Python Series track

Week 04 · Basic Track

Week 4 — Conditionals

Control program flow with if/elif/else blocks. Learn nested conditions, the ternary expression, and how to structure complex decision logic.

Basic Track2 min readFree lesson

Level: Basic | Prerequisite: Week 3 (Comparison/Logic Operators, Input/Output)

Learning Goals

  • Understand the flow of if, elif, else
  • Follow indentation rules
  • Use nested conditional statements
  • Know the concept of truthy/falsy values

1. if Statement

The indented block is executed only when the condition is True.

score = 85
if score >= 60:
    print("Passed!")

Indentation is 4 spaces as the standard. VS Code automatically converts Tab to 4 spaces.

2. if-else

score = 50
if score >= 60:
    print("Pass")
else:
    print("Fail")

3. if-elif-else

Check multiple conditions in order. Only the first True branch is executed, the rest are skipped.

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

4. Nested Conditional Statements

A conditional statement inside another conditional statement. If it becomes too deep, readability drops, so limit to 2-3 levels.

age = 17
if age >= 18:
    if age >= 65:
        print("Preferential route")
    else:
        print("Adult")
else:
    print("Minor")

5. Conditional Expression (Ternary Operator)

Handle branches in a single line. Use only in simple cases.

n = 7
result = "Even" if n % 2 == 0 else "Odd"
print(result)   #Odd

6. Truthy/Falsy Values

In if condition:, 0, "", [], None, False are all considered false.

if "":
    print("Not running")
if 0:
    print("Not running")
if "hello":
    print("Executed")

Key Examples (examples/)

File Content
01_if_else.py Basic if/else
02_grade.py if/elif/else Grade Evaluation
03_nested.py Nested Conditional Statements
04_truthy.py Truthy/Falsy Behavior

⚠️ Common Mistakes

  1. Missing or inconsistent indentation
    if x > 0:
    print("Positive")   # IndentationError
    

→ Always use proper indentation. Mixing tabs and spaces can cause invisible errors.

  1. = instead of ==

    if x = 5:        # SyntaxError
    if x == 5:       #Normal
    
  2. else if instead of elif Python only supports elif. (Different from Java/C's else if)

  3. Use only if in all branches

    if score >= 90:  # A
        print("A")
    if score >= 80:  #If 80~89, both A and B are printed!
        print("B")
    

→ Use elif for exclusive branches.

  1. Force parentheses in conditions
    if (x > 0):    #Works but not recommended
    if x > 0:      #Python style
    

❓ FAQ

Q1. What if there are multiple conditions combined? A. Use and and or. Chained comparisons like if 0 < x < 100: are also possible (Python-specific).

Q2. How many elif can be used? A. No limit. However, if it gets longer than 5, consider other structures like dictionary mapping.

Q3. Is there no switch-case statement? A. From Python 3.10+, match-case has been added. At the beginner level, if/elif is sufficient.

📝 Exercises (exercises/)

  • exercise1.md — Grade calculator
  • exercise2.md — Leap year checker
  • exercise3.md — Rock-paper-scissors (one round)

Next Week

Week 5. Loops — Automatically perform the same action multiple times

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_if_else.pyPython
score = int(input("Score:"))

if score >= 60:
    print("Passed!")
else:
    print("Fail...")
examples/02_grade.pyPython
score = int(input("Score:"))

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Credits: {grade}")
examples/03_nested.pyPython
age = int(input("Age:"))
has_ticket = input("Have a ticket (y/n):") == "y"

if age >= 18:
    if has_ticket:
        print("Entrance allowed")
    else:
        print("Please purchase a ticket")
else:
    print("Minors not allowed")
examples/04_truthy.pyPython
#0, "", [], None, False are all treated as false
values = [0, "", [], None, False, 1, "hi", [1, 2], True]

for v in values:
    if v:
        print(f"{v!r:>10}: Truthy")
    else:
        print(f"{v!r:>10}: Falsy")

Assignment

Goal

Receive a score (0~100) as input and output the grade.

Grade Criteria

  • 90 and above: A
  • 80~89: B
  • 70~79: C
  • 60~69: D
  • 59 and below: F

Input/Output Example

Score: 85
Grade: B

Challenge

  • If below 0 or above 100, output 'Invalid score'

Assignment 2. Leap Year Checker

Goal

Receive a year as input and output whether it is a leap year.

Leap Year Rules

  • If it is a multiple of 4, it is a leap year
  • However, if it is a multiple of 100, it is a common year
  • However, if it is a multiple of 400, it is a leap year again

Input/Output Example

Year: 2024
The year 2024 is a leap year.

Year: 2100
The year 2100 is a common year.

Year: 2000
The year 2000 is a leap year.

Assignment 3. Rock-Paper-Scissors (1 round)

Goal

The user and the computer play rock-paper-scissors once.

Requirements

  • User input: 'Rock', 'Paper', 'Scissors'
  • The computer is random.choice(["Scissors", "Rock", "Paper"])
  • Output the result: Win/Loss/Draw

Input/Output Example

Choice: Scissors
Computer: Paper
User wins!

Challenge

  • For invalid input, output 'Invalid input'
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
score = int(input("Score:"))

if score < 0 or score > 100:
    print("Incorrect Score")
elif score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")
solution2.pyPython
year = int(input("Year:"))

if year % 400 == 0:
    is_leap = True
elif year % 100 == 0:
    is_leap = False
elif year % 4 == 0:
    is_leap = True
else:
    is_leap = False

label = "Leap year" if is_leap else "Common year"
print(f"The year {year} is a {label}.")
solution3.pyPython
import random

CHOICES = ["Scissors", "Rock", "Paper"]
WIN = {"Scissors": "Paper", "Rock": "Scissors", "Paper": "Rock"}

user = input("Choose (Scissors/Rock/Paper):")
if user not in CHOICES:
    print("Invalid input")
else:
    com = random.choice(CHOICES)
    print(f"Computer: {com}")
    if user == com:
        print("Draw")
    elif WIN[user] == com:
        print("User wins!")
    else:
        print("Computer wins!")

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now