Mastering Python Conditional Statements: if, if-else, if-elif-else & More
Python’s conditional statements help in decision-making by executing code blocks based on specified conditions. Understanding if, if-else, and if-elif-else statements is crucial for writing logical and efficient programs. Let’s explore them with practical examples.
1. The if Statement
The if statement evaluates a condition, and if it holds True, the corresponding block of code executes.
if True:
print("Statement is true")
if False:
print("Statement is false") # This will not execute
Example:
x = 20
if x > 10:
print("X is greater than 10")
x = 20
if x < 10:
print("X is less than 10") # No output, as the condition is False
Checking Membership in Lists:
L = [10, 20, 30, 40, 50]
if 20 in L:
print("20 is a member of L")
2. The if-else Statement
The if-else structure helps define an alternative action if the condition is False.
x = 20
if x > 10:
print("X is greater than 10")
else:
print("X is less than 10")
Example: Checking Even or Odd Numbers
values = {}
x = int(input("Enter a value: "))
if x % 2 == 0:
values[str(x)] = "Even"
else:
values[str(x)] = "Odd"
print(values)
3. The if-elif-else Statement
When multiple conditions need evaluation, the if-elif-else structure is useful.
mark = 75
if mark >= 80:
Grade = "A"
elif mark >= 65:
Grade = "B"
elif mark >= 50:
Grade = "C"
else:
Grade = "Repeat"
print(Grade)
Using Logical Operators in Conditions
Python supports logical operators (and, or, not) to create complex conditions.
Example: Using and
x = 30
if x > 10 and x < 50:
print("X is in the correct region")
else:
print("X is out of the region")
Example: Using or
x = 30
if x > 10 or x == 50:
print("X is in the correct region")
else:
print("X is out of the region")
Example: Using not
x = 30
if not x > 10 or x == 50:
print("X is in the correct region")
else:
print("X is out of the region")
5. Implementing Login Authentication with if-else
details = {"Sam": "ABC", "Kane": "XYZ", "Jane": "PQR"}
username = input("Please enter your username: ")
if username in details:
password = input("Please enter your password: ")
if password == details[username]:
print("You have logged in successfully!!!")
else:
print("Check your password...")
else:
print("You are not in the system. Please check your username again.")
6. Inline Decision Making (Ternary Operator)
Python provides a concise way to write simple if-else conditions in a single line.
Example:
x = 20 y = 10 if x > 10: y = 30 print(y) # Output: 30
Using a Ternary Operator:
fruit = 'Apple' check_apple = "Yes" if fruit == 'Apple' else "No" print(check_apple) # Output: Yes
Assigning Grades Conditionally:
mark = 90 grade = "A" if mark >= 80 else "B" if mark >= 65 else "C" if mark >= 50 else "F" print(grade) # Output: A