Programming

if, for and while in Python: conditions and loops

Making decisions with conditions and repeating work with loops.

All lessons · Python lessons: learn from scratch

if / elif / else

If the condition is true, the indented block runs. In Python, indentation (4 spaces) is part of the syntax.

score = 72
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("C")

Use == to compare; a single = only assigns.

The for loop

for repeats a known number of times: over a list, or with range.

for i in range(3):
    print(i)        # 0 1 2

for fruit in ["apple", "pear"]:
    print(fruit)

The while loop

while runs as long as the condition is true. Make sure it eventually becomes false, or the loop never ends. break stops the loop at once.

n = 3
while n > 0:
    print(n)
    n -= 1
print("go!")

Author: Nibras Code