Lesson 2 - Python If Else Explained: Learn Conditional Statements for Beginners

Start learning Python conditional statements with clear examples. Understand how to use if, elif, and else in real scenarios. Use relational and logical operators to write smarter code. Practice online using free Python IDEs like Replit and Google Colab. This beginner-friendly guide helps you code with confidence.

PYTHON

Prof. Leonardo Gomes Guidolin

5/8/20241 min read

What Are Conditional Statements in Python?

Conditional statements allow your Python code to make decisions. By using if, elif, and else, you can execute different blocks of code based on specific conditions. This is essential for creating interactive and dynamic programs.

How to Use if in Python

The if statement runs a block of code only if a condition is true.

age = int(input("Enter your age: "))

if age >= 18:

print("You are an adult.")

If the user enters 18 or more, the message is shown. If not, nothing happens.

Using else for Alternative Outcomes

The else block runs when the if condition is not met.

age = int(input("Enter your age: "))

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

This covers both situations: when the condition is true or false.

Using elif for Multiple Conditions

elif (short for else if) helps test multiple conditions in a clean way.

grade = float(input("Enter your grade: "))

if grade >= 9:

print("Excellent!")

elif grade >= 7:

print("Passed!")

elif grade >= 5:

print("Needs improvement.")

else:

print("Failed.")

This checks a student's grade and prints a message based on the score.

Relational and Logical Operators in Python

You’ll often combine conditional statements with operators:

Relational Operators:
== (equal), != (not equal), >, <, >=, <=

Logical Operators:
and, or, not

Example:

age = int(input("Enter your age: "))

ticket = input("Do you have a ticket? (y/n): ")

if age >= 18 and ticket == "y":

print("You may enter the party!")

else:

print("Entry not allowed.")

Test Your Python Code Online for Free

No installation needed! Try your code using these free platforms:

These tools are great for beginners to learn and practice Python.

Conclusion

Conditional structures like if, elif, and else are crucial for writing flexible Python programs. They help your code react to different scenarios logically. Keep practicing these concepts to become a better Python programmer!