The if statement is the driving force of logical programming. As a result, a better grasp of Python's conditions is a significant addition to your Python programming skills.

Do you want to know more about Python's if? No worries, we'll explain how to use the if statement to take control of your program.

How the if Statement Works in Python

Typically, conditional statements in Python begin with if. Conditions are programmer-defined rules that check if a particular expression is true or false. In essence, they check the validity of some logic.

An if statement in Python generally takes this format:

        if an event is True:
      Execute some commands...

Although the if statement can stand alone, other statements like elif and else can accompany it to modify the logic. You can also use statements like not, and, or, and in with the if condition of Python.

Python also lets you use the if statement directly with control flows like the for loop. Let's see how to use the if statement with each of these cases in the examples below.

How to Use Python's if and if...else Statements

With the if condition, you can tell Python to execute a set of commands as far as an event is true:

        if 5 > 3:
    print("Valid")

You can use a combination of if and else to run a different set of commands if the first condition is false:

        a = 10
b = 3

if a == b:
   print("They're the same")
else:
   print("They're not the same")

How to Use Python's if...elif...else Conditions

Python's elif is similar to JavaScript's else if. Although an else usually ends a condition, you use an elif if you still want to validate other expressions.

Let's see the use-case of Python's elif:

        a = 10
b = 3

if b == a:
    print(a + b)
elif b * a == 30:
    print(b - a)
else:
    print("impossible")

In the code above, Python executes the command within the if statement if its event is true. If not, it executes the elif condition. Otherwise, it outputs the else statement.

You can also use more than one elif to put other conditions in place:

        myList = ['Python', 'MUO', 'Hello']

if 'Python' in myList:
    print("No")
elif 'N' in myList[1]:
    print("MUO")
elif 'e' in myList[2]:
    print("Hello")
else:
print("None is true")

How to Use the "in," "and," and "or" Keywords With Python's if

You can use the in keyword with the if statement to check if an item is present in a list or an array:

        myList = ['Python', 'MUO', 'Hello']

if 'Python' in myList:
print("It's in the list")

You can also include the and expression to check more than a single item:

        myList = ['Python', 'MUO', 'Hello']

if 'Python' in myList and 'Hello' in myList:
print("Hello Python")

Python's set operation provides a slightly shorter way to write the above code:

        myList = ['Python', 'MUO', 'Hello']

if {'Python', 'Hello'}.issubset(myList):
    print("Hello Python")

To check if either item is on the list, you can use the or keyword:

        myList = ['Python', 'MUO', 'Hello']

if 'Python' in myList or 'Bags' in myList:
print("One of them is on the list")

How to Use the Python if With a for Loop

You can also control what happens in a for loop with the if condition. For example, you can set conditions for looping through an iterable using Python's for loop.

Have a look at the example code below to see how this works:

        myList = ['Python', 'MUO', 'Hello']
myList2 = ["Fish", "Gold", "Bag"]

if len(myList) == 3:
    for items in myList:
        print(items)
else:
    for items2 in myList2:
        print(items2)

The code above checks if the length of myList is exactly 3 and loops through it if the statement is true. Otherwise, it executes the else statement and outputs each item in myList2.

You can also modify this code to print all items in either list with exactly four letters:

        myList = ['Python', 'MUO', 'Hello', 'Books', 'Pizza', 'Four']
myList2 = ["Fish", "Gold", "Bag"]

for items in (myList + myList2):
    if len(items) == 4:
        print(items)

The code loops out only items with exactly four-word counts from a concatenation of both lists.

How to Use the if Statement in a Python Function

The if condition can also come in handy when writing a function in Python. As it does in plain code, the if condition can dictate what happens in a function.

Let's see how to use the if statement and other conditions in a Python function by refactoring the last block of code in the previous section above:

        def checkString(list1, list2):
    for items in (list1 + list2):
        if len(items) == 4:
            print(items)

List1 = ['Python', 'MUO', 'Hello', 'Books', 'Pizza', 'Four']
List2 = ["Fish", "Gold", "Bag"]

checkString(List1, List2)

Like the code in the previous section, the above function outputs all items with exactly four-word counts.

Using the if Statement With Python's Lambda Function

You can use the if statement with an anonymous lambda function as well.

Rewriting the function in the previous section as a lambda function gives a similar output:

        checkString = lambda a, b: [y for y in (a + b) if len(y) == 4]

print(checkString(List1, List2))

But here, the code output as a list since we expressed the code in a list comprehension.

How to Use an if Statement in a Python List Comprehension

It's also possible to use the if statement with the for loop in a Python list comprehension.

In this example, let's rewrite the previous code for printing all items with four-word counts in a list comprehension:

        myList = ['Python', 'MUO', 'Hello', 'Books', 'Pizza', 'Four']
myList2 = ["Fish", "Gold", "Bag"]
lis = [lists for lists in (myList + myList2) if len(lists) == 4]
print(lis)

You can also use if...and or if...or in a list comprehension:

        myList = ['Python', 'MUO', 'Hello', 'Books', 'Pizza', 'Four']
myList2 = ["Fish", "Gold", "Bag"]
lis = [lists for lists in (myList + myList2) if ('P' in lists or 'F' in lists)]
print(lis)

The code checks if there are items with either alphabet "P" or "F" in them and outputs them if the statement is true.

Feel free to replace the or operator with and to see what happens.

How to Use Nested if in a Python List Comprehension

In some cases, you can also use a nested if condition in a list comprehension. Let's take a look at an example of a list comprehension that outputs all numbers that can divide three and five using nested if conditions:

        B = range(31)
A = [x for x in B if x % 3 == 0 if x % 5 ==0]
print(A)

However, you can do what the above code does using a set comprehension instead of a list. But this time, you get your output as a set literal:

        A = {x for x in B if x % 3 == 0 if x % 5 ==0}
print(A)

Feel free to play around with other list comprehension examples by changing them to set comprehension as well.

Logical Statements Control Many Automated Programs

Logical statements are the building blocks of many algorithms. Conditional statements let you implement logic to run certain parts of your program.

Real-life projects like game development, machine learning, and web development depend on conditions for task automation. Learning more about conditionals, operators, and program logic will help you code dynamic and responsive programs.