Python has two types of loops - for loops and while loops. If for loops iterate over a list (iterable) element by element, a while loop, on the other hand, repeats statements inside its body as long as the condition in the while statement is satisfied. In that sense, it’s very similar to an if statement. It executes the statements inside the while loop in case the condition is satisfied:
i = 0
while i < 5:
print('Current i is:', i)
i += 1
print('Done')
Current i is: 0
Current i is: 1
Current i is: 2
Current i is: 3
Current i is: 4
Done
The program on the left will print this output
Initially, i is assigned to be 0 ⇒ i = 0.
Then, the program checks if i < 5 and as 0 < 5, it steps inside the while body
The program prints Current i is: 0
The variable i increases its value by 1 turning into i = 1
Then, the program jumps again to the condition and checks if i < 5. As 1 < 5 ⇒ it steps inside the while body
The program prints Current i is: 1
The variable i increases its value by 1 turning into i = 2
The program checks if i < 5. 2 < 5 ⇒ steps inside the while body
The program prints Current i is: 2
The variable i increases its value by 1 turning into i = 3
The program checks if i < 5. 3 < 5 ⇒ steps inside the while body
The program prints Current i is: 3
The variable i increases its value by 1 turning into i = 4
The program checks if i < 5. 4 < 5 ⇒ steps inside the while body
The program prints Current i is: 4
The variable i increases its value by 1 turning into i = 5
The program checks if i < 5. 5 = 5 ⇒ The program steps outside the while loop and prints Done
Challenge
Given a positive integer n. Print the value of n as long as it’s greater than 0 and divide it by 2 (take only the whole part).