Week 3 of 8
Input and Interaction
Programs start listening. Students use input() to ask the player a question, wait for the answer, and use that answer in what the program says back. By the end they have a short chatbot that responds to whatever you type.
- Estimated time
- 50-60 minutes
- Project
- Mini Chatbot
The idea
input() is how a program listens. It shows a prompt, then stops and waits for the player to type and press Enter. Their answer gets stored in a variable, so the program can use it - their name, their guess, their choice - in what it does next. Keep in mind: input() always gives back text.
What you will learn
- Use input() to get an answer from the person running the program.
- Store an answer in a variable and use it later.
- Explain that the program pauses at input() until the user types something.
- Fix an input() line that is missing its quotation marks.
New words
- input()
- A Python command that asks a question and waits for the user to type an answer.
- prompt
- The message input() shows to tell the user what to type.
- user
- The person using the program - in a game, the player.
Project: Mini Chatbot
Edit the starter code below and press Run to see it work. Use Reset starter code to go back to the original at any time.
Run your program to see the output.
Expected output
What should I call you? Alex
Nice to meet you, Alex.
What game are you into right now? soccer
soccer? Good pick. Soon we'll build one of our own.Mini challenge
Add one more question - maybe their favorite color or animal - and use the answer in the program's reply.
Debugging challenge
Running this causes an error before the question even shows up. The message inside input() is text for the user to read. What does every piece of text need around it?
Broken code
name = input(What should I call you? )Show solutionHide solution
The prompt is text, so it needs quotation marks:
name = input("What should I call you? ")Extension challenge
Ask for the player's name and their favorite game, then print one sentence that uses both, like: Alex is ready to play soccer!
Reflect
Last week your program always said the same thing. Now it answers you. What could you ask a player at the start of a game to make it feel like it is about them?
Teacher notes
input() always returns text, even when the user types a number - that becomes important in Week 5, where we compare numbers and use int(). Watch for missing quotes around the prompt. In the coding workspace the prompt and the typed answer both appear in the output panel, so the expected output shows a sample conversation.
Facilitating this lesson? See the teacher & librarian guide for how to run it, common mistakes, and an offline backup activity.
Finished this lesson? Mark it complete to unlock the next week.