Skip to content
Programming Foundations with Python
Path outline

Lesson

Input, variables, and arithmetic

Read integers, calculate with them, and print a result.

Reading information

A program becomes useful when it can work with different values. Instead of writing every number into the source, read the values supplied by the problem. Python's input() reads one line as text. int() converts text representing an integer into an integer value.

A variable gives a value a name. In distance = 12, the equals sign assigns 12 to distance. It does not ask whether the two sides are equal. A later assignment can replace the value associated with the name.

A complete example

Suppose one input line contains the number of boxes and the number of items in each box. This program calculates the total.

Python 3
boxes, per_box = map(int, input().split())
total = boxes * per_box
print(total)

For input:

text
4 6

The output is:

text
24

input() reads the line "4 6". split() separates it into two pieces. map(int, ...) converts both pieces to integers. The assignment gives the first integer to boxes and the second to per_box. Multiplication happens after those values exist.

For a single integer on one line, use n = int(input()). For two integers on separate lines, call input() twice. Always read the input format before choosing a pattern. Reading two values on one line is different from reading one value on each of two lines.

Integer arithmetic

Use + for addition, - for subtraction, and * for multiplication. Parentheses control the order of operations. Multiplication normally happens before addition, so 2 + 3 * 4 produces 14.

The / operator produces a division result that can contain a fractional part. Use // when a problem asks for an integer quotient, and % for a remainder. For example, 17 // 5 is 3 and 17 % 5 is 2. Negative operands require extra care because Python's integer division rounds down.

Common mistakes

Adding strings joins their text instead of adding numbers. The strings "4" and "6" produce "46" when added. Convert input before doing arithmetic. Use ordinary straight quotation marks in code, and do not type the sample input directly into the source.

Problem 1409 gives two integers on one line. Read both, compute their sum, and print only the result. Try small values and a value of zero before submitting. A sample is one example, so passing it does not prove that every valid input works.

Begin with Next Integer to read one value. After adding two values in problem 1409, extend the same input pattern to three values in Sum of Three Integers. For each problem, change your test values and predict the result before running the program.

Sign in to save your progress.

Sign in

Practice