Python Tutorial for Beginners #4: Conditionals - Learn Control Flow with if/else Statements in Python


So far, our Python programs have been pretty basic - they run from top to bottom, execute every line, and that's it. Imagine you are getting ready in the morning. You check the weather - if it’s raining, you grab an umbrella. If it’s cold, you put on a jacket. You repeat the decision making process everyday. Your Python programs can do the same thing. The real programs need to be a smarter, as they need to make choices and repeat actions. Today, we are going to give your code a brain! In this tutorial, you will master the essential control flow tools that every Python programmer needs:
Conditional Statements: if, elif, and else to make decisions
Magic-Case Statements: Python's modern approach to handling multiple conditions
By the end, you'll build programs that can think, decide, and perform actions automatically!, so let’s get started.
Conditional Statements
Remember our morning routine example? Let's turn that into actual Python code. We need our program to make decisions based on different conditions.
if statement
An if statement is like asking a yes/no question to your program. If the answer is yes(True), Python does something. If the answer is no (False), Python skips that code.
Break down of each part:
if - the keyword
condition - something that evaluates to True or False
: - the colon (required)
Indentation - 4 spaces (very important in Python as it does not uses curly braces {}). The code written in indentation is considered as the code to be executed when the condition is met.
An if statement is like asking a yes/no question to your program using the comparison operators we learned earlier. Remember ==, !=, <, >, <=, >=? These operators help us create conditions that evaluate to True or False.
weather = "rainy"
if weather == "rainy":
print("Take an umbrella!")
#This setion of code will execute only when the condition is matched
#If the condition is not matched then this section of code will never get executed
print("Have a great day!")
#This line will always get executed no matter, the condition is met or not
Output:
Take an umbrella!
Have a great day!
weather = "sunny"
if weather == "rainy":
print("Take an umbrella!")
#This setion of code will execute only when the condition is matched
#If the condition is not matched then this section of code will never get executed
print("Have a great day!")
#This line will always get executed no matter, the condition is met or not
Output:
Have a great day!
name = "IronWill"
if name == "IronWill":
print("Hello IronWill!, We are into if condition")
print("We are out of if condition")
Output:
Hello IronWill!, We are into if condition
We are out of if condition
name = "Smith"
if name == "IronWill":
print("Hello IronWill!, We are into if condition")
print("We are out of if condition")
Output:
We are out of if condition
if - else statements
So far, our if statements only do something when the condition is True. But what if we want our program to do something different when the condition is False? This is where if - else statements come to rescue. An if-else statement gives your program two paths to choose from:
Path 1: What to do if the condition is True
Path 2: What to do if the condition is False
Break down of each part:
if - the keyword
condition - something that evaluates to True or False
: - the colon (required)
else - the keyword when condition is not met
Indentation - 4 spaces (very important in Python as it does not uses curly braces {}). The code written in indentation is considered as the code to be executed inside if or else depending the condition is met or not.
In if - else conditions, either of one block of code gets executed ( be it the if block or the else block), never both. Also both the blocks must be indented in the same way ( 4 spaces ). It is important to note that else does not need a condition because it automatically starts executing when if condition is not matched. The code after the if - else block which is not indented
temperature = 15
if temperature > 20:
#This code block will be executed only when if condition is met
print("It's warm outside!")
print("Perfect for a picnic!")
else:
#This code block will be executed only when if condition is not met
print("It's cool outside!")
print("Maybe wear a sweater!")
print("Have a great day!") # This always runs
Output:
It's cool outside!
Maybe wear a sweater!
Have a great day!
temperature = 30
if temperature > 20:
#This code block will be executed only when if condition is met
print("It's warm outside!")
print("Perfect for a picnic!")
else:
#This code block will be executed only when if condition is not met
print("It's cool outside!")
print("Maybe wear a sweater!")
print("Have a great day!") # This always runs
Output:
It's warm outside!
Perfect for a picnic!
Have a great day!
age = int(input("Please enter your age: "))
if age >= 18:
print("You are eligible to vote")
else:
print("Sorry! You are not eligible to vote")
Output:
Please enter your age: 17
Sorry! You are not eligible to vote
if - elif - else chain
What happens when you need to check more than two possibilities? Let's say you're building a grading system, in that:
score = 85
if score>=90:
print("Grade: A")
else:
print("Grade: F")
This is not right. What about B, C, D grades? Where are they and how can they be represented? Using just if-else forces us into only two categories, but in real life there can be multiple possibilities. Here comes if-elif-else chains to our rescue that have elif that lets you check multiple conditions in sequence. It is short form of "else if" and allows you to handle many different scenarios.
if - checks the first condition
elif - checks additional conditions (you can have multiple elif statements)
else - handles everything that wasn't caught by if or elif. You can also omit else if you want to, but it allows you to have the generalised condition, when all the other conditions fail.
: - colon after each condition (required)
Indentation - 4 spaces for each code block
It is important to note that only one block of code gets executed no matter how many conditions you have in your if - elif - else chain.
Let us look at the most popular grading example using if - elif - else chain:
score = 85
if 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")
print("End of Grading System")
Output:
Grade: B
How it works?
Python checks conditions from top to bottom:
First: Is score >= 90? If yes, execute that block and skip the rest
Second: If not, is score >= 80? If yes, execute that block and skip the rest
Third: If not, is score >= 70? If yes, execute that block and skip the rest
Fourth: If not, is score >= 60? If yes, execute that block and skip the rest
Finally: If none of the above, execute the else block
It is always important to start with the most specific or highest conditions first. Let us look at that with the help of following code snippet:
score = 95
if score >= 60: # This catches ALL passing scores first!
print("You passed!")
elif score >= 90: # This will NEVER run because 95 >= 60 is already True!
print("Excellent!")
elif score >= 80: # This will NEVER run!
print("Great!")
Here you will get the output as “You passed!“ , despite putting the conditions for score>=90 due to improper order of conditions. Here it will first check if the score >=60 or not? If it is >60 (which in our case is) then we simply execute its’ code block and move out of the conditional statements which would give us wrong output here. So order of the conditions is important and always start with the most specific or highest conditions first. The correct way for above conditions would be:
if score >= 90:
print("Excellent!")
elif score >= 80:
print("Great!")
elif score >= 60:
print("You passed!")
Nested if - else statements
Sometimes you need to make a decision inside another decision. Think of it like this: If it's raining, then check if I have an umbrella. If I have an umbrella, go outside. If I don't have an umbrella, stay inside. This is called nesting - putting one if-else statement inside another if-else statement. And not just if - else statement, you can put one if-elif-else inside if or vice versa.
Inner if-else belongs to the outer if block
Each if needs its matching else at the same indentation level
Indentation levels matter - Each nested level needs 4 more spaces and it is important to maintain the indentation level. Because if indentation alters, then your program could produce false results.
Now that you understand nested conditionals, let's see them in action with a practical example:
weather = input("What's the weather? (Sunny/Rainy/Snowy): ")
if weather == "Sunny":
temperature = int(input("What's the temperature? "))
if temperature >= 25:
activity = input("Beach or Park? ")
if activity == "Beach":
swimsuit = input("Do you have a swimsuit? (Yes/No): ")
if swimsuit == "Yes":
print("Perfect beach day! Don't forget sunscreen")
else:
print("Get a swimsuit and go to the beach!")
else:
print(" Great day for a park picnic!")
else:
print("Nice day for a walk, but might be a bit cool.")
elif weather == "rainy":
print("Perfect day to stay inside!")
else:
print("Bundle up if you go outside!")
Output:
What's the weather? (Sunny/Rainy/Snowy): Sunny
What's the temperature? 30
Beach or Park? Beach
Do you have a swimsuit? (Yes/No): Yes
Perfect beach day! Don't forget sunscreen
When to avoid nested if else statements?
When there are too many levels especially when there are more than 3-4 levels because it gets confusing.
If you have simple conditions then use elif instead
In case of independent statements, use separate if statements.
Q. Nested vs elif - When to use which?
Use elif when conditions are mutually exclusive, and use nested when one condition depends on the another condition.
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
#These are different conditions, yes they are similar but none of them depends on one another.
# So we can use elif
has_money = True
item_available = True
if has_money:
if item_available:
print("Purchase successful!")
else:
print("Item out of stock!")
else:
print("Insufficient funds!")
# Here the purchase is successful only when item_available and has_money both are true.
# has_money and item_available depend on each other, item_available is checked only when has_money=True
# Hence they both are not mutually exclusive and therefore we use nested if else
Match-Case Statements : Switch Statements in Python
The match-case statement is Python's way of checking a value against multiple options, just like a switch statement in other programming languages. Think of it as a cleaner way to write long if-elif chains. You give it a value, and it checks that value against different cases until it finds a match, then runs the code for that case.
match: The keyword that starts the statement - like saying "check this value"
case: Each option you want to check against - like saying "if it equals this"
value: The thing you're checking (variable, number, string, etc.)
pattern: What you are comparing the value to (could be a number, string, or more complex)
_ (underscore): The "catch-all" case is a default case and runs if nothing else matches (like else). It is not mandatory to use this, but it's recommended as it handles unexpected values that don't match any other case.
value = int(input("Please enter the day number(1-7): "))
match (value):
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursay"
case 5:
return "Friday"
case 6:
return "Saturday"
case 7:
return "Sunday"
case _:
return "Please enter valid number"
Output:
Please enter the day number(1-7): 6
Saturday
Match-case statements can be more efficient than long if-elif chains, especially when you have many conditions to check and the patterns are simple value comparisons. However, for simple cases with just 2-3 conditions, if-elif might be more readable.
Today we've covered Python's complete decision-making toolkit - from simple if statements to nested if-else chains, and finally to the powerful match-case statement. Start with basic if statements for single conditions, progress to if-elif-else chains for multiple options, and use match case when you have many conditions to check against a single value. Remember to keep your conditions simple, use meaningful variable names, and always consider edge cases with default handlers.
The key to mastering these concepts is practice, practice, and more practice! Try creating your own examples, modify the provided code snippets, and experiment with different scenarios. The more you code, the more natural these concepts will become. In tomorrow's blog will dive into Python loops where we'll learn how to repeat actions and automate repetitive tasks efficiently. Keep practicing, and you'll soon be able to master the art of controlling program flow in Python! Stay Tuned
Enjoyed today’s blog? Don’t forget to like, share it with your friends, and leave your valuable feedback – it really helps! Your support keeps the content coming.
Keep practicing and Happy Coding! 🚀
Subscribe to my newsletter
Read articles from Raj Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Raj Patel
Raj Patel
Hey there! I'm Raj Patel, a passionate learner and tech enthusiast currently diving deep into Data Science, AI, and Web Development. I enjoy turning complex problems into simple, intuitive solutions—whether it's building real-world ML projects like crop disease detection for farmers or creating efficient web platforms for everyday use. I’m currently sharpening my skills in Python, Machine Learning , Javascript and love sharing what I learn through blogs and open-source contributions. If you're into AI, clean code, or building impactful tech—let’s connect!