User input
Ask the user for information with input()
So far your programs have used values you typed into the code. Real programs, like a chatbot, need to ask the user for information while they run. That's what input() does.
How input() works
input() pauses your program, shows a message, and waits for the user to type something and press Enter. Whatever they typed is returned as a string.
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")Run this in your terminal with python main.py. The program waits until you type your name.
"Your name: ". Otherwise the user's typing sticks right against the colon.Input is always text
Even if the user types 25, you get the string "25". To do math, convert it first.
age_text = input("How old are you? ")
age = int(age_text)
print(f"Next year you will be {age + 1}.")You can also convert in a single line:
age = int(input("How old are you? "))Cleaning the input
Users add extra spaces and mix upper and lower case. Clean the text before you check it.
answer = input("Continue? (yes/no) ").strip().lower()
if answer == "yes":
print("Let's go!")
else:
print("Okay, stopping.")Building a chat prompt
This is the heart of every command-line chatbot: read what the user wrote and turn it into a message.
user_text = input("You: ")
message = {"role": "user", "content": user_text}
print(message)Later you'll put this inside a loop, so the chatbot keeps asking until the user types quit.
input() in VS Code with your own Python file.Common mistakes
- Doing math on raw input:
input("Age: ") + 1raises aTypeError. Convert withint()first. - Comparing without cleaning:
"Yes " == "yes"isFalse. Use.strip().lower(). - Forgetting that
int()crashes if the user types letters. You'll learn to handle this withtry/exceptlater.
What's next?
Now your programs can listen. Next, you'll learn data structures: lists, dictionaries, tuples, and sets let you store many values together.