Taking User Input
Interactive Python programs come alive when they can read information from the user. In this chapter you'll learn how the input() function works, how to capture text, numbers and multiple values from the keyboard, and how to convert and validate user-entered data the right way.
Overview
Interactive
Make your scripts react to real user actions instead of running with fixed values.
Built-in
No imports or libraries required — input() ships with Python by default.
Flexible
Works with strings, numbers, lists, and even multi-value inputs with one call.
Simple Syntax
One short line of code is enough to capture data from the keyboard.
Safe by Default
Returns a string so unexpected characters never crash the program automatically.
Syntax
- The
input()function always returns a string, regardless of what the user types. - An optional prompt argument is displayed to the user — keep it short and end with a space.
- Use type-casting functions like
int(),float(), orbool()to convert the result.
variable = input(prompt)
# Type-cast when you need a number
age = int(input("Enter your age: "))
price = float(input("Enter price: "))
Detailed Explanation
- How input() works: When Python reaches an
input()call the program halts and waits. The cursor blinks on the terminal until the user presses Enter. Everything typed before Enter is captured as astrobject and returned. Even if the user types25, Python stores it as the string"25", not the number 25. - Why it always returns a string: Python is designed for predictability. By guaranteeing a string return type,
input()never fails because of unexpected data. You decide how to interpret the data — as text, integer, float, list, etc. — by applying the correct conversion. - Type conversion: Wrap the input call with
int()for whole numbers,float()for decimals, or use.split()followed bylist()/map()for collections. If conversion fails, Python raisesValueError, which you can catch withtry/except. - Reading multiple values on one line: Use
input().split()to break a single line into pieces using whitespace (or any delimiter). Combine withmap()to convert each piece in one expression. - Best practices: Always show a clear prompt, strip extra whitespace with
.strip(), validate the value before using it, and never trust raw user input in production — sanitize it.
Code Examples
name = input("Enter your name: ")
print("Welcome,", name, "to PBA Institute!")
Welcome, Riya to PBA Institute!
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
Enter second number: 20
Sum = 30
length = float(input("Length: "))
width = float(input("Width: "))
print("Area =", length * width)
Width: 3.2
Area = 17.6
a, b, c = input("Enter three numbers: ").split()
print("Numbers:", a, b, c)
Numbers: 4 8 15
nums = list(map(int, input("Enter numbers: ").split()))
print("Total =", sum(nums))
Total = 15
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Please enter a valid number.")
Please enter a valid number.
Real-World Use Cases
Login Forms
Username and password capture in command-line apps and quick prototypes.
Calculators
Read operands and an operator from the user before computing the result.
Billing Software
Take item name, quantity, and price interactively to generate a bill.
Mini Games
Quiz games, number-guessing, hangman — all rely on keyboard input.
Chatbots & CLI Tools
Conversational scripts read user messages line by line and respond.
Data Entry Scripts
Populate CSVs, JSON, or databases with values typed at the terminal.
Notes & Pro Tips
- Always include a meaningful prompt — blank inputs confuse users.
- Strip extra spaces with
input().strip()to avoid hidden bugs in comparisons. - Use
int()only when you are sure the value is whole; otherwise preferfloat(). - Combine
split()withmap()for clean multi-value reading. - Wrap risky conversions in
try/except ValueErrorto keep the program robust. - Never use the dangerous
eval(input(...))with untrusted input — it executes arbitrary code.
Common Mistakes
- Forgetting type conversion:
x = input() + 1raisesTypeErrorbecausexis a string. - Confusing
input()withraw_input():raw_input()existed only in Python 2 and was removed in Python 3. - Assuming numeric input: the user may type letters; always validate.
- Misusing
eval(): it runs whatever the user types — a serious security risk. - Not stripping whitespace:
"yes " == "yes"isFalse— trailing spaces matter. - Reading numbers with only one
int():int("10 20")fails — usesplit()first.
Practice Problems
- Problem 1: Write a program that asks for the user's first and last name and prints the full name.
- Problem 2: Take two numbers from the user and print their sum, difference, product and quotient.
- Problem 3: Read a temperature in Celsius and convert it to Fahrenheit.
- Problem 4: Ask the user for five marks in one line and print the average.
- Problem 5: Read a sentence and print how many words it contains.
- Problem 6: Build a simple BMI calculator that asks for weight (kg) and height (m) and prints the BMI.
Interview Questions
- Q1. What is the return type of the
input()function in Python? - Q2. How do you take an integer input from the user?
- Q3. How can you read multiple values from the user in a single line?
- Q4. What is the difference between
input()andeval(input())? Why is the latter unsafe? - Q5. How do you handle invalid input from the user without crashing the program?
- Q6. What was
raw_input()in Python 2 and why was it removed in Python 3?
Frequently Asked Questions
- Q1: Why does input() always return a string?
Python's input() captures keystrokes as text. Treating every input as a string keeps behaviour predictable; you choose how to convert it. - Q2: How do I take integer input?
Wrap input() with int(), e.g. age = int(input('Age: ')). - Q3: How do I read more than one value at a time?
Use input().split() — it returns a list of tokens — and convert each token if needed: list(map(int, input().split())). - Q4: What happens if the user types text where I expected a number?
Python raises ValueError. Handle it with a try/except block to keep your program user-friendly. - Q5: Is eval(input()) safe?
No. eval executes anything the user types, including dangerous code. Avoid it for any non-trusted input. - Q6: Can I set a default value when the user just presses Enter?
Yes — store the result, check if it is empty with .strip(), and assign your own default if it is.
Summary
The input() function is your gateway to interactive Python. It pauses execution, displays an optional prompt, and returns a string. With a small dose of type conversion, split(), and try/except, you can build any interactive application — from quick calculators to full command-line tools. Practice converting inputs and validating them — these habits will follow you into every Python project.
Continue Learning
Previous
Go to Previous Chapter