Getting Input: Talking to Your Robot
Give your Python robot ears! Learn how to collect keyboard inputs using the input function, convert types, and create interactive chat scripts.
Welcome back, conversationalist! 💬
So far, our Python robot has done all the talking using print(). But a real conversation is a two-way street! Today, we are going to give our robot ears so it can listen to what we type and reply.
To do this, we use the input() command!
How the Robot Listens (The input flow)#
The input() command pauses your program and waits for you to type something on your keyboard. Once you press Enter, Python takes your words and saves them inside a variable box!
graph TD
Question["1. Robot asks: 'What is your name?'"] --> Input["2. You type: 'Alex' and hit Enter"]
Input --> Box["3. Value 'Alex' is saved inside 'name' variable"]
Box --> Greet["4. Robot says: 'Nice to meet you, Alex! 👋'"]
Here is how we write this in Python:
name = input("What is your name? ")
print("Nice to meet you, " + name + "! 👋")pythonWhen you run this code, the robot will display the question, pause, and wait. Once you type your name and hit Enter, it will print the greeting!
The Secret Trap: Numbers vs Words! ⚠️#
There is a secret trap with input(). The robot assumes everything you type is a word (a String), even if you type a number!
For example:
age = input("How old are you? ")
print(age + 5) # 💥 ERROR! Python cannot add a number to a word.pythonTo fix this, we must use a magic spell called int() to convert the typed words into a real number:
age = input("How old are you? ")
age = int(age) # Converts the text (like "10") into a real number (10)
print("In 5 years, you will be:", age + 5)pythonTry It Yourself! 🎮#
Open your Python editor and try creating this mini chat game:
color = input("What is your favorite color? ")
if color == "blue":
print("No way! Blue is my favorite color too! 💙")
else:
print(color + " is a very cool color! 🎨")pythonTry typing different colors and see how the robot reacts!
With the power of input(), you can now build interactive text adventure games where the player types in commands like "go left", "open door", or "attack monster". Keep experimenting!