Python Operators · Exercises
Beginner

Python Operators Exercises

4 exercises that build on the Python Operators lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Operators are symbols such as +, == and and that combine values into a new value — a number from arithmetic, or True/False from a comparison or a logical test. By the end you can do arithmetic including //, % and **, predict the order Python works things out in, compare values, combine conditions with and/or/not, and update variables with +=. You will practise: Rectangle calculator; Predict the results; Fix the time converter; Is it a leap year?.

0 / 4 completed

Python Operators practice exercises

1. Rectangle calculator

Write code Easy

Using the given width and height, create three variables:

  • area — width times height,
  • perimeter — the distance all the way round (2 × width + 2 × height),
  • is_square — True if width and height are equal, otherwise False. Use a comparison operator rather than typing True or False.

Then print all three.

Your code
width = 7
height = 4

# create area, perimeter and is_square

2. Predict the results

Predict the output Medium

Read the code and type exactly what it prints. Think about the type each operator returns and the order Python works things out in.

Read this code
print(10 / 4)
print(10 // 4, 10 % 4)
print(2 + 3 * 2 ** 2)
print(not 5 > 3 or 1 == 1.0)

3. Fix the time converter

Fix the bug Medium

This code should turn 135 minutes into 2 h 15 min, but it prints 2.25 h 0.0 min. Fix it so that hours and minutes are whole numbers (ints).

Your code
total_minutes = 135
hours = total_minutes / 60
minutes = total_minutes - hours * 60
print(hours, "h", minutes, "min")

4. Is it a leap year?

Write code Hard

A year is a leap year if it is divisible by 4 — except years divisible by 100, which are not — unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 and 2023 are not.

Write one expression using %, == / !=, and and or that stores True or False in is_leap for the given year, then print it. Before pressing Check, try changing year to 2000, 2023 and 2024 to make sure your expression works for every case.

Your code
year = 1900

# is_leap = ...

print(year, "is a leap year:", is_leap)

Next lessonPython Strings

More Python Operators examples · All Python exercises