Learn/Python/3. Reading input and arithmetic
Lesson 3 of 15
Sign in

Python, lesson 3

Reading input and arithmetic

Programs become useful when they react to data. The simplest way to get data into a Python program is input(). It reads one line from standard input and hands it back as a string, with the trailing newline already removed.

Each call reads the next line. If there are no lines left, input() raises an EOFError, so only call it as many times as there are lines to read.

Text is not a number

input() always returns a str, even if the user typed digits. To do maths you convert it:

int() and float() ignore spaces around the number, so " 42 " is fine. Text like passed to , or passed to either, raises a . You'll learn to handle that in the lesson on errors.

2 exercises to try what you just read.

Exercise 1

Split the bill

Press Ctrl Enter or Check to test your code.

Exercise 2

Movie length

Press Ctrl Enter or Check to test your code.

"4.5"
int()
"ten"
ValueError

When several numbers share one line, split the line first. split() with no argument breaks on any run of spaces and gives you a list of strings:

map(int, ...) applies int to every piece, and the two names on the left unpack the result.

Arithmetic operators

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
//floor division7 // 23
%remainder7 % 21
**power7 ** 249

Two things surprise people coming from other languages:

  • / always gives a float, even for 8 / 4 (that's 2.0). Use // when you want a whole number.
  • // rounds down, toward minus infinity, so -7 // 2 is -4, not -3.

divmod(a, b) gives you both answers at once as a pair: divmod(130, 60) is (2, 10). That's perfect for turning minutes into hours and minutes.

The usual precedence rules apply: ** first, then *, /, //, %, then + and -. Use parentheses whenever the order isn't obvious to a human reader.

Python's integers have no size limit, so 2 ** 200 just works. Floats are approximations, so 0.1 + 0.2 prints 0.30000000000000004. That's normal for every language that uses binary floating point.

Shorthand updates

total += 5 means total = total + 5. The same pattern works for -=, *=, /=, //= and %=.

Rounding for display

To show money or measurements neatly, use a format spec in an f-string. :.2f means "a float with exactly two digits after the point":

This rounds only the displayed text; the variable keeps its full value.

Further reading

  • Built-in function input()
  • The Python Tutorial: Using Python as a calculator
  • Built-in function divmod()

Friends share a restaurant bill equally. The first line is the bill total (it may have decimals), the second line is the number of people. Print how much each person pays with exactly two digits after the decimal point.

Sample input:

Sample output:

Streaming apps show running times like 2 h 10 min. Read a whole number of minutes and print it in exactly that form: hours, a space, h, a space, minutes, a space, min.

Sample input:

Sample output:

name = input()
print(f"Hi, {name}!")
age = int(input())        # "29"  -> 29
height = float(input())   # "1.75" -> 1.75
a, b = input().split()          # "3 4" -> "3", "4"
a, b = int(a), int(b)

x, y = map(int, input().split())  # the same thing in one line
share = 10 / 3
print(f"{share:.2f}")   # 3.33
100
3
33.33
130
2 h 10 min