Python User Input
User input allows users to enter data while the program is running. Python uses the input() function to take input from users.
Why User Input is Important?
- User input makes programs interactive.
- Programs can work with dynamic data.
- Users can enter their own values.
- User input is used in forms, calculators, games, and real applications.
Basic User Input
The input() function is used to take input from the keyboard.
name = input("Enter your name: ")
print(name)
How this Program Works?
Step 1: Python shows the message:
Enter your name:
Step 2: User enters a value.
Rahul
Step 3: The entered value gets stored inside variable name.
Step 4: Python prints the stored value.
Rahul
Input Always Returns String
By default, the input() function returns data as a string.
age = input("Enter your age: ")
print(age)
print(type(age))
Output
25 <class 'str'>
Even though the user entered 25, Python still stores it as a string.
Converting Input to Integer
Use the int() function to convert input into integer.
age = int(input("Enter your age: "))
print(age)
print(type(age))
Output
25 <class 'int'>
Now Python stores the value as integer instead of string.
Taking Decimal Input
Use the float() function for decimal numbers.
price = float(input("Enter price: "))
print(price)
print(type(price))
Output
99.99 <class 'float'>
Taking Multiple Inputs
You can take multiple values from users.
name = input("Enter your name: ")
city = input("Enter your city: ")
print(name)
print(city)
User Input Addition Example
This example creates a simple calculator using user input.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
total = num1 + num2
print(total)
Example Calculation
num1 = 10 num2 = 20 total = 10 + 20
Output
30
String Concatenation with Input
Input values can also be combined with strings.
name = input("Enter your name: ")
print("Welcome " + name)
Output
Welcome Rahul
Common Mistake
If numbers are not converted using int(), Python performs string joining instead of addition.
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print(num1 + num2)
Example
num1 = "10" num2 = "20"
Python joins both strings.
1020
To perform actual addition, use int().
Real Life Example
This example stores student information entered by the user.
student_name = input("Enter student name: ")
student_marks = int(input("Enter marks: "))
print("Student Name:", student_name)
print("Marks:", student_marks)
Summary
- input() function is used to take user input.
- Input values are stored as strings by default.
- Use int() for integer input.
- Use float() for decimal input.
- User input makes programs interactive.
- User input is used in calculators, forms, games, and applications.