While Loop in Python

Level 234 keystrokes

This prints numbers from 3 down to 1. The while loop continues as long as n is greater than 0, decreasing n by 1 each time.

Python code

# Initialize variable n with value 3
1n = 3
# while loop repeats as long as the condition is True
# n > 0 checks if n is still positive
2while n > 0:
# Print the current value of n
3 print(n)
# n -= 1 is shorthand for n = n - 1 (decreases n by 1)
4 n -= 1

Output

3
2
1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • =× 2
  • -× 1
  • :× 1
  • (× 1
  • )× 1
  • >× 1

More Python examples at level 2

← Python typing practice