A while loop repeats code until the condition is met. Unlike for loops, the number of iterations in it may be unknown. A while loop always consists of a condition and a block of code.
A while loop ends if and only if the condition is true, in contrast to a for loop that always has a finite countable number of steps. For illustration: If you create a program that waits for network connectivity, you could use a while loop.
Type this code:
#!/usr/bin/python x = 3 while x < 10: print(x) x = x + 1
Executes the code below until the condition x < 10 is met. Unlike a for loop, the iterator i is increased in the loop.
You should see
Try the exercises below
1. Make a program that multiples itself by 2 until the number is large than 128 2. Ask a number until its the correct one
After completing these continue with the next exercise.
1. Make a program that multiples itself by 2 until the number is large than 128
num = 2 while num < 128: num = num * 2 print(num)
2. Ask a number until its the correct one (Python 3)
num = int(input('Enter number: ')) while num != 12: num = int(input('Enter number: '))