← All lessons
Python basics · Lesson 5 of 10

Input and types

So far programs have only talked. input() lets them listen: it shows a question, waits for the person to type something and press Enter, and gives back what they typed. Store it in a variable to use it.

name = input("What's your name? ")
print(f"Nice to meet you, {name}!")

If someone types Priya, that prints Nice to meet you, Priya!. (The examples on this site can't wait for typing, so the input ones don't show their output.)

Here's the catch: input() always gives back a string, even if the person typed digits. Text and numbers are different types, and Python won't mix them by itself. "5" + 1 is an error, because Python won't guess whether you meant 6 or "51". It stops with a TypeError.

type() tells you what type a value is. You'll see int, float, str (string) and others.

print(type(5))
print(type(2.5))
print(type("5"))
Prints
<class 'int'>
<class 'float'>
<class 'str'>

To change a value's type, use the type's name as a function. This is called converting (or casting). int("5") turns the text "5" into the number 5, float("2.5") gives 2.5, and str(42) turns a number into the text "42".

text = "20"
number = int(text)
print(number + 1)
print(text + "1")
print("Age: " + str(30))
Prints
21
201
Age: 30

So a program that asks for a number converts the answer straight away:

age = int(input("How old are you? "))
print(f"In ten years you'll be {age + 10}.")

If the text isn't a number, converting fails: int("ten") stops with a ValueError (the type was right, a string, but its value couldn't be turned into a number). int("2.5") fails too; use float() for decimals. int() on a float chops off the decimal part: int(3.9) is 3.

Practice

What does this print?

print(type("12"))
More info

Quick reference

input("question")Shows the question, waits for typing and Enter, and gives back a string.
type(x)x's type: int, float, str and so on.
int() float() str()Convert to a whole number, a decimal or text.
TypeErrorTwo types that don't go together, like "5" + 1.
ValueErrorThe right type but a value that can't be used, like int("ten").

Related courses