if function in python

In Python, the if statement is used for conditional execution. It enables the program to execute different code blocks based on certain conditions. The basic syntax for the if statement in Python is:

main.py
if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False
107 chars
5 lines

Here, condition is a boolean expression that evaluates to either True or False. If condition is True, then the code block under the if statement is executed. If condition is False, then the code block under the else statement is executed.

For example, let's say we want to check whether a number is even or odd:

main.py
num = 5

if num % 2 == 0:
    print(f"{num} is even")
else:
    print(f"{num} is odd")
87 chars
7 lines

This will output:

main.py
5 is odd
9 chars
2 lines

The % operator is used to perform modulus division, which returns the remainder of the division. If num % 2 equals zero, then it means num is even, and the code block under the if statement is executed. Otherwise, if num % 2 is not zero, it means num is odd, and the code block under the else statement is executed.

gistlibby LogSnag