if elif else¶
- The
if
...elif
...else
statement is a powerful construct in Python for making conditional decisions. It allows you to execute different blocks of code based on multiple conditions.if condition1: # Code to execute if condition1 is True print('inside condition 1') elif condition2: # Code to execute if condition1 is False and condition2 is True print('inside condition 2') else: # Code to execute if all conditions are False print('all above conditions failed. i am inside else part now 😂')
- Explanation
if condition1
: The program checks ifcondition1
is True.- If
condition1
is True, the indented code block below it is executed, and the rest of theelif
andelse
blocks are skipped.
- If
elif condition2
(optional): This is an "else if" clause.- If
condition1
is False, the program then checks ifcondition2
is True. - If
condition2
is True, the code block followingelif
is executed, and theelse
block is skipped.
- If
else
(optional): This is a catch-all block.- If all the preceding conditions (
condition1
and anyelif
conditions) are False, the code block withinelse
is executed.
- If all the preceding conditions (
- Explanation
In [ ]:
Copied!
from random import randint
grade = randint(70, 100)
if grade >= 90:
print("Excellent! You got an A.")
elif grade >= 80:
print("Great job! You got a B.")
else:
print("Keep studying! You got a C or below.")
from random import randint
grade = randint(70, 100)
if grade >= 90:
print("Excellent! You got an A.")
elif grade >= 80:
print("Great job! You got a B.")
else:
print("Keep studying! You got a C or below.")
- Explanation
- The program prompts the user for their grade.
- The
if
statement checks if the grade is 90 or higher. If so, it prints "Excellent!". - The
elif
statement checks if the grade is at least 80 but less than 90. If so, it prints "Great job!". - The
else
block executes if the grade is below 80.
- You can have multiple
elif
conditions to check for different scenarios. - The
else
block is optional, but it's a good practice to include it to handle cases where none of the conditions are True. - Indentation is crucial in Python. Make sure all code blocks within
if
,elif
, andelse
are properly indented (usually by 4 spaces). - By mastering
if...elif...else
statements, you can write Python programs that make informed decisions based on various conditions, making your code more flexible and responsive.