New to Programming? No Worries! Start Learning Python from Scratch — Part 2: Mastering Python Conditional Statements

Rohollah
Python Mastery for Beginners
6 min readAug 12, 2024

Welcome to the second part of our Python programming series! In this article, we’ll dive into the core concepts of conditional statements, which are crucial for making decisions in your code. From basic “if-else” statements to more advanced topics like nested conditions, multiple conditions, ternary operators, and even the new “case match” feature, this guide will help you gain a solid understanding of how to control the flow of your Python programs. Whether you’re a complete beginner or looking to strengthen your skills, you’ll find everything you need to master conditional logic in Python.

Complete Python Conditional statements In One Video

The Simplest Conditional Structure: If Statement

In Python, if, else, and elif are used to control the flow of a program by making decisions based on conditions.

If Statement

The “if” statement checks a condition and executes a block of code only if that condition is true.

age = 18

if age >= 18:
print("You are an adult.")

This code checks if the variable age is 18 or older and prints "You are an adult." if the condition is true.

If Else Statement

The “if else” statement allows the program to choose between two blocks of code, executing one if the condition is true and the other if it’s false.

age = 16

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

This code checks if the variable age is 18 or older; if true, it prints "You are an adult.", otherwise, it prints "You are a minor.

If Elif Statement

The “if elif” statement lets the program evaluate multiple conditions in sequence, executing the first block where the condition is true, with an optional else block for when none of the conditions are met.

age = 20

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

This code evaluates the value of age, printing "You are a child." if under 13, "You are a teenager." if between 13 and 17, and "You are an adult." if 18 or older.

To Learn More About Python Control Flow Visit This Link

“What is the difference between a ‘try-except’ statement and an ‘if-else’ statement in the Python language?” | by Luqman Ilman Muhammad | Medium

Nested Conditions

Allow you to place an if statement inside another if statement, creating layers of decision-making within your code. This structure is useful when you need to check additional conditions only if a previous condition is true. By nesting conditions, you can create more specific and complex logic flows, enabling your program to handle a variety of scenarios with precision.

Nested If Statement
Nested If Statement
age = 20
is_student = True

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

The code first checks if the age is 18 or older; if true, it then checks if the person is a student. If both conditions are met, it prints “You are an adult student.” If the person is not a student but is still 18 or older, it prints “You are an adult.” If the age is less than 18, the code bypasses the nested condition and simply prints “You are a minor.”

Multiple Conditions

Multiple Conditions allow you to evaluate more than one condition at the same time using logical operators like and, or, and not. This helps in creating complex decision-making scenarios within a single if statement

age = 20
is_student = True

if age >= 18 and is_student:
print("You are an adult student.")

The code above checks whether both conditions — being 18 or older and being a student — are true, and if so, it prints “You are an adult student.”

Ternary Condition Operator

In Python is a shorthand way to write an if-else statement in a single line, making the code more concise and readable.

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)

The above code checks if age is 18 or older; if true, it assigns "Adult" to status, otherwise it assigns "Minor", and then prints the result

ASSERT

The assert statement in Python is used to test if a condition is true. If the condition is false, the program will raise an AssertionError, which can be helpful for debugging by ensuring certain conditions hold true during execution. It's commonly used to catch bugs early by verifying assumptions in the code.

x = 10
assert x > 0, "x should be greater than 0"
print("x is positive.")

In the above example, the assert statement checks if x is greater than 0. If this condition is true, the program continues to execute and prints "x is positive." If the condition is false, it raises an AssertionError with the message "x should be greater than 0.

List Comprehension

List Comprehension is a concise way to create lists in Python by applying an expression to each item in an iterable, optionally including a condition to filter items. It allows for more readable and efficient code compared to traditional loops.

Lets look at someexamples:

1. Squaring the elements of a list using list comprehension.

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers if x % 2 == 0]
print(squares)

In the above example, the code creates a new list squares containing the squares of even numbers from the numbers list, using list comprehension to achieve this in a single line.

2 . Filtering elements from a list using list comprehension.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)

The above code uses list comprehension to create `even_numbers`, a list containing only the even elements from the original `numbers` list by filtering out the odd ones.

List comprehension with nested conditions

List comprehension with nested conditions lets you apply multiple filters or transformations to list elements in a single, concise line of code, enabling more efficient and readable processing of complex criteria.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_or_odd = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print(even_or_odd)

The above code uses list comprehension to create a list, `even_or_odd`, which labels each number in `numbers` as “Even” or “Odd” based on whether it’s divisible by 2. The final list is then printed, showing the even or odd status of each number.

The result of the code is :

# Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

To Learn More About Python List Comprehension visit this link

Python List Comprehension Is Not Just Syntactic Sugar | by Christopher Tao | Towards Data Science

Match Case

Is a feature introduced in Python 3.10 that allows for more readable and structured decision-making through pattern matching, similar to switch-case statements in other languages. It enables you to match values or patterns and execute specific blocks of code based on the matched case, making it easier to handle complex branching logic in a clean and organized way.

command = "start"

match command:
case "start":
print("Starting the process.")
case "stop":
print("Stopping the process.")
case "pause":
print("Pausing the process.")
case _:
print("Unknown command.")

In the above example, the match statement checks the value of command and executes the corresponding case block. If command is "start", it prints "Starting the process."; if it's "stop", it prints "Stopping the process."; if it's "pause", it prints "Pausing the process." If command doesn't match any of the specified cases, the default case (case _:) prints "Unknown command.

To Learn More About Python Match Case Visit This Link

Did You Know — We Have Match Case Blocks In Python? | by Liu Zuo Lin | Level Up Coding (medium.com)

--

--