Skip to content

Practical Exercises for Conditional Statements and Logical Operators in Python

Updated: at 04:45 AM

Conditional statements and logical operators are fundamental concepts in Python and programming in general. Mastering their use allows you to write complex programs by controlling the flow of execution and making decisions based on different conditions.

This comprehensive guide provides practical exercises and examples for learning how to effectively use conditional statements like if, else, and elif statements as well as logical operators such as and, or, not in Python.

Table of Contents

Open Table of Contents

Introduction

Conditional statements, also called conditional expressions, allow a program to execute different code blocks based on whether a condition is True or False. The most common conditional statement in Python is the if statement.

The if statement checks whether the condition following it evaluates to True and executes the code indented under it if so. Optional elif and else statements can extend its functionality.

Logical operators like and, or and not allow creating complex conditional expressions involving multiple conditions.

Mastering conditional statements and logical operators is essential for beginning Python programmers looking to write non-trivial programs that can make decisions and execute blocks of code selectively.

This guide will provide various hands-on exercises and examples to help you gain a strong grasp over using conditionals and logical operators in Python.

Prerequisites

Before starting with the exercises, you should have:

The examples are written for Python 3 specifically. Some behavior may differ if you run the code with Python 2.

Conditionals in Python

Let’s first briefly revisit the key conditional statements in Python:

The if Statement

The basic syntax of an if statement is:

if condition:
   code to execute if condition is True

The condition can be any expression that evaluates to True or False.

For example:

num = 10
if num > 5:
    print(f"{num} is greater than 5")

This will check if num is greater than 5. If so, it will print that num is greater than 5. The code under the if statement is indented using spaces (4 spaces recommended).

The else Statement

An else statement can be added after an if statement to execute code when the if condition is False:

num = 3
if num > 5:
   print(f"{num} is greater than 5")
else:
   print(f"{num} is not greater than 5")

Here, since num is not greater than 5, the code under else is executed.

The elif Statement

The elif statement allows chaining multiple conditions and code blocks:

num = 7

if num > 10:
   print(f"{num} is greater than 10")
elif num > 5:
   print(f"{num} is greater than 5")
else:
   print(f"{num} is not greater than 5")

Here num > 10 is checked first, and since it’s False, the next elif block is executed. Multiple elif blocks can be added in this manner.

The if, elif, else structure allows only one block to execute. Once a condition is True, the rest are skipped.

Comparison Operators

Comparison operators compare two values and evaluate to True or False. They are essential for writing conditional expressions.

The standard comparison operators are:

For example:

num1 = 5
num2 = 10

print(num1 == num2) # False
print(num1 != num2) # True
print(num1 > num2) # False
print(num1 < num2) # True

These operators can be used to compare numbers, strings, lists, and other types.

Logical Operators

Logical operators allow combining multiple conditional expressions and evaluating the result as a boolean value.

The three logical operators in Python are:

For example:

x = 5
y = 8
z = 10

print(x > 3 and y > 5) # True AND True = True
print(x > 8 and y > 5) # False AND True = False

print(x > 8 or y > 5) # False OR True = True

print(not(x == y)) # not(False) = True

Multiple logical operators can be chained together to create complex conditional logic in if statements.

Now that we’ve reviewed the basics, let’s jump into some practical exercises.

Exercises

The following exercises cover common scenarios and use cases for conditionals and logic operators. They are designed to get you comfortable with writing conditional expressions and control flows in Python.

Try to solve the exercises first before looking at the solutions provided below each problem statement.

Exercise 1 - Number Comparisons

Write a program that takes two integers from the user and prints:

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if num1 > num2:
  print("First is greater")
elif num2 > num1:
  print("Second is greater")
else:
  print("Numbers are equal")

This exercise covers:

Exercise 2 - Calculate Discount

Take the original price of an item and discount percentage as input. If the discount is 50% or more, print “Huge discount!”. If the discount is 20% or more but less than 50%, print “Good discount.”. Otherwise, print “No discount”.

original_price = float(input("Enter original price: "))
discount_percent = float(input("Enter discount percentage: "))

if discount_percent >= 50:
  print("Huge discount!")
elif discount_percent >= 20:
  print("Good discount")
else:
  print("No discount")

This covers:

Exercise 3 - Check Age Eligibility

Take age as input and print “Eligible” if age is >= 18, otherwise print “Not eligible”.

age = int(input("Enter age: "))

if age >= 18:
  print("Eligible")
else:
  print("Not eligible")

This example demonstrates:

Exercise 4 - Find Largest of Three Numbers

Take three numbers as input and print the largest number among the three.

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))

largest = num1
if num2 > largest:
    largest = num2
if num3 > largest:
    largest = num3

print("Largest number is:", largest)

This covers:

Exercise 5 - Check Leap Year

Take year as input and print “Leap year” if it is a leap year, else print “Not leap year”. A leap year checks:

year = int(input("Enter year: "))

if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
  print("Leap year")
else:
  print("Not leap year")

This demonstrates:

Exercise 6 - Calculate Grade

Take exam marks as input and print the grade based on standard grading scheme:

marks = float(input("Enter your marks: "))

if marks >= 90:
  print("Grade: A")
elif marks >=80 and marks < 90:
  print("Grade: B")
elif marks >= 70 and marks < 80:
  print("Grade: C")
elif marks >= 60 and marks < 70:
  print("Grade: D")
else:
  print("Grade: F")

This covers:

Exercise 7 - Print Days of the Week

Take number of day from user where 1 is Sunday, 2 is Monday etc. Print name of the weekday.

day = int(input("Enter day number(1-7): "))

if day == 1:
  print("Sunday")
elif day == 2:
  print("Monday")
elif day == 3:
  print("Tuesday")
elif day == 4:
  print("Wednesday")
elif day == 5:
  print("Thursday")
elif day == 6:
  print("Friday")
elif day == 7:
  print("Saturday")
else:
  print("Invalid day number")

This demonstrates:

Exercise 8 - Calculator

Create a simple calculator that takes two numbers and an operator as input. Perform the operation and print result based on operator:

Handle division by zero error by printing “Cannot divide by zero” when second number is 0.

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")

if op == '+':
  print(num1 + num2)
elif op == '-':
  print(num1 - num2)
elif op == '*':
  print(num1 * num2)
elif op == '/':
  if num2 == 0:
    print("Cannot divide by zero")
  else:
    print(num1 / num2)
else:
  print("Invalid operator")

This covers:

Exercise 9 - Check Triangle Validity

Take lengths of three sides as input. Print whether a valid triangle can be formed or not based on following rules:

  1. Sum of two sides is greater than the third side.
  2. Difference between any two sides is less than the third side.
  3. No side is zero or negative.

Print “Valid triangle” or “Invalid triangle” accordingly.

a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))

if a + b > c and b + c > a and c + a > b and a > 0 and b > 0 and c > 0:
  print("Valid triangle")
else:
  print("Invalid triangle")

This problem demonstrates:

Exercise 10: Find Largest Among Three Strings

Take three string inputs and print the largest string in lexicographical order.

str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
str3 = input("Enter third string: ")

largest = str1
if str2 > largest:
    largest = str2
if str3 > largest:
    largest = str3

print("Largest string is:", largest)

This example shows:

Summary

These exercises showcase a variety of common scenarios where conditionals and logical operators can be used in Python programs.

Some key points:

After practicing these exercises, you should have a much better grasp of using conditional statements and logical operators in Python. You can start applying these concepts to build more useful programs.

Some examples of what you can develop:

The possibilities are endless! With the fundamental building blocks you now have, you can start tackling more challenging projects to continue honing your Python skills.