The IF statement


In Python, the if statement is used for conditional execution of code. It allows the program to evaluate if a certain condition is true or false and, based on the result, execute specific blocks of code.

a. Basic IF statement:

The basic if statement executes a block of code only if the provided condition is true.

Code

if 5 > 3:
    print('5 is greater than 3')

Output

5 is greater than 3

b. IF-ELSE statement:

The if-else construct evaluates a condition, and if it's true, it executes the block of code under the if. If it's false, it executes the block of code under the else.

Code

num = -1
if num > 0:
    print('Positive number')
else:
    print('Non-positive number')

Output

Non-positive number

c. IF-ELIF-ELSE statement:

For multiple conditions, the if-elif-else construct can be used. It checks conditions sequentially and stops at the first true condition it encounters.

Code

grade = 85
if grade >= 90:
    print('A')
elif grade >= 80:
    print('B')
else:
    print('C or below')

Output

B

Enquiries

[email protected]

Copyright © 2023 - slash-root.com