Python input()
Function
The input() function is used to read user input from the keyboard. It's one of the first functions you'll use when making interactive Python programs.
Syntax
input(prompt)
Parameters:
prompt
(optional) – A string, shown to the user before input is read.
Returns:
- Always returns the input as a
string
.
Example 1: Basic Input
name = input("What is your name? ")
print("Hello, " + name)
What is your name? Alice
Hello, Alice
Example 2: Taking Numeric Input
age = input("Enter your age: ")
print("You are", age, "years old")
Enter your age: 25
You are 25 years old
Note:
Even if you type numbers, input()
returns them as strings. You need to convert them manually using int()
or float()
.
Example 3: Converting Input
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Sum is:", num1 + num2)
Enter first number: 5
Enter second number: 10
Sum is: 15
Use Case: Making Interactive Programs
- Ask questions and receive answers from the user
- Create command-line quizzes or games
- Take dynamic inputs in loops
Common Mistakes
- Forgetting to convert numeric input using
int()
orfloat()
- Trying to perform math directly on the string result of
input()
- Not handling invalid input (e.g., letters instead of numbers)
Interview Tip
In Python coding interviews, input is often simulated using input()
. Always remember that it returns strings and type conversion may be required.
Summary
input()
pauses the program and waits for user input- Returns the result as a
string
- Use
int()
,float()
, oreval()
to convert the input if needed
Practice Problem
Write a program that asks the user for two numbers and prints the multiplication result.
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Product is:", a * b)