The Python Journey – Chapter III Python Conditionals

python conditionals

Python Conditionals: A Detailed Explanation of If-Else Statements with Examples

The Python Journey gets exciting as we delve deeper in the newer chapters. In the last chapter we looked in the details of Python Variables and Python Data Types. Today we dive in to conditionals. Python conditionals are one of the core features of any programming language, allowing developers to control the flow of the program based on specific conditions. Python’s conditional statements—primarily if, elif (else if), and else—allow us to execute different blocks of code depending on whether a given condition is true or false. We will also look into some more statements that are available in Python 3.10 or later.

In this guide, we’ll explore Python’s conditional statements, their syntax, and provide examples to help you understand how they work.

Table of Contents

Chapter III Python Conditionals (If-Else Statements)

The if Statement

The else Statement

The elif Statement

Nested if Statements.

Conditional Expressions (Ternary Operator)

Logical Operators in Conditional Statements.

Comparison Operators in Conditionals.

pass Statement in Conditionals.

Python with Statement

Python Switch-Case Statements.

Using match-case (Python 3.10+):

Other Statements in Python.

The if Statement

The if statement in Python evaluates a condition (which can be either True or False), and if the condition is True, the block of code associated with the if statement is executed. If the condition is False, the block of code is skipped.

Syntax:

if condition:

    # code to execute if the condition is true

Example:

age = 18

if age >= 18:

    print("You are eligible to vote.")

In this example, the condition age >= 18 is evaluated. If age is greater than or equal to 18, the message “You are eligible to vote.” is printed.

The else Statement

The else statement provides an alternative block of code that is executed if the condition in the if statement evaluates to False. In other words, if the if condition is not met, the else block will run.

Syntax:

if condition:

    # code to execute if the condition is true

else:

    # code to execute if the condition is false

Example:

age = 16

if age >= 18:

    print("You are eligible to vote.")

else:

    print("You are not eligible to vote yet.")

In this case, the condition age >= 18 is False since age is 16. Therefore, the message “You are not eligible to vote yet.” is printed.

The elif Statement

The elif statement (short for “else if”) allows for checking multiple conditions. It comes after an if statement and can be followed by another elif or an else block. It’s useful when you have more than two possibilities to evaluate.

OnePlus Nord CE4 Lite 5G (Super Silver, 8GB RAM, 128GB Storage)

Syntax:

if condition1:

    # code to execute if condition1 is true

elif condition2:

    # code to execute if condition2 is true

else:

    # code to execute if neither condition1 nor condition2 are true

Example:

score = 85

if score >= 90:

    print("Grade: A")

elif score >= 80:

    print("Grade: B")

elif score >= 70:

    print("Grade: C")

else:

    print("Grade: F")

In this example:

  • The if condition checks if the score is 90 or above (which is False).
  • The elif condition checks if the score is 80 or above (which is True), so the message “Grade: B” is printed. No further conditions are evaluated once a match is found.

Nested if Statements

Python allows you to nest one if statement inside another. This is useful when you need to check multiple related conditions in a hierarchical manner.

Syntax:

if condition1:

    if condition2:

        # code to execute if both condition1 and condition2 are true

Example:

age = 20

has_id = True

if age >= 18:

    if has_id:

        print("You can enter the club.")

    else:

        print("You need an ID to enter.")

else:

    print("You are not old enough to enter.")

In this example:

  • The outer if checks if the person is at least 18 years old.
  • If True, the inner if checks if the person has an ID.
  • If both conditions are met, the message “You can enter the club.” is printed. If the person is under 18, the message “You are not old enough to enter.” is displayed without checking the ID condition.

Python Conditional Expressions (Ternary Operator)

In Python, you can also write an if-else statement in a single line using the ternary operator, which is a concise way to return one of two values based on a condition.

Syntax:

value_if_true if condition else value_if_false

Example:

age = 20

eligibility = “Eligible” if age >= 18 else “Not eligible”

print(eligibility)  # Output: Eligible

Here, the condition age >= 18 is checked. If it’s True, “Eligible” is assigned to the eligibility variable; otherwise, “Not eligible” is assigned.

Logical Operators in Conditional Statements

Python provides three logical operators to combine multiple conditions:

  • and: Evaluates to True if both conditions are True.
  • or: Evaluates to True if at least one condition is True.
  • not: Reverses the truth value of the condition.

Example Using and:

age = 20

has_ticket = True

if age >= 18 and has_ticket:

    print(“You can watch the movie.”)

else:

    print(“You cannot watch the movie.”)

In this example, both conditions (age >= 18 and has_ticket) must be True for the message “You can watch the movie.” to be printed.

SAMSUNG GALAXY S23 FE 5G (MINT 256 GB STORAGE) (8 GB RAM)

