Talking to Your Program: input()

Python for Absolute Beginners · Lesson 7

1 / 16

What you'll learn

2 / 16

Programs that listen

3 / 16

Your first input

name = input("What is your name? ")
print("Nice to meet you, " + name + "!")

Output:
What is your name? Sam
Nice to meet you, Sam!

The text in parentheses is the prompt — end it with a space so the typing doesn't bump against the question.

4 / 16

Type in the right place

5 / 16

What you type is always text

6 / 16

Text plus text, in code

age = input("How old are you? ")
print(age)
print(age + age)

Output:
How old are you? 12
12
1212

age + age printed 1212, not 24 — + joins text instead of adding.

7 / 16

The TypeError

age = input("How old are you? ")
print(age + 1)

Output:
TypeError: can only concatenate str (not "int") to str

Read it slowly: concatenate means join, str means text, and int means whole number. It points at the exact problem.

8 / 16

A friendlier print: commas

print("Hello,", "Sam")
print("Sam is", 12, "years old")

Output:
Hello, Sam
Sam is 12 years old

Commas put a space between pieces and mix text and numbers freely. Use commas to show things; use + to build one piece of text to store.

9 / 16

Turning text into a number

age_text = input("How old are you? ")
age = int(age_text)
print("Next year you will be", age + 1)

Output:
How old are you? 12
Next year you will be 13

Now age holds the number 12, so age + 1 is 13.

10 / 16

One line, and when it fails

age = int(input("How old are you? "))

Output (type twelve):
How old are you? twelve
ValueError: invalid literal for int() with base 10: 'twelve'

Read it from the inside out: ask first, then convert. int() can only convert text that looks like a whole number — a decimal like 12.5 fails too.

11 / 16

Putting it together

name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello,", name)
print("In 10 years you will be", age + 10)

Output:
What is your name? Sam
How old are you? 12
Hello, Sam
In 10 years you will be 22

Run it again with different answers — the output changes while the program stays exactly the same.

12 / 16

Hands-on exercise

13 / 16

Key takeaways

14 / 16

Take the quiz

Take the Lesson 7 quiz — 5 quick questions to check what you learned.

15 / 16

Next lesson

Booleans and Comparisons

16 / 16

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.