Python If Else Tutorial 🎯

beginner
12 min

Python If Else Tutorial 🎯

Welcome to our comprehensive guide on Python's If Else statements! This tutorial is designed for beginners and intermediate learners, covering the basics, advanced examples, and real-world applications. Let's dive in!

What is an If Else Statement in Python? 📝

An If Else statement is a conditional statement that allows your Python code to make decisions based on certain conditions. It's a fundamental building block for creating dynamic and intelligent programs.

python
if condition: # Code to execute if condition is True else: # Code to execute if condition is False

Understanding the If Else Structure 💡

  1. Condition: This is a test that Python performs. It can be any expression that evaluates to True or False.
  2. Code to execute if condition is True: This block of code will run if the condition is True.
  3. Code to execute if condition is False: This block of code will run if the condition is False.

Basic If Else Examples 📝

Let's look at some simple examples to understand how the If Else statement works:

python
age = 17 if age >= 18: print("You are an adult.") else: print("You are a minor.")

In the above example, we check if the user's age is 18 or above. If true, it prints "You are an adult.", otherwise it prints "You are a minor."

If...Elif...Else Statement 💡

You can use multiple elif (short for "else if") statements to test multiple conditions. The first true condition will be executed.

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

In this example, we check if the user's age is 18 or above (adult), if not, we check if the user's age is 16 or above (teenager), and if not, the user is a child.

Quiz 🎯

Quick Quiz
Question 1 of 1

Given the following code, what will be the output?

Stay tuned for more advanced examples and practical applications of Python's If Else statements in our next lessons! 🚀