90 likes | 126 Views
Control Structures. WHILE Statement. Looping. S. E. Q. U. REPITITION. …or Iteration. E. N. …a step or sequence of steps that are repeated until some condition is satisfied. C. E. Sometimes we want to repeat a bit of code many times. We use loops to achieve this!
E N D
Control Structures WHILE Statement Looping
S E Q U REPITITION …or Iteration E N …a step or sequence of steps that are repeated until some condition is satisfied. C E
Sometimes we want to repeat a bit of code many times. We use loops to achieve this! For example, if you wanted to output the same statement 3 times, we would use a FOR loop. This is because we know the number of iterations. RULE: use a FOR loop if the number of iterations is known. What if we don’t know the number of iterations? For example, iterate until the user enters a specific value…
WHILE Loop Condition ? If condition is true Execute code block Like if statements, while loops evaluate whether a condition is true or false! The block is evaluated (iterated) until the condition becomes false. If condition is false
Looping mechanisms in python… In Python, there are 2 looping mechanisms… WHILE LOOP LOOPS for a an unknown number of times! For example, output HELLO WORLD ? times until user types quit. FOR LOOP LOOPS for a specified number of times! For example, output HELLOW WORLD 3 times
Syntax while <condition>: <block of code executed> Example, prompt the user to guess the password (dalriada) >>>password = (‘dalriada‘) guess = input(‘Please enter password: ‘) while guess != password: print(‘Access denied') guess = input(‘Please try again’) print(‘Access granted’)
What will be output here? >>>number =1 while number < 5: print(number*number) number = number + 1
What will be output here? >>>while x < 5: print(‘Hello’)