Common input, output and arithmetic fragments for Python 3. See also the Java and C++ versions.

Contents

Reading input

One value per line

input() returns the next line as a string (without the newline), so convert it to the type you need:

name = input()             # text
n = int(input())           # whole number
x = float(input())         # number with a decimal point

int("3.5") is an error. If a value might have a decimal point but you need a whole number, convert in two steps: int(float(text)).

Several values on one line

split() breaks a line into a list of strings at spaces (any amount of whitespace). Pick out each piece by its position in the list (starting at 0) and convert it to the type you need:

parts = input().split()        # "Alice 11 17 92.5"
                               #   -> ["Alice", "11", "17", "92.5"]
name = parts[0]                # "Alice"
grade = int(parts[1])          # 11
age = int(parts[2])            # 17
score = float(parts[3])        # 92.5

A list of numbers on one line

When a line holds a list of numbers, split() gives you a list of strings. Loop over it to build a list of integers:

words = input().split()        # "5 10 15" -> ["5", "10", "15"]
nums = []
for w in words:
    nums.append(int(w))
# nums is now [5, 10, 15]

Other separators

Pass the separator to split, and use strip() to remove extra spaces around each piece:

pieces = input().split(",")    # "red, green ,blue"
                               #   -> ["red", " green ", "blue"]
fields = []
for p in pieces:
    fields.append(p.strip())
# fields is now ["red", "green", "blue"]

A count followed by that many lines

n = int(input())
for i in range(n):
    line = input()
    # process line

Every line until the end of the input

Use this when the problem does not say how many lines there will be:

import sys

for line in sys.stdin:
    line = line.strip()        # remove the trailing newline (and spaces)
    if line != "":             # skip blank lines, if the problem allows
        print(line)            # replace with code to process line

Or read everything at once into a list of lines:

import sys

lines = sys.stdin.read().splitlines()

Reading from a file

with open("data.txt") as f:
    for line in f:
        line = line.strip()
        # process line

The file name is relative to the folder the program runs in, which in some IDEs is not the folder holding your .py file. If the file is “not found”, try the full path, such as open(r"C:\Users\me\data.txt") (the r keeps the backslashes from being treated as escapes).

Working with numbers

Converting between float and int

int(3.7)            # 3   (int() drops the fraction: rounds toward zero)
int(-3.7)           # -3
float(5)            # 5.0
round(3.7)          # 4
round(2.5)          # 2   (!) ties round to the even number
round(3.5)          # 4
round(3.14159, 2)   # 3.14

If a problem says “round to the nearest whole number” and halves matter, round may not do what you expect. For positive numbers, int(x + 0.5) rounds halves up.

Division

7 / 2       # 3.5  -- / always gives a float
7 // 2      # 3    -- // is floor division (rounds down)
-7 // 2     # -4   -- down, not toward zero
7 % 2       # 1    -- remainder
-7 % 2      # 1    -- remainder takes the sign of the right side
divmod(17, 5)   # (3, 2): quotient and remainder together

Rounding up and down

import math

math.floor(3.7)     # 3
math.ceil(3.2)      # 4
math.floor(-3.7)    # -4

math.ceil(a / b) works for small numbers, but a / b is a float and can be slightly off for large values. For integers, “divide and round up” is safer with integer arithmetic only:

def ceildiv(a, b):
    return -(a // -b)

ceildiv(7, 2)       # 4  (for example, boxes needed for 7 items, 2 per box)
ceildiv(8, 2)       # 4

Other handy operations

abs(-5)             # 5
min(3, 8, 1)        # 1
max(nums)           # largest value in a list
sum(nums)           # total of a list
2 ** 10             # 1024 (power)

Python integers never overflow, so 2 ** 100 is exact.

Math functions

import math

math.sqrt(2)                    # 1.4142135623730951
math.pi                         # 3.141592653589793
math.sin(math.radians(30))      # 0.49999999999999994 -- trig uses radians
math.degrees(math.atan2(1, 1))  # 45.0
math.hypot(3, 4)                # 5.0, distance from (0,0) to (3,4)
math.log(100, 10)               # 2.0
math.exp(1)                     # 2.718281828459045

Floating-point results are rarely exact (note the sine above). Compare floats with a tolerance instead of ==:

if abs(a - b) < 1e-9:
    print("equal")
# or: math.isclose(a, b)

Formatting output

print(0.1 + 0.2) prints 0.30000000000000004. When a problem asks for a specific number of decimal places, use an f-string:

x = 3.14159
print(f"{x:.2f}")           # 3.14
print(f"{x:8.2f}")          # "    3.14" (8 characters wide, right-aligned)
print(f"{x:<8.2f}|")        # "3.14    |" (left-aligned)
print(f"{1234567.891:,.2f}")  # 1,234,567.89
print(f"{42:5d}")           # "   42"
print(f"{0.256:.1%}")       # 25.6%
print(f"Total: ${x:.2f}")   # Total: $3.14

Use d only for integers: f"{3.5:d}" stops the program with ValueError: Unknown format code 'd' for object of type 'float'. The f code works for both, so f"{5:.2f}" prints 5.00.

Printing several values:

print(a, b, c)              # separated by spaces
print(a, b, c, sep=",")     # separated by commas
print(a, end="")            # no newline afterward

To print a list on one line with spaces between the values (and no extra space at the end), convert each value to a string and join them:

strs = []
for v in nums:
    strs.append(str(v))
print(" ".join(strs))       # "5 10 15"

Match the expected output exactly: extra spaces, missing blank lines, or a different number of decimal places can cause a solution to fail.

Example: average of the input

Reads numbers (any number per line, any number of lines) until the end of the input and prints their average to two decimal places:

import sys

total = 0.0
count = 0
for line in sys.stdin:
    for token in line.split():
        total += float(token)
        count += 1

if count > 0:
    print(f"{total / count:.2f}")

Example: sorting and searching

The goal of this example is to illustrate reading data, sorting it, and searching for values. It is written to be easy to follow rather than as fast as possible; for instance, the search simply checks every entry.

The program reads a file of names and ages (in years), sorts the entries by age (and by name when two ages are equal), displays them all in order, and then displays the ages of everyone named Parker. Suppose people.txt holds one name and age per line (see Reading from a file for where to put it):

Parker 17
Alex 16
Jordan 17
Parker 15
Casey 16
# Read every name and age from the file. Each entry is stored as a
# pair (a tuple) with the age first, such as (17, "Parker").
people = []
with open("people.txt") as f:
    for line in f:
        parts = line.split()           # "Parker 17" -> ["Parker", "17"]
        if len(parts) == 2:            # skip blank lines
            name = parts[0]
            age = int(parts[1])
            people.append((age, name))

# Sort. Python compares pairs one item at a time: by age first, and by
# name only when the ages are equal. That is why the age comes first.
people.sort()

# Display all entries in order. Each pair is split back into its age
# and name.
for age, name in people:
    print(name, age)

# Search: check every entry and display the age of each one named Parker.
print("Ages of Parker:")
for age, name in people:
    if name == "Parker":
        print(age)

Output:

Parker 15
Alex 16
Casey 16
Jordan 17
Parker 17
Ages of Parker:
15
17

Names are compared character by character, and every uppercase letter comes before every lowercase one, so "Zoe" sorts before "adam".