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.
The basic if statement executes a block of code only if the provided condition is true.
if 5 > 3: print('5 is greater than 3')
5 is greater than 3
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.
num = -1 if num > 0: print('Positive number') else: print('Non-positive number')
Non-positive number
For multiple conditions, the if-elif-else construct can be used. It checks conditions sequentially and stops at the first true condition it encounters.
grade = 85 if grade >= 90: print('A') elif grade >= 80: print('B') else: print('C or below')
B
Copyright © 2023 - slash-root.com