User Input In Python — PBA Institute Tutorial
Chapter 02 · Python Programming Series
12 min read Beginner

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(), or bool() to convert the result.
User Input — Syntax
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 a str object and returned. Even if the user types 25, 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 by list()/map() for collections. If conversion fails, Python raises ValueError, which you can catch with try/except.
  • Reading multiple values on one line: Use input().split() to break a single line into pieces using whitespace (or any delimiter). Combine with map() 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

Example 1 — Greeting the User
name = input("Enter your name: ")
print("Welcome,", name, "to PBA Institute!")
Output Enter your name: Riya
Welcome, Riya to PBA Institute!
Example 2 — Adding Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
Output Enter first number: 10
Enter second number: 20
Sum = 30
Example 3 — Float Input (Area of a Rectangle)
length = float(input("Length: "))
width  = float(input("Width: "))
print("Area =", length * width)
Output Length: 5.5
Width: 3.2
Area = 17.6
Example 4 — Multiple Inputs on One Line
a, b, c = input("Enter three numbers: ").split()
print("Numbers:", a, b, c)
Output Enter three numbers: 4 8 15
Numbers: 4 8 15
Example 5 — Convert Multiple Numbers Using map()
nums = list(map(int, input("Enter numbers: ").split()))
print("Total =", sum(nums))
Output Enter numbers: 1 2 3 4 5
Total = 15
Example 6 — Safe Input with try/except
try:
    age = int(input("Enter your age: "))
    print("Next year you will be", age + 1)
except ValueError:
    print("Please enter a valid number.")
Output Enter your age: twenty
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 prefer float().
  • Combine split() with map() for clean multi-value reading.
  • Wrap risky conversions in try/except ValueError to keep the program robust.
  • Never use the dangerous eval(input(...)) with untrusted input — it executes arbitrary code.

Common Mistakes

  • Forgetting type conversion: x = input() + 1 raises TypeError because x is a string.
  • Confusing input() with raw_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" is False — trailing spaces matter.
  • Reading numbers with only one int(): int("10 20") fails — use split() 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() and eval(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

Next

Go to Next Chapter