1 using the While loop
1 while 5 : print (current_number) 1
2 Let the user choose to quit
" Tell me somthing, and I'll repeat it back to you " "\nenter ' quit ' to endThe program" "and" while " quit': message=input (prompt) if message! ='quit': print (message)
3 Use Flag
" Tell me somthing, and I'll repeat it back to you " "\nenter ' quit ' to endof program"= True while Active: = input (prompt) if'quit': = False Else: print (message)
4 using Break to exit a loop
prompt ="\nplease enter the name of a city that has visited:"prompt+="\ n (enter ' quit ' when you're finished.)" whiletrue:city=input (Prompt)ifCity = ='quit': BreakElse: Print ("I ' d love to go to"+ city.title () +"!")
5 using continue in loops
0 while Ten : 1 if 2 = =0: continue print (Current_number)
6 working with a while loop to work with lists and dictionaries
Unconfirmed_users = ['Alice','Brian','Candace']confirmed_users= [] whileUnconfirmed_users:current_user=Unconfirmed_users.pop () print ("Verifying User:"+current_user.title ()) confirmed_users.append (current_user) print ("\ n The following users have been confirmed:") forConfirmed_userinchConfirmed_users:print (Confirmed_user.title ())
7 Deleting a specific list element
Pets = ['Dog','Cat','Dog','Goldfish','Cat','Rabbit','Cat']print (pets) while 'Cat' inchPets:pets.remove ('Cat') Print (pets)
8 using user input to populate the dictionary
responses ={}polling_active=True whilePolling_active:name= Input ("\ Your name?") Response= Input ("which mountain would climb someday") Responses[name]=Response Repeat= Input ("would another person respond? (Yes or no") ifrepeat = ='No': Polling_active=Falseprint ("\--poll results--") forName,responseinchresponses.items (): Print (name+"would to climb"+ Response +".")
Getting started with Python-while loops