appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Decisions and loops

Lesson 2 of 410 minBeginner

if, elif, else, for and while.

Python uses indentation (four spaces) to group code. There are no braces.

age = 20
if age >= 18:
    print("adult")
elif age >= 13:
    print("teen")
else:
    print("child")
  • Comparisons: == equal, != different, <, <=, >, >=.
  • Combine with and, or, not.
  • Check membership with in: "a" in "banana" is True.

Careful= assigns a value and == compares. Writing if x = 3: is an error.

for loops

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

for letter in "abc":
    print(letter)

while loops

count = 3
while count > 0:
    print(count)
    count -= 1

Use break to leave a loop early and continue to skip to the next round. Make sure a while loop eventually becomes false, or it runs forever (stop it with Ctrl+C).

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does range(3) produce?
2. How does Python group the lines inside an if block?
3. Which operator compares two values?
4. What does break do inside a loop?

Key terms