Getting user input with input().

The input() function is how you make your Python programs interactive. It tells the computer to pause execution, wait for the user to type something on their keyboard, and hit the Enter key. Once the user hits Enter, the program takes whatever they typed and continues running.

The Golden Rule of input()

Everything typed into an input() function is returned as a String (str). Even if the user types a number like 42, Python sees it as the text "42". If you want to do math with it, you must convert it (typecast it) to an integer or float first.

Here are 10 examples showing how to use the input() function, from basic to advanced.

Example 1: The Simplest Form

You can use input() without any text. The console will just blink and wait, which can be confusing for the user, but it works.

Python

print("Type something and press Enter:")
user_text = input()
print("You typed:", user_text)

Example 2: Adding a Prompt String

The most common way to use input() is to put a string inside the parentheses. This string prints to the screen to tell the user what to do.

Python

name = input("What is your name? ")
print(f"Hello, {name}!")

Example 3: The Data Type Trap (Proving it’s a String)

If you ask for a number and try to add to it without converting it, Python will throw an error (or do string concatenation). This proves input() always creates strings.

Python

number = input("Enter the number 5: ")
print(type(number))  # This will output: <class 'str'>

# If you try print(number + 10), you will get a TypeError!

Example 4: Converting to an Integer (int)

To do math with whole numbers, wrap the input() function inside the int() function.

Python

age = int(input("How old are you? "))
future_age = age + 10
print(f"In 10 years, you will be {future_age} years old.")

Example 5: Converting to a Float (float)

If you need a number with decimals (like money or measurements), wrap the input() function inside the float() function.

Python

price = float(input("Enter the price of the item: $"))
tax = price * 0.07
total = price + tax
print(f"Your total with 7% tax is ${total}")

Example 6: Cleaning Up Spacing (.strip())

Users often accidentally type spaces before or after their answers. You can attach .strip() to the end of your input to automatically remove invisible white spaces at the beginning and end.

Python

username = input("Enter your username: ").strip()
# If the user types "   ninja99   ", it gets saved perfectly as "ninja99"
print(f"Welcome back, '{username}'!")

Example 7: Making Inputs Case-Insensitive (.lower())

If you are checking if a user answered “yes” or “no”, you don’t want to worry about whether they typed “YES”, “Yes”, or “yes”. You can use .lower() to convert their input to lowercase immediately.

Python

answer = input("Do you want to play again? (yes/no): ").lower()

if answer == "yes":
    print("Restarting game...")
else:
    print("Game over.")

Example 8: Getting Multiple Inputs at Once (.split())

You can ask the user to type multiple things on one line (separated by spaces) and split them into separate variables using .split().

Python

first, last = input("Enter your first and last name separated by a space: ").split()
print(f"First Name: {first}")
print(f"Last Name: {last}")

Example 9: Using input() as a “Pause” Button

Sometimes you don’t actually care what the user types; you just want the program to pause so they have time to read something before moving on. In this case, you don’t even need to save the input to a variable.

Python

print("--- LEVEL 1 COMPLETED ---")
print("You found a hidden treasure chest!")
input("Press Enter to open the chest...")
print("You got 100 gold coins!")

Example 10: A Mini-Calculator (Combining Concepts)

Here is how you combine prompts, typecasting, and formatting into a complete, interactive block of code.

Python

print("--- Area Calculator ---")
width = float(input("Enter the width in meters: "))
length = float(input("Enter the length in meters: "))

area = width * length
print(f"The total area is {area} square meters.")

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *