Sunday, February 18, 2018

While Loops

While Loops are conditions that as long as a certain condition is True.

index = 1
while index <= 5:
       print(index)
       index+ = 1 #same as index = index +1

Output:
1
2
3
4
5

Using While to Quit:
name= "\nWhats your name?"
prompt += "\nEnter 'q' to end the program. "



name = ""
while name!= 'q':
   name= input(prompt)
   print(""Hello: " + message)

Using a flag:
name= "\nWhats your name?"
prompt += "\nEnter 'q' to end the program. "
myFlag = True

while myFlag:
         message = input(prompt) 
         if message =='q':
           myFlag =False
         else:
           print(""Hello: " message)

Using break to exit a Loop:
name= "\nWhats your name?"
prompt += "\nEnter 'q' to end the program. "
while myFlag:
         message = input(prompt) 
         if message =='q':
           break;
         else:
           print(""Hello: " message)

Using Continue:
index = 0
while index < 10:     
      index = index + 1     
      if index % 2 == 0:         
            continue;
      print(index)



      
Output: 
1
3
5
7
9



        
         
                


No comments:

Post a Comment