Basics of User Input

Code Examples

Example 1

This example shows the most basic use of input(). When the program runs, it displays the text "What is your name? " on the screen and waits for the user to type something. After the user types their name and presses Enter, the program stores that name in the variable user_name. Then it uses this variable to create a personalized greeting. If the user types "Alex", the program will display "Hello, Alex!".

# Basic input and output example
user_name = input("What is your name? ")
print("Hello, " + user_name + "!")

Example 2

This simple "echo" program demonstrates how input() captures exactly what the user types. The program prompts the user to type anything, stores their input in the variable message, and then displays it back to them. This helps beginners understand that whatever is typed becomes a string that can be stored and used later in the program.

# Echo what the user types
message = input("Type something and I'll repeat it: ")
print("You said:", message)

Example 3

This example shows how to collect multiple pieces of information from a user. The program asks for the user's name, age, and favorite hobby one by one, storing each response in a separate variable. Notice that we don't do any conversion on the age yet for now, we're just treating all inputs as strings. After collecting the information, the program displays a summary of what the user entered.

# Collecting multiple inputs
print("Please tell me about yourself:")
name = input("Name: ")
age = input("Age: ")
hobby = input("Favorite hobby: ")

# Display the collected information
print("\nYour Information:")
print("Name:", name)
print("Age:", age)
print("Favorite hobby:", hobby)