Conditional Statements in Python#

Conditional statements allow us to make decisions in our code based on certain conditions. In this notebook, we’ll explore the basic structure and usage of conditional statements in Python.

Let’s start by importing the required libraries. In this case, we don’t need any specific libraries for conditional statements, but it’s good practice to include this cell for consistency.

# No specific imports required for this lesson

The ‘if’ Statement#

The most basic form of a conditional statement is the ‘if’ statement. It executes a block of code if a specified condition is true.

Let’s create a simple ‘if’ statement to check if a number is positive.

number = 5

if number > 0:
    print(f"{number} is positive")
5 is positive

The ‘if-else’ Statement#

We can extend the ‘if’ statement with an ‘else’ clause to specify what should happen if the condition is false.

Let’s modify our previous example to handle both positive and non-positive numbers.

number = -2

if number > 0:
    print(f"{number} is positive")
else:
    print(f"{number} is not positive")
-2 is not positive

The ‘if-elif-else’ Statement#

For multiple conditions, we can use the ‘elif’ (short for ‘else if’) statement. This allows us to check several conditions in sequence.

Let’s create an example that categorizes a number as positive, negative, or zero.

number = 0

if number > 0:
    print(f"{number} is positive")
elif number < 0:
    print(f"{number} is negative")
else:
    print(f"{number} is zero")
0 is zero

Nested Conditional Statements#

We can also nest conditional statements inside each other for more complex decision-making.

Let’s create an example that categorizes a number and checks if it’s even or odd.

number = 4

if number != 0:
    if number > 0:
        print(f"{number} is positive")
    else:
        print(f"{number} is negative")
    
    if number % 2 == 0:
        print(f"{number} is even")
    else:
        print(f"{number} is odd")
else:
    print(f"{number} is zero")
4 is positive
4 is even

Conclusion#

Conditional statements are fundamental to programming logic. They allow your code to make decisions and execute different paths based on specific conditions. Practice using these statements to create more dynamic and responsive programs!