In Python, most programs need to collect information from users, such as their name, age or a number. This is done using the input() function, which:
- Pauses the program and waits for the user to type something.
- Returns the entered value as a string (str).
- Optionally displays a prompt message to guide the user.
Unlike some languages that rely on dialog boxes, Python keeps it simple by taking input directly from the console.
This program asks the user for a value, stores it as a string and then prints it back.
Python
val = input("Enter your value: ")
print(val)
Output
Enter your value: 123
123
When you use input() in a program:
- The program pauses until the user provides some input.
- You can optionally provide a prompt message (e.g., "Enter your age:").
- Whether you type letters, numbers, or symbols, Python always stores it as a string by default.
- If you need another data type (like integer or float), you must convert it manually using typecasting.
Example: This program checks the data type of user input to confirm that both number and name are stored as strings.
Python
num = input("Enter number:")
print(num)
name1 = input("Enter name: ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))
Output
Enter number: 45
45
Enter name: John
John
Type of number: <class 'str'>
Type of name: <class 'str'>
Often, you need numerical input (like age, marks, or salary). Since input() returns a string, you must convert it using int() or float().
This program converts user input into an integer.
Python
num = int(input("Enter a number: "))
print(num, "is of type", type(num))
Output
Enter a number: 25
25 is of type <class 'int'>
This program converts user input into a float (decimal number).
Python
floatNum = float(input("Enter a decimal number: "))
print(floatNum, "is of type", type(floatNum))
Output
Enter a decimal number: 19.75
19.75 is of type <class 'float'>
Sometimes, a program needs to accept more than one value at once. In Python, this can be done by entering values separated by spaces and then splitting them into separate variables.
Example: This program takes two numbers from the user in one input line, splits them and prints them separately.
Python
x, y = input("Enter two numbers separated by space: ").split()
print("First number:", x)
print("Second number:", y)
Output
Enter two numbers separated by space: 10 20
First number: 10
Second number: 20
Related Posts:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice