12 Python if else Exercises for Beginners

python-if-else-exercises-for-practice-program-with-solution-pdf

One of the basic concepts of Python is the if else statement, which allows you to execute different blocks of code depending on some conditions. In this article, we will learn how to use the if-else statement in Python and practice some exercises for beginners.

Course for You: Learn Python in 100 days of coding

What is the if-else statement in Python?

The if-else statement in Python is a way of making decisions based on some conditions. The general syntax of the if-else statement is:

if condition:
    # do something if condition is True
else:
    # do something else if condition is False

The condition can be any expression that evaluates to either True or False. For example, you can use comparison operators (==, !=, <, >, <=, >=) or logical operators (and, or, not) to create conditions. The code inside the if block will be executed only if the condition is True, otherwise the code inside the else block will be executed.

You can also use the elif keyword to add more conditions after the first if statement. The syntax of the elif statement is:

if condition1:
    # do something if condition1 is True
elif condition2:
    # do something if condition1 is False and condition2 is True
else:
    # do something if both condition1 and condition2 are False

You can have as many elif statements as you want, but you can only have one else statement at the end. The conditions are checked from top to bottom, and only the first one that is True will be executed.

Now that you have learned how to use the if-else statement in Python, you can try some exercises to test your skills. Here are some problems that you can solve using the if-else statement:

Exercise 1: Checking Even or Odd

Let’s start with a simple exercise. Write a Python program that takes an integer as input and prints whether it is even or odd using if else statement.

# if else program in python exercises: Even or Odd
num = int(input("Enter an integer: "))

if num % 2 == 0:
    print(num, "is even.")
else:
    print(num, "is odd.")
Enter an integer: 12
12 is even.
Enter an integer: 15
15 is odd.

Exercise 2: Grade Calculator

Create a Python program that calculates and displays the grade of a student based on their score. The grading criteria are as follows:

  • Score >= 90: A
  • 80 <= Score < 90: B
  • 70 <= Score < 80: C
  • 60 <= Score < 70: D
  • Score < 60: F
# if else exercises in python test: Grade Calculator
score = float(input("Enter your score: "))

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")
Enter your score: 75
C
Enter your score: 89
B

Exercise 3: Leap Year Checker

Write a Python program that checks if a given year is a leap year or not. A leap year is divisible by 4, except for years divisible by 100 but not divisible by 400.

# if else program in python exercises: Check for Leap Year
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(year, "is a leap year.")
else:
    print(year, "is not a leap year.")
Enter a year: 2023
2023 is not a leap year.
Enter a year: 2024
2024 is a leap year.

Exercise 4: Age Classifier

Create a Python program that categorizes a person’s age into different groups: child, teenager, adult, or senior.

# if else exercises in python
age = int(input("Enter your age: "))

if age < 18:
    print("You are a child.")
elif age < 60:
    print("You are an adult.")
else:
    print("You are a senior citizen.")
Enter your age: 23
You are an adult.

Exercise 5: Temperature Converter

Write a Python program that converts temperatures between Celsius and Fahrenheit. The user should input the temperature and its unit (C or F), and the program should convert it to the other unit.

# python if-else exercises for beginners: Temperature converter
temperature = float(input("Enter the temperature: "))
unit = input("Enter the unit (C or F): ")

if unit == 'C':
    fahrenheit = (temperature * 9/5) + 32
    print(f"{temperature}°C is equal to {fahrenheit}°F.")
elif unit == 'F':
    celsius = (temperature - 32) * 5/9
    print(f"{temperature}°F is equal to {celsius}°C.")
else:
    print("Invalid unit. Please enter 'C' or 'F'.")
Enter the temperature: 21
Enter the unit (C or F): C
21.0°C is equal to 69.8°F.
Enter the temperature: 41
Enter the unit (C or F): F
41.0°F is equal to 5.0°C.

Exercise 6: Simple Calculator for Addition

Create a simple calculator program that performs addition, subtraction, multiplication, or division based on user input.

# if else exercises in python: simple Calculator
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

result = num1 + num2
print(f"The sum of {num1} and {num2} is {result}.")
Enter the first number: 2
Enter the second number: 3
The sum of 2.0 and 3.0 is 5.0.
Enter the first number: 5
Enter the second number: 9
The sum of 5.0 and 9.0 is 14.0.

Exercise 7: Number Comparison

Write a program that compares two numbers and determines whether they are equal, greater than, or less than each other.

