
If-Else Statements in Python
if condition:
# code to execute if the condition is True
else:
# code to execute if the condition is False
The if keyword is followed by a condition that is evaluated as True or False.
If the condition is True, the indented code block after the if statement is executed.
If the condition is False, the indented code block after the else statement (if present) is executed.
marks = int(input("Enter your marks: "))
if marks >= 60:
print("Congratulations! You passed.")
else:
print("You didn't pass. Please try again next time.")
This program asks the user for their marks. It then uses an if statement to check if the marks are greater than or equal to 60 (assuming the passing mark). If the condition is True, the "Congratulations" message is printed. Otherwise, the "You didn't pass" message is printed.
The condition can be any expression that evaluates to True or False. Common comparisons include == (equal to), != (not equal to), < (less than),> (greater than), <= (less than or equal to), and>= (greater than or equal to).
You can have multiple lines of code indented within the if and else blocks
If the condition is False, and there's no else block, no code is executed after the if statement.
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Excellent! You got an A.")
elif marks >= 80:
print("Great work! You got a B.")
elif marks >= 70:
print("Well done! You got a C.")
else:
print("Keep practicing! You got a D or F.")
r = int(input("weight of the parcel : "))
if r <= 10:
u1 = (r * 20)
print(f"the charge for parcel {u1}")
elif r <= 30:
u2 = (r * 10)
print(f"the charge for parcel {u2}")
elif r <= 50:
u3 = (r * 8)
print(f"the charge for parcel {u3}")
elif r > 50:
u4 = (r * 5)
print(f"the charge for parcel {u4}")
else:
print("invalid unit")
This program uses nested if and elif (else if) statements to assign grades based on the marks. The elif statements are checked only if the previous if conditions are False.
1. Write a program that asks the user for a number and checks if it's positive, negative, or zero.
2. Write a program that asks the user for the day of the week (as a number, e.g., 1 for Monday) and prints the corresponding day name.