Learn Python: The Fundamentals

In Python, control flow lets your program make decisions and follow different paths depending on the situation. The most common control flow tool is the if statement, which checks whether a condition is True. If it is, Python runs the code inside that block. You can add more conditions using elif, and finish with else to handle anything that didn’t match earlier checks.

 

Basic Branching

Here’s a simple example that checks someone’s age and prints a message based on their age group:

 

age = 18

if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")

 

Each condition is tested in order. As soon as one is True, Python runs that block and skips the rest.

 

Chaining Conditions & Common Patterns

When checking for ranges, always put the most specific or highest threshold first. This way, you avoid skipping conditions or creating unreachable branches. You can also keep your code cleaner by printing or returning results early, especially in longer chains.

 

score = 87

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

print("Grade:", grade)

 

This structure is easy to read and expands well if you need to add more grading bands later.

 

Interactive Exercise: Grade Checker

Let’s put this into practice. Change the value of score to see how the logic flows. Try values like 99, 88, or 45. You can also add a new condition—for example, print “A+” if the score is 97 or above.

 


# Try: 99, 90, 88, 72, 61, 45
score = 75

if score >= 97:
print("Grade: A+")
elif score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D/F")

 
Put the highest scores first so they match before broader categories.
 

Control flow is what makes your programs smart — it helps them adapt to different inputs and make decisions. Mastering if, elif, and else is the foundation for building logic in all kinds of applications, from games to data analysis.