← Python from Scratch Lesson 11 of 78 · 10 XP

Type conversion

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

input() always returns a string, even if a number was typed. To do arithmetic, you have to turn the string into a number — this is type conversion (casting):

x = input()      # typed 5 → x = "5" (a string)
x = int(x)       # now x = 5 (a number)

The main functions:

int("42")      # 42
int(3.9)       # 3   — the fractional part is dropped, NOT rounded
float("2.5")   # 2.5
str(100)       # "100"

Usually int() is wrapped straight around input():

age = int(input("Age: "))

If a string can't be turned into a number, you get an error: int("hello") → ValueError.

Task. Read two lines with numbers. First print their sum as numbers, and on the second line their concatenation as strings. For 3 and 4: 7, then 34.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.