Python Programs on Conditional Statements
Pogram 1: Write a python program to check a given number is Even or Odd.
Logic: If a number is evenly divisible by 2 with no remainder, then it is even.
Program:
# Get input from user
number = int(input("Enter a number: "))
# Check if the number is even or odd
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
Output:
Enter a number: 24
24 is an even number.
Enter a number: 37
37 is an odd number.
24 is an even number.
Enter a number: 37
37 is an odd number.
Pogram 2: Write a python program to find the greatest of 3 integer numbers.
Logic:
- Compare the first number (x1) with the other two (x2 and x3).
- If x1 is greater than or equal to both x2 and x3, then x1 is the greatest.
- If not, check if x2 is greater than or equal to both x1 and x3.
- If neither x1 nor x2 is the greatest, then x3 must be the greatest.
Program:
# Get three numbers from user
x1 = int(input("Enter first number: "))
x2 = int(input("Enter second number: "))
x3 = int(input("Enter third number: "))
# Find the greatest number
if x1 >= x2 and x1 >= x3:
greatest = x1
elif x2 >= x1 and x2 >= x3:
greatest = x2
else:
greatest = x3
# Display the result
print("The greatest number is:", greatest)
Output:
Enter first number: 45
Enter second number: 78
Enter third number: 23
The greatest number is: 78
Enter second number: 78
Enter third number: 23
The greatest number is: 78
Pogram 3: Write a python program to demonstrate nested if statement.
Program:
# Student Grade Evaluator with Attendance Check
# Input student details
marks = float(input("Enter student's marks (0-100): "))
attendance = float(input("Enter attendance percentage (0-100): "))
# Outer if - Check if student meets minimum attendance requirement
if attendance >= 75:
print("Attendance requirement satisfied. Checking marks...")
# First level nested if - Grade determination
if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'
# Second level nested if - Pass/Fail check
if grade != 'F':
print(f"Result: PASS with Grade {grade}")
else:
print("Result: FAIL")
if marks < 30:
print("Warning: Very low marks!")
else:
print("Result: FAIL (Insufficient attendance)")
if attendance < 50:
print("Severe warning: Attendance below 50%!")
Output:
Enter student's marks (0-100): 85
Enter attendance percentage (0-100): 90
Attendance requirement satisfied. Checking marks...
Result: PASS with Grade B
Enter attendance percentage (0-100): 90
Attendance requirement satisfied. Checking marks...
Result: PASS with Grade B