Reading String Input

Does input() Return a String in Python?

In Python 3, input() always returns a str, even when the user types digits. Learn how to convert the result to a number and why that step matters.

On this page
  1. The short answer
  2. Checking the type
  3. Converting the result
  4. What happens at the end of input
  5. How this compares with C++
  6. A note on Python 2
  7. Quick recap

The short answer

Yes. In Python 3, input() always returns a str, even when the user types only digits. If you need a number, convert the text yourself with int() or float().

Checking the type

text = input("Enter a number: ")
print(type(text))  # <class 'str'> for any input

number = int(text)
print(number + 1)

If the user types 41, text holds the characters "41", not the number 41. Adding a number to it directly, as in text + 1, raises a TypeError, because Python does not join a string and an integer.

Converting the result

int() turns a string of whole-number digits into an integer, and float() turns it into a decimal number:

age = int(input("Enter your age: "))
price = float(input("Enter a price: "))

If the text is not a valid number, such as abc, int() raises a ValueError. The same happens for 3.5 with int(), because it is not a whole number. To handle bad input, wrap the conversion in a try block:

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a whole number.")

What happens at the end of input

When there is no more input to read, for example when a script runs with its input closed, input() raises an EOFError.

How this compares with C++

In C++, the type of the variable you read into decides how the text is parsed:

  • std::cin >> age, where age is an int, reads a whole number directly.
  • std::getline(std::cin, text), where text is a std::string, stores the whole line as text.

For the full set of C++ rules for reading text, see the guide to c input string.

A note on Python 2

This article covers Python 3. Python 2 worked differently: its input() evaluated the text that was typed, and raw_input() returned a string. Python 2 is no longer supported, so new code should use Python 3.

Quick recap

In Python 3, input() returns a str. Convert it with int() or float() when you need a number, and handle ValueError for text that is not a valid number. In C++, the variable’s type plays a similar role when you read with >>.

The complete guide to reading string input

How to Read String Input in C++
Read the guide

Keep exploring

Guides from other topics

All topics →