Relational, Logical, and Conditional Operators in Python
Understand how Python makes decisions with comparisons, logical connectors, and conditional statements.
1) Relational Operators
x, y = 10, 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= 10) # True
print(y <= 15) # False
2) Logical Operators
a, b = 5, 15
print(a > 0 and b > 0) # True
print(a > 0 or b < 0) # True
print(not(a > b)) # True
3) if, else, and elif
marks = 72
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
# Output: Grade B
4) Ternary Operator
Shorthand: x if condition else y
.
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
# Example: maximum of two numbers
x, y = 25, 40
maximum = x if x > y else y
print(maximum) # 40
5) Multilevel Conditions
x, y, z = 15, 40, 30
# Find maximum of three numbers using nested if-else
if x > y and x > z:
maximum = x
elif y > z:
maximum = y
else:
maximum = z
print(maximum) # 40
6) Practical Examples
Leap Year
year = 2024
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Leap Year") # Leap Year
else:
print("Not a Leap Year")
Triangle Possibility and Type
a, b, c = 5, 5, 8
if a + b > c and a + c > b and b + c > a:
if a == b == c:
print("Equilateral Triangle")
elif a == b or b == c or a == c:
print("Isosceles Triangle") # Isosceles Triangle
else:
print("Scalene Triangle")
else:
print("Triangle not possible")
Convert 24-Hour Time to AM/PM
hour = 21
minute = 15
if hour == 0:
print(f"12:{minute} AM")
elif hour < 12:
print(f"{hour}:{minute} AM")
elif hour == 12:
print(f"12:{minute} PM")
else:
print(f"{hour - 12}:{minute} PM") # 9:15 PM
7) Assignments (Click to Show Answer)
Q1: Write a ternary operator to find the smallest of two numbers.
a, b = 8, 3
minimum = a if a < b else b
print(minimum) # 3
Q2: Write a program to check whether a year is a leap year.
year = 1900
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Leap Year")
else:
print("Not Leap Year") # Not Leap Year
Q3: Given three sides, decide if a triangle is possible. If possible, classify it.
a, b, c = 7, 7, 7
# Output: Equilateral Triangle
Q4: Convert 14:45 (24-hour format) to AM/PM.
hour, minute = 14, 45
print(f"{hour-12}:{minute} PM") # 2:45 PM
0 Comments