In Python, there are several decision-making statements that allow you to control the flow of your program based on certain conditions. The most commonly used decision-making statements are:
if
statement: This statement allows you to execute a block of code if a certain condition is true.
1 2 3 4 |
x = 10 if x > 5: print("x is greater than 5") |
if-else
statement: This statement allows you to execute one block of code if a certain condition is true, and another block of code if the condition is false.
1 2 3 4 5 6 |
x = 10 if x > 5: print("x is greater than 5") else: print("x is not greater than 5") |
if-elif-else
statement: This statement allows you to test multiple conditions and execute the corresponding code block for the first true condition.
1 2 3 4 5 6 7 8 |
x = 10 if x > 15: print("x is greater than 15") elif x > 5: print("x is greater than 5 but less than or equal to 15") else: print("x is not greater than 5") |