Almost every useful program needs to ask the user for something: a name, a number, a file path or a setting. In Python, the built-in input() function handles this. This article shows how to read input in Python, what the original raw_input() example does, how to convert the text you receive, and how to read data from a serial port when the input comes from a device instead of a keyboard.
The original example (Python 2)
The program below asks for a name and prints it back. It uses raw_input() and the print statement, which only work in Python 2:
a = raw_input("enter your name\n")
print 'your name is', a
The text inside the brackets is the prompt shown to the user. The \n at the end moves the cursor to a new line, so the user types the answer on the next line. Whatever the user types is stored in the variable a as a string.
Output
The video below shows the program running and the result printed in the console.
The same program in Python 3
Python 2 is no longer maintained, and most tutorials, libraries and tools now expect Python 3. Two things change:
raw_input()was renamed toinput().printis now a function, so it needs brackets.
name = input("Enter your name: ")
print("Your name is", name)
Run it, type a name, press Enter, and the program prints it back. If you still see a NameError for raw_input, you are running Python 3 with Python 2 code. If you see a syntax error on print, it is the other way around.
How input() works
When Python reaches an input() call, it pauses, shows the prompt (if you gave one), and waits until the user presses Enter. It then returns everything typed as a string, without the final newline character.
That last point matters. Even if the user types 42, Python gives you the text "42", not the number 42.
Converting input to numbers
To do maths with what the user typed, convert the string first with int() or float():
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
Use int() for whole numbers and float() for numbers with a decimal point. Without the conversion, age + 1 would raise a TypeError because you cannot add a number to a string.
Handling invalid input
If the user types letters where you expect a number, int() raises a ValueError and the program stops. A try/except block lets you ask again instead:
while True:
text = input("Enter a whole number: ")
try:
number = int(text)
break
except ValueError:
print("That is not a whole number, try again.")
print("You entered", number)
The loop repeats until the conversion works, then break exits it.
Cleaning up text
Users often add extra spaces or use different capital letters. Two string methods help:
strip()removes spaces at the start and end.lower()turns the text into lowercase, which makes comparisons like “yes” and “Yes” easier.
answer = input("Continue? (yes/no): ").strip().lower()
if answer == "yes":
print("Continuing...")
Reading several values at once
To read more than one value on a single line, split the string at the spaces:
a, b = input("Enter two numbers: ").split()
print(int(a) + int(b))
This fails if the user does not type exactly two values, so add error handling for anything beyond a quick test.
Reading input from a serial port
Input does not always come from a keyboard. Microcontroller boards, sensors and radio modules often talk to a computer over a serial port, and Python can read from them with the pyserial library. Install it with pip install pyserial, then read a line like this:
import serial
port = serial.Serial("COM3", 9600, timeout=1)
line = port.readline().decode().strip()
print("Received:", line)
port.close()
A few things to check before it works:
- Port name: on Windows it looks like
COM3; on Linux it is often/dev/ttyUSB0or/dev/ttyACM0. Your device manager or system tools show the right one. - Baud rate: it must match the rate set on the device. 9600 is common, but use whatever your device is configured for.
- One program at a time: only one program can use a port at once, so close any serial monitor before running your script.
- Bytes, not text: serial data arrives as bytes, which is why the example calls
decode().
For a longer walk-through, see our guide on how to send and receive serial data from Python with XCTU or an Arduino. If you want a working project, the article on displaying temperature in Python using Arduino reads a sensor value over serial and shows it on screen.
Common mistakes
- Forgetting to convert: input is always a string until you convert it.
- Mixing Python versions:
raw_input()andprint "text"belong to Python 2;input()andprint()belong to Python 3. - Using Python 2’s input(): in Python 2,
input()tries to evaluate what the user types as code, which is unsafe. Useraw_input()there. - No prompt: a blank cursor confuses users. Always say what you want them to type.
Where to go next
Once you are comfortable with input, try a small project: a calculator, a quiz, or a unit converter. If you are weighing Python against another language for embedded work, our comparison of C language vs Python explains the trade-offs. For hardware ideas that use the same input skills, browse these Raspberry Pi Python projects, or see how to plot sensor readings in Arduino data analysis with Python.
FAQ
What is the difference between input() and raw_input()?
In Python 3, raw_input() no longer exists and input() does the same job: it returns what the user typed as a string. In Python 2, raw_input() returned a string, while input() evaluated the text as Python code, so it should be avoided.
Why does input() always return a string?
Python cannot know whether the user means a number, a word or something else, so it returns exactly what was typed. You decide how to interpret it with int(), float() or other conversions.
How do I read a number from the user in Python?
Wrap the call in a conversion function, for example int(input("Enter a number: ")). Add a try/except ValueError block so the program does not crash on bad input.
How do I read input from a serial port in Python?
Install the pyserial library, open the port with serial.Serial() using the correct port name and baud rate, and call readline() or read(). Decode the returned bytes to get text.