Presentation is loading. Please wait.

Presentation is loading. Please wait.

Flow Control II While Loops.

Similar presentations


Presentation on theme: "Flow Control II While Loops."— Presentation transcript:

1 Flow Control II While Loops

2 Greeter Revisited name = input("What's your name?") if name != "": print('Hello,', name, '!') else: print("You didn't enter a name!") This program handles missing input, but... We want to give a user who fails to enter a name another chance!

3 A Second Chance... ?! name = input("What's your name?") if name != "": print('Hello,', name, '!') else: print("You didn't enter a name!") Coding Horror

4 Looping Revisited You know how to repeat a section of code a set number of times Sometimes, you need a way to repeat a section of code as long as a condition holds The while loop repeats a section of code until its condition becomes false: print("Countdown:") num = 5 while num > 0: print(num, '...') num = num - 1 print("Blast off!") Countdown: 5 4 3 2 1 Blast off!

5 Can We Use a While Loop? name = input("What's your name?") if name != "": print('Hello,', name, '!') else: print("You didn't enter a name!") Challenge: Rewrite this program using a while loop so the user gets repeated chances to enter a name.

6 Requiring a Valid Entry
name = input("What's your name?") while name == "": print("You didn't enter a name!") print('Hello,', name, '!')

7 The Formatter We're writing a program to format the user's hard drive
Before we do the deed, we want the user to confirm: confirm = input("Should I format your hard drive (Y/N)?") if confirm == 'Y': print('Formatting drive...') elif confirm == 'N': print('We won't format your drive.') else: print('Invalid entry.') Challenge: Require the user to enter a Y or N, prompting repeatedly until they do so. For those who know about Boolean logic, do it without Boolean operators

8 Requiring a Valid Entry II
valid = False while valid == False: confirm = input("Should I format your hard drive (Y/N)?") if confirm == 'Y': valid = True elif confirm == 'N': else: print('I didn't understand your response. Please enter Y or N.')


Download ppt "Flow Control II While Loops."

Similar presentations


Ads by Google