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
- Prerequisites
- Conditionals in Python
- Comparison Operators
- Logical Operators
- Exercises
- Exercise 1 - Number Comparisons
- Exercise 2 - Calculate Discount
- Exercise 3 - Check Age Eligibility
- Exercise 4 - Find Largest of Three Numbers
- Exercise 5 - Check Leap Year
- Exercise 6 - Calculate Grade
- Exercise 7 - Print Days of the Week
- Exercise 8 - Calculator
- Exercise 9 - Check Triangle Validity
- Exercise 10: Find Largest Among Three Strings
- Summary
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:
- Basic knowledge of Python syntax and datatypes
- Experience with variables, loops, functions, and other core language constructs
- Python 3 installed on your system
- A working IDE or code editor for running the example code
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:
==
Equal to!=
Not equal to>
Greater than<
Less than>=
Greater than or equal to<=
Less than or equal to
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:
and
- Evaluates toTrue
if both operands areTrue
or
- Evaluates toTrue
if either one operand isTrue
not
- Negates or inverts aTrue
orFalse
value
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:
- “First is greater” if the first number is greater
- “Second is greater” if the second number is greater
- “Numbers are equal” if both numbers are equal
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:
- Taking input from user
- Comparing two numbers using
>
and==
operators - Printing different messages based on comparison result
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:
- Comparing floats using
>=
and nestedif-elif-else
structure - Calculating discount amount from percentage
- Controlling program flow based on discount
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:
- Simple
if-else
based on a single condition - Comparing an int to a literal number
- Basic eligibility check
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:
- Comparing multiple numbers instead of just two numbers
- Tracking the largest number seen so far
- Checking each number against the current largest number
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 is multiple of 4 and not multiple of 100
- Year is multiple of 400
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:
- Checking two conditions using logical operators
- Using modulo (%) operator to check for factors
- Complex conditions for leap year check
Exercise 6 - Calculate Grade
Take exam marks as input and print the grade based on standard grading scheme:
-
= 90 - A
-
= 80 and < 90 - B
-
= 70 and < 80 - C
-
= 60 and < 70 - D
- < 60 - F
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:
- Chaining multiple
elif
blocks - Using
and
operator to check ranges -nested if-elif-else structure - Calculating grade based on standard scheme
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:
- Using
elif
ladder to check multiple conditions - Validating user input falls in expected range
- Print appropriate strings based on day number
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:
- +: Add two numbers
- -: Subtract second number from first
- *: Multiply two numbers
- /: Divide first number by second
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:
- Handling multiple arithmetic operations
- Nested
if
statement to check division by zero - Printing appropriate messages and results
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:
- Sum of two sides is greater than the third side.
- Difference between any two sides is less than the third side.
- 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:
- Checking multiple triangle validity rules
- Chaining logical operators
and
andor
- Ensuring no zero or negative sides
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:
- Comparing string order using
>
operator - Finding largest of strings similar to numbers
- Strings are sorted lexicographically
Summary
These exercises showcase a variety of common scenarios where conditionals and logical operators can be used in Python programs.
Some key points:
- The
if
,elif
, andelse
statements allow controlling code execution based on conditions. - Comparison operators like
>
,==
etc can compare numbers, strings, and other objects. - Multiple conditions can be combined using logical operators
and
,or
,not
. - Indentation is important in Python to define blocks of code under conditionals.
- Conditionals are critical for writing non-trivial Python programs with complex decision making and control flows.
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:
- Games with scoring and rules
- Business applications with purchase discount logic
- Form validators for web applications
- Classifier and predictive systems using machine learning
- Automated scripts to process different file types
- Tools for data analysis and visualization
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.