Example Using or:

age = 16

has_ticket = True

if age >= 18 or has_ticket:

    print("You can watch the movie.")

else:

    print("You cannot watch the movie.")

Here, since has_ticket is True, the overall condition is True, even though age >= 18 is False.

Example Using not:

has_passed = False

if not has_passed:

    print(“You need to retake the test.”)

In this example, not has_passed evaluates to True because has_passed is False, so the message “You need to retake the test.” is printed.

Comparison Operators in Conditionals

Python offers several comparison operators to evaluate conditions:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • >=: Greater than or equal to
  • <: Less than
  • <=: Less than or equal to

Example:

x = 10

y = 20

if x < y:

    print("x is less than y")

else:

    print("x is not less than y")

Here, x < y evaluates to True, so the message “x is less than y” is printed.

pass Statement in Conditionals

Sometimes, you may need to write an if statement but don’t want to perform any action if the condition is true. In such cases, the pass statement can be used as a placeholder to avoid syntax errors.

Example:

x = 5

if x > 0:

    pass  # Do nothing for now

else:

    print(“x is not greater than 0”)

Using pass tells Python to do nothing and move on, which is useful during code development.

Python with Statement

The with statement in Python is used to wrap the execution of a block of code with methods defined by a context manager. This is especially useful for resource management, such as opening files or establishing network connections, where proper handling of resources is required (e.g., closing files automatically after processing). It simplifies code and ensures that resources are cleaned up properly, even if exceptions occur during the block execution.

Syntax:

with expression [as variable]:

    code_block

Example:

with open(“example.txt”, “r”) as file:

    content = file.read()

    print(content)

# The file is automatically closed after the block

In this example, the file is opened in read mode, and once the block inside the with statement is completed, the file is automatically closed, even if an error occurs.


Python Switch-Case Statements

Python does not have a built-in switch-case statement like many other programming languages (e.g., C, Java). However, similar functionality can be achieved using a combination of dictionaries and functions or using Python’s new pattern matching (match statement) introduced in Python 3.10.

Using Dictionaries:

Dictionaries can be used to map cases to values or functions.

Example:

def switch_case(option):

    switcher = {

        1: "Option 1 selected",

        2: "Option 2 selected",

        3: "Option 3 selected"

    }

    return switcher.get(option, "Invalid Option")

print(switch_case(1))  # Output: Option 1 selected

print(switch_case(4))  # Output: Invalid Option

In this example, a dictionary is used to simulate a switch-case structure, where the keys represent different cases and the values are the corresponding actions.

python

Using match-case (Python 3.10+):

The match-case statement is Python’s native pattern matching, similar to a switch-case in other languages.

Example:

def match_case(option):

    match option:

        case 1:

            return "Option 1 selected"

        case 2:

            return "Option 2 selected"

        case 3:

            return "Option 3 selected"

        case _:

            return "Invalid Option"

print(match_case(2))  # Output: Option 2 selected

Here, the match-case statement directly maps values to cases, offering a more readable approach for switch-like behavior in Python.


Other Statements in Python

1. if-else Statement:

This is the basic conditional statement in Python used to execute a block of code based on a condition.

Example:

x = 10

if x > 5:

    print(“x is greater than 5”)

else:

    print(“x is less than or equal to 5”)

2. for Loop:

The for loop in Python iterates over a sequence (such as a list, tuple, or string).

Example:

for i in range(3):

    print(i)

# Output: 0, 1, 2

3. while Loop:

The while loop continues execution as long as a condition is true.

Example:

x = 0

while x < 3:

    print(x)

    x += 1

# Output: 0, 1, 2

4. try-except Statement:

This is used for exception handling in Python, ensuring graceful error handling.

Example:

try:

    result = 10 / 0

except ZeroDivisionError:

    print(“Cannot divide by zero!”)

Conclusion

Python’s conditional statements provide powerful tools for controlling the flow of a program. By using if, elif, and else blocks, you can create logical branches to handle different conditions. With support for logical operators (and, or, not), comparison operators, and even nested conditionals, Python offers extensive flexibility for decision-making within your code. Mastering these constructs is key to writing efficient and effective Python programs.

Python provides various control flow structures like with for resource management, the match-case introduced in Python 3.10 as an alternative to switch-case, and other fundamental statements like if-else, loops (for, while), and exception handling (try-except). These structures are vital for controlling program execution and managing resources effectively.

Python good reads

Dhakate Rahul

Dhakate Rahul

2 thoughts on “The Python Journey – Chapter III Python Conditionals

  1. Автор старается оставаться объективным, чтобы читатели могли сформировать свое собственное мнение на основе предоставленной информации.

Comments are closed.