Getting Keyboard Input with Python input()
Learn how Python input() reads keyboard text, stores responses in variables, converts values with int() and float(), and supports calculations and if statements.
Interactive programs can pause and ask the person running them for information. Keyboard input is one of the simplest forms of command-line interaction: the program displays a prompt, the user types a response, and the program uses that response.
This lesson assumes you know how to run a basic Python script, use print(), create variables, and perform basic arithmetic. See how to run Python code and review Python variables if needed.
What input() Does
input() is a Python built-in function that reads one line entered at the keyboard and returns it as a string. A string is a sequence of text characters.
The program waits at input() until the user types a response and usually presses Enter. Execution then resumes, and the returned value can be printed, stored, converted, calculated, or tested in a condition.
name = input("Enter your name: ")
print(f"Hello, {name}!")The text inside input() is an optional prompt. A prompt is text that tells the user what information to enter.
Example interaction
Enter your name: Priya
Hello, Priya!In this interaction, Enter your name: is the prompt, Priya is the user's keyboard response, and the final line is printed by the program.
Storing a Response in a Variable
A variable is a named location used to retain a value for later use. Assigning the result of input() to a variable lets the program use the response more than once.
name = input("What is your name? ")
print("Welcome, " + name)
print("It is nice to meet you, " + name + ".")The assignment runs in this order:
- Python displays the prompt.
- Python waits for a response and Enter.
input()returns the response as a string.- The string is assigned to
name. - The program uses
namein the output statements.
The Value from input() Is Always Text
Even if the user types digits, input() initially returns a string. For example, typing 25 produces the text value "25", not the integer value 25.
value = input("Enter a value: ")
print(type(value))If the user enters 25, the output is:
<class 'str'>This distinction matters because text and numbers behave differently. Numeric arithmetic cannot directly add a string to an integer.
number = input("Enter a number: ")
# This causes a TypeError if number contains text such as "5".
# total = number + 10Converting Input to Numbers
Type conversion means changing a value from one data type to another. Use int() for whole numbers and float() for decimal numbers or other values that need fractional parts.
Read a whole number with int()
count = int(input("Enter a whole number: "))
print(count)The expression int(input(...)) first reads text and then converts that text to an integer. If the user enters 12, count stores the integer 12.
Read a decimal with float()
price = float(input("Enter a price: "))
print(price)Use float() when a decimal value such as 19.99 is acceptable. A floating-point number can also represent a whole-number entry such as 20.
Conversion succeeds only when the entered text has a valid format for the chosen type. Text such as "twelve" cannot be converted by int(), and "3.5" is not valid integer syntax for int().
Using Input in Expressions
After conversion, an entered number can be used with arithmetic operators. The original response is text; the converted variable is numeric.
base = 10
response = input("Enter another whole number: ")
addition = int(response)
total = base + addition
print(f"{base} + {addition} = {total}")Here, response contains text, while addition contains an integer. Conversion can also be written directly around input():
base = 10
addition = int(input("Enter another whole number: "))
print(f"The sum is {base + addition}.")Complete addition example
fixed_number = 8
user_number = int(input("Enter a whole number to add: "))
sum_value = fixed_number + user_number
print(f"{fixed_number} + {user_number} = {sum_value}")For example, entering 5 produces:
Enter a whole number to add: 5
8 + 5 = 13Using Input with Decisions
A conditional is code that runs according to whether a condition is true. An if statement executes an indented block only when its condition evaluates to true.
When an age is used in a comparison, convert it to an integer before comparing it with a numeric threshold.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age >= 21:
print(f"{name} meets the age requirement.")If the user enters an age of 21 or greater, the message appears. If the condition is false, the indented block is skipped.
An if...else statement can provide a result for both cases:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age >= 21:
print(f"{name} is eligible.")
else:
print(f"{name} is not eligible yet.")The comparison operator >= means “greater than or equal to.” Review comparison operators and if statements for more conditional examples.
Input Workflow
Common Input Patterns
# Read a text response
name = input("Enter your name: ")
# Read a whole number
count = int(input("Enter a whole number: "))
# Read a decimal number
price = float(input("Enter a price: "))
# Use converted input in a condition
age = int(input("Enter your age: "))
if age >= 21:
print("Eligible")Troubleshooting
A calculation fails because the response is text
Cause: The result of input() was used directly with numeric arithmetic.
Fix: Convert whole-number input with int(), or decimal input with float(), before calculating.
int() raises ValueError
Cause: The user entered text, a decimal, or another value that is not valid integer syntax.
Fix: Ask for a whole number and validate the response before conversion, or use float() when decimal input is appropriate. Exception handling with try and except can handle invalid entries gracefully; see try and except statements.
The program appears to stop at the prompt
Cause: input() is waiting for a response.
Fix: Type the requested value and press Enter. The program continues after the line is submitted.
An age comparison gives an error or an incorrect result
Cause: The age was kept as a string instead of being converted to an integer.
Fix: Use age = int(input("Enter your age: ")) before comparing age with a numeric threshold.
Key Points
input()reads one line of keyboard input and returns a string.- The optional prompt tells the user what to enter.
- The program waits until the user submits the response, usually with Enter.
- Assign the result to a variable to retain and reuse it.
- Digits entered through
input()are still text until converted. - Use
int()for whole numbers andfloat()for decimal values. - Convert numeric input before arithmetic or comparisons.
- Use stored input in output statements, expressions, and
iforif...elsedecisions.