Python for AIPython for AI
Python Basics

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.

Show prompt
"Your name: "
→
Wait
user types
→
Enter
user confirms
→
Return text
always a str
input() stops the program until the user presses Enter.
python
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.

Add a space at the end of your prompt text, like "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.

python
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:

python
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.

python
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.

python
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.

The in-browser exercises on this site can't pause for keyboard input. Practice input() in VS Code with your own Python file.

Common mistakes

  • Doing math on raw input: input("Age: ") + 1 raises a TypeError. Convert with int() first.
  • Comparing without cleaning: "Yes " == "yes" is False. Use .strip().lower().
  • Forgetting that int() crashes if the user types letters. You'll learn to handle this with try/except later.

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.