Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1 Guessing Game • • • • Generate random int between 1 and 10 Prompt user for guess Keep prompting as long as guess incorrect Tell user guess correct While Loop • Execute list of statements while some condition is true – Keep executing those statements until condition is false • Syntax: Loop back to condition at end of loop Condition true while condition: first statement inside loop Condition … false last statement inside loop first statement after loop • Statements in loop indicated with indentation 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! 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! Guessing Game Code 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 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 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 Improved Guessing Game Code
© Copyright 2026 Paperzz