Download presentation
Presentation is loading. Please wait.
Published byAnis Parsons Modified over 9 years ago
1
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1
2
Guessing Game Generate random int between 1 and 10 Prompt user for guess Keep prompting as long as guess incorrect Tell user guess correct
3
While Loop Execute list of statements while some condition is true – Keep executing those statements until condition is false Syntax: while condition: first statement inside loop … last statement inside loop first statement after loop Statements in loop indicated with indentation Condition true Loop back to condition at end of loop Condition false
4
While Loop Design What is condition to be tested each time loop starts? What must be done before the while loop? – Usually something to get initial value to be tested in condition What must be done inside the while loop? – What code should be repeated as long as condition true? – Must be something that can eventually make the condition false!
5
Guessing Game Design What is condition to be tested each time loop starts? – User guess not correct – guess != random number generated What must be done before the while loop? – Need a value for guess and random number – Generate random number random.randint(1, 10) generates random int from 1 to 10 – Prompt user for their first guess What must be done inside the while loop? – Tell user guess incorrect – Prompt user for next guess Without this, will never exit loop!
6
Guessing Game Code
7
Guessing Game Trace Computer generates 9 as number Prompt user for first number 5 != 9 true so enter loop 1 != 9 true so enter loop again 8 != 9 true so enter loop again 2 != 9 true so enter loop again 6 != 9 true so enter loop again 9 != 9 false so exit loop
8
Infinite Loops What if loop never exits? Usual cause: Nothing in loop body can change condition to false Can exit program manually with Ctrl-C
9
Branches and Loops Can nest complex code inside a loop Example: Hints in guessing game – If guess less than number, print “too low” – If guess greater than number, print “too high” Must be placed inside loop, since done for each wrong guess Must be executed before prompting for next guess
10
Improved Guessing Game Code
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.