if else elif
时间: 2023-10-30 09:37:07 浏览: 76
If-else and elif are conditional statements in programming languages that allow the program to execute different sets of instructions based on certain conditions.
If statement: It is a basic conditional statement that executes a set of instructions if a condition is true. If the condition is false, the program will skip the instructions in the if block.
Syntax:
if condition:
#execute instructions if condition is true
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output: x is greater than 5
Else statement: It is used after an if statement to execute a set of instructions when the condition is false.
Syntax:
if condition:
#execute instructions if condition is true
else:
#execute instructions if condition is false
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Output: x is less than or equal to 5
Elif statement: It is used to check additional conditions after the if statement. It allows the program to execute different sets of instructions based on multiple conditions.
Syntax:
if condition1:
#execute instructions if condition1 is true
elif condition2:
#execute instructions if condition2 is true
else:
#execute instructions if both condition1 and condition2 are false
Example:
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is less than or equal to 5")
Output: x is greater than 5 but less than or equal to 10
阅读全文