Make the Machine Ask You Something

Explore how to get user input and convert data types.

So far, we’ve been instructing Python on what to do. Now, let’s make Python ask us something!

This lesson will teach us to use the input() function to create simple, interactive programs.


Python wants to know you

Note: After you run the widget below, you’ll be expected to enter the input. Click inside the terminal window to type your input.

name = input("What is your name? ")
print("Hello,", name)
Asking for user input and printing a response

We just had a two-way conversation with our computer!


How it works

  • input() shows a prompt and waits for the user to type something.

  • It always returns a string (even if we type a number).

  • We can store the result in a variable.

age = input("How old are you? ")
print("You are", age, "years old.")

print(type(age))
Storing input in a variable and printing a sentence

Even if you enter a number (like 25), Python treats everything from input() as text—also called a string. We can see this by printing type(age). Add the following line of code in the widget above to see what it prints.

print(type(age))

Printing type(age), would give us:

<class 'str'>

This tells us age is a string, not a number—even if it looks like one! So even if you type a number like 42 or 3.14, it will be treated as a string "42" or "3.14".

Try this out! Notice how the result is text, even if it looks like a number.


How to use the input as a number

If we want to do math with what the user types, we need to convert it from a string to a number. For example, if we want to do math (like adding 5 years to the age we entered), we have to tell Python, “Hey, treat this text as a number!” We do that using something called type casting, which just means converting one type to another—in this case, from text to a number.

age = input("How old are you? ")
future_age = int(age) + 5
print("In 5 years, you’ll be", future_age)
Code converting input from string to number using int()

In this example, int(age) changes the user’s input from text to a number (an integer) so we can add 5 to it. If you didn’t convert it, Python would get confused—it can’t add a number to a word!

Try removing int() and see what error you get—that’s how Python tells you it needs a number, not a word.

The int() function converts the input from text to a number.


Your turn: Build a mini Q&A

name = input("Name: ")
# fav_food = Write code to take its input. 
# pet = Write code to take its input

print("Hi", name, "! Enjoy your", fav_food, "with your future pet", pet, "!")
Collecting multiple inputs and printing a fun sentence

Customize the prompts and create a fun interactive story!