๐Ÿ Python for Teens & Beginners ยท Lesson 4 of 7

Conditions: if and else

Google Classroom

The program decides by itself.

if / else

age = int(input("Age: "))
if age >= 13:
    print("You can make an account")
else:
    print("Ask a parent first")

The colon : and the indentation (4 spaces) matter. Indented lines belong to the if or the else.

Comparisons

==Equal to (two = signs!)
!=Not equal to
< >Less than, greater than
<= >=Less/greater than or equal

elif: more choices

score = int(input("Score: "))
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("Keep practicing!")

Python checks from the top and runs only the first true branch.

and, or, not

if temp > 60 and not raining:
    print("Go to the park")

Tip

๐Ÿ’ก The most common beginner bug: if x = 5 instead of if x == 5. One = stores, two == compares.

โœ๏ธ Practice: your turn

  1. Ask for a number and say whether it is even or odd
  2. Write a letter-grade program with if/elif/else
  3. Ask for a password and print โ€œWelcomeโ€ only if it matches
  4. Ask for the temperature (ยฐF) and suggest what to wear

โœ๏ธ Run Python in your browser, no install โ†—

๐Ÿง  Quick quiz

Answer all 4 questions correctly to mark this lesson as done.

1. Which compares two values?
2. What marks the lines inside an if?
3. score = 85. Which prints with the code above?
4. What does != mean?

0 of 4 correct