Python If … Else

Understanding Python Conditional Statements: A Comprehensive Guide

Python, renowned for its simplicity and readability, offers a range of conditional statements that are fundamental for decision-making in programming. This guide aims to provide a clear and concise understanding of these statements, enabling both beginners and seasoned programmers to write more efficient and readable code.

1. Python Conditions and If Statements

Python evaluates conditions using the standard logical expressions from mathematics. An “If statement” is written by using the if keyword.

Here’s a simple example:

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

This code checks if x is greater than 5 and prints a message if the condition is true.

2. Indentation

Python uses indentation to define scope in the code. Proper indentation is crucial as incorrect indentation leads to errors. For instance:

Here’s a simple example:

if x > 5:
print("x is greater than 5")  # This will cause an error

3. Elif

The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.

Here’s a simple example:

if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but not greater than 10")

4. Else

The else keyword catches anything which isn’t caught by the preceding conditions. It can be combined with if statements as follows:

Here’s a simple example:

if x > 10:
    print("x is greater than 10")
else:
    print("x is 10 or less")

5. Short Hand If

For simple conditions, the shorthand if can be used on a single line:

Here’s a simple example:

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

6. Short Hand If…Else

Similarly, short-hand if…else can also be written in a single line:

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

7. And

The and keyword is a logical operator that combines conditional statements:

if x > 5 and x < 15:
    print("x is greater than 5 and less than 15")

8. Or

The or keyword links two conditions and is true if at least one condition is true:

if x > 5 or x < 4:
    print("x is either greater than 5 or less than 4")

9. Not

The not keyword is a logical operator used to invert the truth value:

if not(x > 5 and x < 15):
    print("x is not between 5 and 15")

10. Nested If

You can have if statements inside if statements, known as nested if statements:

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

By mastering these conditional statements, you can control the flow of your Python programs with precision and clarity. Practice these concepts regularly to enhance your Python programming skills.