top of page

Mastering Python If Statements: A Beginner's Guide

Updated: May 17, 2023

Python is widely used in many applications, such as web development, data analysis, and artificial intelligence. One of the critical features that allow Python to be at the forefront of these fields is its ability to use conditions to control the flow of a program. In this article, we'll discuss the syntax and types of conditions used in Python to control the flow of your scripts.



Boolean Expressions

A boolean expression is a statement that evaluates to either "True" or "False." In Python, these expressions are then used to determine if a condition has been met. Below is a table that lists Python's most commonly used conditional statements.

Statements

Definition

==

Checks if the value on the left is equal to the value on the right

!=

Checks if the value on the left is NOT equal to the value on the right

>

Checks if the value on the left is greater than the value on the right

<

Checks if the value on the left is smaller than the one on the right

>=

Checks if the value on the left is greater than or equal to the value on the right

<=

Checks if the value on the left is less than or equal to the value on the right

Below is an example checking to see if a variable `x` is equal to a value of 5:

x = 5
print(x == 5)

# Output: True

Below is an example checking to see if the same variable `x` is less than 3:

x = 5
print(x < 3)

# Output: False

In addition to comparison operators, boolean expressions can be combined with logical operators to create more complicated conditions. Below is a table that lists Python's most commonly used logical operators.

Logical Operator

Definition

and

Checks if both conditional statements to the left and right evaluate to true

or

Checks to see if one of the conditional statements to the left and right evaluates to true

not

Inverts the result of a conditional statement

Below is an example that checks if two boolean expressions evaluate to true:

x = 5
print(x > 3 and x == 5)

# Output: True

The example below modifies the previous by using the "not" operator:

x = 5
print(not x > 3 and x == 5)

# Output: False

The "not" operator flips the result of `x > 3` to evaluate to false. See what happens if you change the symbol to "<", while keeping the "not" operator.



If Statements

The if statement takes the boolean expression one step further. It allows for the execution of a block of code if and only if the specified boolean expression evaluates to true. Below is an example of the syntax for an if statement:

if boolean_expression:
    # code to be executed

One important thing to note is the indentation after the semi-colon. In most programming languages, curly braces define the code block; in Python, indentations are used instead. Without the indentation, an error will result, and any code that is not indented will not be considered within the block of code.


Below is a code snippet that utilizes an if statement to determine if a variable `x` is larger than some variable `y` and prints "x is greater than y" if the condition is true.

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

The above Python code will result in no output because `x` is not greater than `y`.



If-Else Statements

We can add further functionality to the if statement we created above by using the "else" keyword. This keyword allows us to execute a block of code if all other if statements result in a false condition. Below is the syntax used for an if-else statement:

if boolean_expression:
    # code to be executed if condition is true
else:
    # code to be executed if condition is false

The below code snippet is a modification of the previous example. Remember that when the program ran, no output was observed because the variable `x` was smaller than `y`. An else block can be added to account for that specific case.

x = 5
y = 10
if x > y:
    print("x is greater than y")
else:
    print("x is less than or equal to y")

If you run the above code, you see that the code in the else block is executed, not the code in the if block.



Else-If Statements

What if there are multiple conditions that you need to check and not just one? That's when you want to use the "elif" keyword. This keyword behaves like an if statement with a few minor differences: it always comes after the if statement and will only execute if the previous if statements condition evaluates to false. Below is the syntax for the else-if statement:

if boolean_expression1:
    # code to be executed if condition1 is true
elif boolean_expression2:
    # code to be executed if condition1 is false and condition2 is true
else:
    # code to be executed if both condition1 and condition2 are false

One important note is that you are not limited to the total amount of elif statements you write, and you're not required to use the else statement. Below is an example else-if statement that prints various messages to the terminal depending on the value of a variable. Play around with different values to get all of the print messages to show.

x = 5
if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")


Nested If Statements

You are not limited to only print statements that can be executed within the if statement block. To gain even finer control or implement complex rules, you can place more if statements inside the code blocks of others. Below is an example demonstrating the basic syntax for a nested if statement:

if boolean_expression1:
    # code to be executed if condition1 is true
    if boolean_expression2:
        # code to be executed if condition2 is true
    else:
        # code to be executed if condition2 is false
else:
    # code to be executed if condition1 is false

Another important note is the use of many nested if statements make your code much harder to maintain and read, so use nested if statements judiciously.


Here's a basic example of how nested if statements could be used to print out different messages based on more complex rules.

x = 5
y = 10
if x > 0:
    if y % 2 == 0:
        print("x is positive and y is even")
    else:
        print("x is positive and y is odd")
else:
    print("x is not positive")


Conclusion

An essential component of any program is a conditional statement. Whether you use straightforward boolean expressions or intricate if statements, the important thing is to use them in a way that makes your code simple to comprehend. You'll be able to create more powerful and effective programs with the knowledge provided in the article about Python conditions.


2 views0 comments

Recent Posts

See All
bottom of page