Getting input
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Ask the user with input
input()waits for the user to type a line and press Enter.- It gives back what they typed. Store it in a variable.
- Join two strings together with
+.
name = input()
print("Welcome, " + name)
input always gives a string
- Whatever the user types comes back as a string.
- Even if they type
5, you get the text"5", not the number. - So
"5" + "5"is"55"(joined text), not10.
print("5" + "5") # 55 — joined text, not the number 10
Turn text into a number
int(...)turns text into a whole number:int("5")→5.float(...)turns text into a decimal:float("2.5")→2.5.- Convert first, then you can do maths.
age = int(input())
print(age + 1)
Now you try
- These checks type the input for you, so just read with
input(). - Each task needs only one
input().
Read a name with input(), then print Hi, then the name then !. For the input Sam, the output should be Hi, Sam!.
Click Run to see the output here.
Read a whole number with input(), convert it with int(...), then print the number plus 100. For input 7, the output should be 107.
Click Run to see the output here.
Read a whole number, convert it with int(...), then print its square (the number times itself). For input 5, the output should be 25.
Click Run to see the output here.