Autocodewizard Logo Control Flow - Conditionals -Autocodewizard Ebooks - Python Programming Essentials: A Beginner�s Guide to Code and Data

Chapter 4: Control Flow � Conditionals

Learn how to control the flow of your code with conditional statements such as if, elif, and else.

This chapter will introduce you to conditional statements, which are essential for decision-making in programming. By the end, you'll know how to use if, elif, and else to control code execution based on conditions.

The if Statement

The if statement allows you to execute code only if a specific condition is true. Here�s a simple example:

x = 10
if x > 5:
    print("x is greater than 5")

In this example, the code inside the if block will only execute if x > 5 is true.

The else Statement

The else statement follows an if statement and executes code if the condition is false:

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less")

In this example, the code inside the else block executes because x > 5 is false.

The elif Statement

The elif (else if) statement checks additional conditions if the previous if statement is false:

x = 10
if x > 15:
    print("x is greater than 15")
elif x > 5:
    print("x is greater than 5 but not greater than 15")
else:
    print("x is 5 or less")

In this example, since x > 5 is true but x > 15 is false, only the elif block executes.

Nested Conditionals

You can nest if, elif, and else statements inside one another to check multiple conditions:

x = 20
if x > 10:
    print("x is greater than 10")
    if x > 15:
        print("x is also greater than 15")
    else:
        print("x is greater than 10 but not greater than 15")

In this example, the inner if statement only executes if the outer if statement�s condition is true.

Logical Operators with Conditionals

You can use logical operators and, or, and not to combine multiple conditions within a single if statement:

age = 25
income = 50000
if age > 18 and income > 40000:
    print("Eligible for loan")

In this example, the code in the if block will execute only if both conditions are true.

Summary and Next Steps

In this chapter, we covered Python�s conditional statements if, elif, and else. You should now be comfortable using these statements to control the flow of your code. In the next chapter, we�ll dive into loops, which allow you to repeat actions in your programs.