Get User Input in Python with input()

Learn how to use Python input() to read keyboard input, convert text to numbers, perform calculations, make decisions, and handle invalid entries.

Interactive programs request information from a person while they run. In a command-line Python program, the keyboard is a basic way for a user to provide that information.

Python's built-in input() function displays a prompt, waits for a response, and returns what the user typed. You can store that response in a variable and use it later.

How input() works

input() is a function for receiving text from the keyboard. You can pass an optional prompt, which is the message that tells the user what to enter.

name = input('What is your name? ')

When Python reaches this line, execution pauses. The program displays the prompt and waits until the user types a response and presses the Enter key. The Enter key submits the response and allows the program to continue.

The response is assigned to the variable name. A variable is a named location used to store a value.

A personalized greeting

name = input('What is your name? ')
print(f'Hello, {name}!')

A possible interaction looks like this:

What is your name? Maya
Hello, Maya!

The sequence is:

  1. The program displays the prompt.
  2. The user types Maya and presses Enter.
  3. input() returns the entered text.
  4. The text is stored in name.
  5. print() displays a greeting containing the stored value.

input() always returns a string

A string, written as str in Python, is a sequence of text characters. input() always returns a string, even when the user types digits.

value = input('Enter a number: ')
print(type(value))

If the user enters 3, value contains the text '3', not the numeric value 3. These values look similar when displayed, but they have different types:

'3'   # string text
3     # integer number

Because input is text, direct arithmetic with it is not appropriate. For example, adding a number to the result of input() causes a type error. Two strings may instead be combined as text, which is not the same as numerical addition.

first = input('First value: ')
# total = first + 5       # Not valid: first is a string
# print(first + '5')       # Produces text such as '35', not 8

Converting input to integers

Type conversion means changing a value from one data type to another. Use int() when the expected response is a whole number, such as 3, 0, or -2.

number = int(input('Type a whole number: '))

The common pattern is int(input(...)): input() reads text, then int() converts suitable integer-form text into an integer.

Adding an entered number to a fixed value

This program starts with 5, reads a whole number, adds the two integers, and stores the result.

fixed_value = 5
entered_value = int(input('Enter a whole number: '))
total = fixed_value + entered_value

print(f'{fixed_value} + {entered_value} = {total}')

If the user enters 3, the output is:

Enter a whole number: 3
5 + 3 = 8

int() accepts integer-form text such as '3'. It does not accept decimal-form text such as '3.5'. Decimal input requires float() instead.

Converting input to floating-point numbers

A floating-point number represents a number that can have a decimal part. Use float() when decimal values are allowed or required, such as measurements, prices, or distances.

price = float(input('Enter a price: '))
total = price * 2
print(f'Two items cost ${total:.2f}.')

If the user enters 4.75, the calculation uses the numeric value 4.75, not the text '4.75'. Use int() for whole-number input and float() for decimal input.

Choosing a conversion for user input

Expected inputFunctionReturned typeExample entered valueAppropriate use
Textinput()strHelloNames, words, and other text
Whole numberint(input())int3Counts, ages, and other integer quantities
Decimal numberfloat(input())float3.5Prices, measurements, and decimal calculations

Using input in conditional logic

An if statement runs code only when its condition is true. Numeric input must be converted before it is compared with a numeric threshold.

name = input('What is your name? ')
age = int(input('How old are you? '))

if age >= 21:
    print(f'{name} meets the age requirement.')

For a user named Jordan who enters 22, the program prints the eligibility message. A user who enters an age below 21 does not trigger the indented block.

The conversion is important: age must be an integer before Python evaluates age >= 21. A string from plain input() should not be compared with an integer threshold.

You can add an else branch when the program should report both outcomes:

name = input('What is your name? ')
age = int(input('How old are you? '))

if age >= 21:
    print(f'{name} meets the age requirement.')
else:
    print(f'{name} does not meet the age requirement.')

Handling invalid numeric input

int() and float() raise ValueError when the entered text cannot be converted to the requested numeric type. For example, int('three') and float('many') are invalid conversions.

Use try and except to prevent invalid input from stopping the program unexpectedly.

try:
    age = int(input('How old are you? '))
    print(f'Your age is {age}.')
except ValueError:
    print('Please enter a valid whole number.')

Python runs the code in the try block. If conversion raises ValueError, Python runs the matching except block instead.

Asking again until the input is valid

A loop can repeat the prompt after invalid input. The loop stops after a successful conversion.

while True:
    try:
        quantity = int(input('Enter a whole-number quantity: '))
        break
    except ValueError:
        print('Please enter a valid whole number.')

print(f'Quantity recorded: {quantity}')

This pattern is useful when the program cannot continue until it has a valid number. A decimal version can replace int() with float().

Common input outcomes

User entryExpressionResult or behavior
A name such as Mayainput('Name: ')Returns the string 'Maya'
A valid whole number such as 8int(input('Number: '))Returns the integer 8
A decimal such as 2.5float(input('Value: '))Returns the floating-point value 2.5
Nonnumeric text such as eightint(input('Number: '))Raises ValueError unless it is caught

Troubleshooting input programs

  • Addition fails or becomes text concatenation: The response is still a string. Convert it with int() or float() before arithmetic.
  • ValueError appears: The entered text is not in the format accepted by the conversion function. Enter a valid number or catch the exception with try and except.
  • A numeric comparison behaves unexpectedly: Convert the input before using operators such as >=, <, or ==.
  • The program seems to stop after a question: input() is waiting. Type the requested response and press Enter.
  • A decimal cannot be entered with int(): int() expects integer-form text. Use float() if decimal input is allowed.

Key points

  • Use input(prompt) to display a prompt and read keyboard input.
  • The program pauses until the user enters a response and presses Enter.
  • Store the returned response in a variable when it will be used later.
  • input() always returns a str.
  • Use int(input(...)) for whole numbers and float(input(...)) for decimal numbers.
  • Convert numeric input before calculations or comparisons.
  • Catch ValueError when users may enter invalid numeric text.