Python allows users to enter data during program execution using the input() function.
The input() function pauses the program and waits for the user to enter a value.
Getting User Input
Example:
name = input("Enter your name: ")
print(name)
Output:
Enter your name: John
John
Input Always Returns a String
The input() function always returns the entered value as a string.
Example:
age = input("Enter your age: ")
print(type(age))
Output:
<class 'str'>
Converting Input to Integer
Use the int() function to convert user input into an integer.
Example:
age = int(input("Enter your age: "))
print(age)
Output:
Enter your age: 25
25
Converting Input to Float
Use the float() function to convert user input into a float.
Example:
price = float(input("Enter price: "))
print(price)
Output:
Enter price: 99.99
99.99
Taking Multiple Inputs
You can take multiple inputs and store them in different variables.
Example:
name = input("Enter your name: ")
city = input("Enter your city: ")
print(name)
print(city)
Output:
Enter your name: John
Enter your city: London
John
London
Using User Input in Calculations
Example:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(num1 + num2)
Output:
Enter first number: 10
Enter second number: 20
30
Taking Multiple Values in One Line
Use split() to separate values entered in a single line.
Example:
name, age = input("Enter name and age: ").split()
print(name)
print(age)
Output:
Enter name and age: John 25
John
25
Practical Example
Create a simple welcome message using user input.
Example:
name = input("Enter your name: ")
print(f"Welcome, {name}!")
Output:
Enter your name: John
Welcome, John!
Common Mistakes
Adding numbers without converting input:
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print(num1 + num2)
Output:
Enter first number: 10
Enter second number: 20
1020
Correct way:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(num1 + num2)
Output:
30
Summary
- Use the
input()function to get user input. - Input values are returned as strings.
- Use
int()andfloat()to convert input values. - Multiple values can be accepted using
split(). - User input can be used in calculations, conditions, and programs.