# python if-else exercises pdf for beginners: Number Comparison
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

if num1 == num2:
    print("Both numbers are equal.")
elif num1 > num2:
    print(f"{num1} is greater than {num2}.")
else:
    print(f"{num1} is less than {num2}.")
Enter the first number: 23
Enter the second number: 31
23.0 is less than 31.0.

Exercise 8: Simple ATM Machine

Create a basic ATM machine program that allows users to check their account balance and withdraw funds. You can set an initial account balance and then deduct the withdrawn amount.

# if else exercises pdf in python: ATM machine
account_balance = 1000  # Initial account balance

print("Welcome to the ATM!")
option = input("Choose an option (1: Check Balance, 2: Withdraw): ")

if option == "1":
    print(f"Your account balance is ${account_balance}.")
elif option == "2":
    amount = float(input("Enter the withdrawal amount: "))
    if amount <= account_balance:
        account_balance -= amount
        print(f"Withdrawn ${amount}. New balance: ${account_balance}.")
    else:
        print("Insufficient funds.")
else:
    print("Invalid option. Please choose 1 or 2.")
Welcome to the ATM!
Choose an option (1: Check Balance, 2: Withdraw): 1
Your account balance is $1000.
Welcome to the ATM!
Choose an option (1: Check Balance, 2: Withdraw): 2
Enter the withdrawal amount: 200
Withdrawn $200.0. New balance: $800.0.
Welcome to the ATM!
Choose an option (1: Check Balance, 2: Withdraw): 2
Enter the withdrawal amount: 1200
Insufficient funds.

Exercise 9: BMI Calculator

Create a Python program that calculates and categorizes a person’s Body Mass Index (BMI) based on their height and weight.

# if else program in python exercises: BMI score
weight = float(input("Enter your weight (in kilograms): "))
height = float(input("Enter your height (in meters): "))

bmi = weight / (height ** 2)

if bmi < 18.5:
    print("Underweight")
elif 18.5 <= bmi < 24.9:
    print("Normal weight")
elif 25 <= bmi < 29.9:
    print("Overweight")
else:
    print("Obese")
Enter your weight (in kilograms): 72
Enter your height (in meters): 1.8
Normal weight

Exercise 10: Ticket Pricing

Create a Python program for a movie theater that calculates ticket prices based on age and time of day. Tickets for children (age < 12) are $5, adults (age >= 12) are $10, and seniors (age >= 60) are $7. For evening shows (after 5 PM), there’s an additional $2 surcharge.

# if else exercises in python test: Ticket pricing
age = int(input("Enter your age: "))
time = int(input("Enter the showtime (24-hour format): "))

ticket_price = 0

if age < 12:
    ticket_price = 5
elif age >= 12 and age < 60:
    ticket_price = 10
else:
    ticket_price = 7

if time >= 17:  # Evening show surcharge after 5 PM
    ticket_price += 2

print("Ticket Price:", "$" + str(ticket_price))
Enter your age: 23
Enter the showtime (24-hour format): 18
Ticket Price: $12
Enter your age: 23
Enter the showtime (24-hour format): 10
Ticket Price: $10

Exercise 11: Voting Eligibility Checker

Create a Python program that determines whether a person is eligible to vote based on their age.

# if else exercises in python with module: Voting Eligibility Checker
age = int(input("Enter your age: "))

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote yet.")
Enter your age: 17
You are not eligible to vote yet.
Enter your age: 23
You are eligible to vote.

Exercise 12: Check for Vowel or Consonant

Write a Python program that checks whether a given letter is a vowel or a consonant.

# python pdf if-else exercises for beginners: Check for Vowel or Consonant

letter = input("Enter a letter: ").lower()

if letter.isalpha() and len(letter) == 1:
    if letter in 'aeiou':
        print(f"{letter} is a vowel.")
    else:
        print(f"{letter} is a consonant.")
else:
    print("Invalid input. Please enter a single letter.")
Enter a letter: a
a is a vowel.
Enter a letter: n
n is a consonant.

Conclusion

In this article, I have listed 12 normal and nasted ‘if else’ practice program exercises in Python, you can use it as pdf and read it whenever you want. These ‘if-else’ exercises cover various scenarios and will help you gain confidence in using conditional statements in Python more often to prepare for the interview.

Also Read:  21 Python String Exercises for Beginners

This is it for this article. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding. If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python. See you in the comment section below.

Similar Read:

Leave a comment