Making Decisions

Numbers and Expressions


Learning Objectives

  • You can use integers and floating-point numbers in calculations.
  • You can write arithmetic expressions using +, -, *, /, //, and % where appropriate.
  • You can translate a small word problem into variables and expressions.
  • You understand enough operator precedence to read common expressions and know when to use parentheses for clarity.
  • You can use intermediate variables to make calculations easier to read and explain.

Programs often need to do more than store values. They calculate with them. This chapter introduces the arithmetic tools you need for small programs and, more importantly, the habit of translating a real situation into clear expressions.

Calculating with Integers and Floats

The previous chapter distinguished int and float values. This chapter focuses on what you can calculate with them. Recall that:

  • int for whole numbers;
  • float for numbers represented with a decimal point.

Examples:

students = 28
temperature = 21.5

Basic arithmetic works much as you would expect:

print(10 + 3)
print(10 - 3)
print(10 * 3)
print(10 / 3)

The / operator performs division and produces a float:

print(10 / 2)

prints 5.0.

You can try out the examples in the editor below. Type them in, run them, and check that the output is what you expect.

No files opened Select a file to edit

Other Useful Arithmetic Operators

Python has several additional numeric operators.

Floor Division

// performs floor division:

print(17 // 5)

This gives 3.

Remainder

% gives the remainder after division:

print(17 % 5)

This gives 2.

Together, these are useful for converting a number of minutes into hours and leftover minutes:

minutes = 95
hours = minutes // 60
remaining_minutes = minutes % 60
print(f"{hours} h {remaining_minutes} min")

The output is:

1 h 35 min

Convert minutes into hours and minutes

0 / 10 points

Write a program that reads a whole number of minutes and separates it into complete hours and leftover minutes.

Use // to calculate the hours and % to calculate the leftover minutes. Store the entered value in total_minutes, the complete hours in hours, and the remainder in minutes.

Print exactly two lines. The hours line must come first:

Hours: 2
Minutes: 15

The example above is the required output for input 135. Use input() without a visible prompt so the output contains only these two lines. You may assume the input is a valid non-negative whole number.

From Input to Calculation

Remember that input(...) returns text. A calculation therefore usually starts with conversion:

minutes = int(input("Minutes: "))
hours = minutes / 60
print(hours)

Calculate a price with tax

0 / 10 points

Write a program that reads a price as a decimal number and calculates the price after adding 25.5% VAT.

Use these meaningful intermediate variables:

  • price for the entered price;
  • tax_amount for 25.5% of the price;
  • final_price for the price plus the tax.

Print final_price as a number. You do not need to format it to a fixed number of decimal places yet.

For input 10.50, the result should be 13.1775. You may assume the input is a valid non-negative number.

Operator Precedence

Consider:

result = 2 + 3 * 4

Python performs multiplication before addition, so the result is 14, not 20.

Parentheses can change the grouping:

result = (2 + 3) * 4

Now the result is 20.

You do not need to memorize a huge precedence table. For the expressions in this course, the following is usually enough:

  1. parentheses first;
  2. multiplication, division, floor division, and remainder;
  3. addition and subtraction.

When an expression is even slightly difficult to read, use parentheses or intermediate variables. Code is read far more often than it is typed.

Explain an expression step by step

0 / 15 points

Explain this program line by line:

a = 5 * 2 + 5
x = 10 + a * 2
a = 1
print(x)

For each assignment, state the value of the variable after the line runs and explain why it has that value. When a line contains more than one operator, explain the order in which Python performs the operations. Also explain whether assigning a new value to a changes x.

Finish by stating exactly what the program outputs.

Translating a Word Problem into Code

Suppose the task is:

A cinema ticket costs 12 euros. Ask how many tickets the user wants and calculate the total price.

A useful approach is to identify the quantities:

  • ticket price;
  • number of tickets;
  • total price.

Then turn them into variables:

ticket_price = 12
ticket_count = int(input("How many tickets? "))
total_price = ticket_price * ticket_count
print(f"Total: {total_price} euros")

The program is simple because the representation is simple. The variable names line up with the quantities in the problem description.

Estimate weekday study time

0 / 5 points

Arrange the Python statements so the program asks for the average minutes studied per weekday and estimates the total for five weekdays.

The first two assignments are independent and may appear in either order. Leave the incorrect calculation unused.

Now try the same kind of translation in plain language. Arrange the steps so the generated program stores a ticket price and a ticket count, calculates the total, and prints it.

Arithmetic and natural-language programming

0 / 5 points

Drag and drop the natural-language programming steps to the area marked with “Program”. Arrange the steps so the program stores a ticket price of 12 and a ticket count of 3, calculates the total price, and prints that total.

Some of the blocks are not needed.

Intermediate Variables Are Often Better

It is possible to write many calculations in one line. For instance, the above program could be written as:

print(f"Total: {12 * int(input('How many tickets? '))} euros")

This works, but it is harder to inspect and explain. Extra variables are not waste. They name the pieces of the reasoning and make it easier to read, trace, and explain. Prefer the following more explicit version over one-liners:

ticket_price = 12
ticket_count = int(input("How many tickets? "))
total_price = ticket_price * ticket_count
print(f"Total: {total_price} euros")

Formatting Numeric Output

Sometimes a calculation produces more decimal places than you want to show.

hours = 95 / 60
print(hours)

The exact output may contain many digits. In an f-string, you can request a fixed number of decimal places:

print(f"{hours:.1f} hours")

This displays one digit after the decimal point.

1.6 hours

Formatting changes how the number is shown. It does not change the stored value in hours.

Display a friendly average speed

0 / 10 points

Write a program that reads a distance in kilometers and a time in hours, both as decimal numbers.

Calculate the average speed in kilometers per hour and display it with exactly one digit after the decimal point, followed by km/h.

For inputs 150 and 2, the output must be:

75.0 km/h

Use input() without visible prompts so the output contains only the result. You may assume both inputs are valid positive numbers.

Common Pitfalls

A few common problems:

  • trying to add an integer to an unconverted input string;
  • using integer conversion when the input may contain a decimal point;
  • confusing / with //;
  • writing a correct but unreadable expression with too many operations on one line;
  • forgetting that units matter.

The last point is easy to underestimate. A value called time is less informative than time_minutes or time_hours. The variable name can carry the unit and prevent mistakes.

Use the following exercise to apply the chapter’s arithmetic tools in one complete calculation.

Calculate how many pizzas to order

0 / 15 points

Write a program that reads two positive whole numbers:

  1. the number of people;
  2. the number of pizza slices each person will eat.

Each pizza has 8 slices. Calculate how many whole pizzas must be ordered so that there are enough slices for everyone, including when the required slices do not divide evenly into pizzas.

For positive whole numbers, adding 7 before floor-dividing by 8 rounds a partial pizza up:

pizzas = (total_slices + 7) // 8

Print the result in this form:

Pizzas: 2

Use input() without visible prompts. You may assume both inputs are greater than zero.

Check Your Understanding

  1. What is the difference between / and //?
  2. What does % calculate?
  3. Why does 2 + 3 * 4 produce 14?
  4. Why can intermediate variables make a calculation easier to understand?
  5. Why must numeric user input usually be converted before arithmetic?
  6. What is the difference between changing a float’s value and merely formatting it for display?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0