๐ Python for Teens & Beginners ยท Lesson 4 of 7
Conditions: if and else
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
- Ask for a number and say whether it is even or odd
- Write a letter-grade program with if/elif/else
- Ask for a password and print โWelcomeโ only if it matches
- Ask for the temperature (ยฐF) and suggest what to wear
๐ง Quick quiz
Answer all 4 questions correctly to mark this lesson as done.
0 of 4 correct
All lessons in Python for Teens & Beginners
- ๐ 1. Your first programprint, quotation marks, and error messages
- ๐ฆ 2. Variables and inputStore information and ask the user
- ๐งฎ 3. Math in PythonOperators, division, remainder and powers
- ๐ 4. Conditions: if and elseThe program decides by itself
- ๐ 5. Loops: for and whileRepeat code without copying it
- ๐ 6. ListsMany values in one variable
- ๐ฒ 7. Project: a guessing gameThe computer picks a number, and you guess