Intro to Programming: How to Handle User Input in Python

Most programs work on data that is passed to them via files, APIs, databases or user input. Python has a built-in function called input that facilitates reading data directly from users.
By Ciprian Stratulat • Updated on Mar 2, 2023
blog image

Hi and welcome back to a new article in my Intro to Programming series! In this article, you'll learn about the first of several ways to get data into our program - more specifically, you'll learn about user input.


So far, you've only written code that relied on some variables already being set to some values. In reality, programs rarely operate on such hard-coded data. Instead, most programs work on data that is passed to them via files, APIs, databases, or user input. The advantage of not using preset values for your variables is that your program is more general. That means that it can be used in more than one scenario, and potentially by more people, even those who may not be programmers themselves.

For example, if you wanted to write a program that simply returns the number of letters in a person's name, it would be annoying to have to rewrite the program for each new friend who wanted to try it. Instead, ideally, you'd want to write your program in such a way that when it starts, it prompts your friend to enter their name, and then uses that as the input data.

That is exactly what you'll learn in this article. Python has a built-in function called input that facilitates reading data from users. I'll first explore it in a Jupyter notebook. Then, I'll quickly jump to a code editor to show you how you'd run a program that requires user input outside of a Jupyter notebook.



Article continues below

How to Add Python's User Input in Jupyter Notebook

Let's start with the example I just talked about.

Let's say that I want to read a person's name and print the length of the name. I can do that simply by writing name = input('What is your name?'). If I run this, you'll see this input box where I can enter a name, let's say, James.

What happened here is that the input function read what I entered and stored it in the variable called name. You can see for yourself by simply printing the value stored in name. If I run print(name), I get James.

Now that I have the person's name stored in a variable, I can easily print the length of it: print(len(name)), and I get 5.

# Let's create a variable "name" that takes input
name = input('What is your name?')

# Now, let's run the code. When we see
What is your name?
#Let's enter

#Let's print the name
# which returns
# James

# And when we print the length of the name
# We get
# 5

This is something you may not have seen before, but don't let it confuse you.

What happened here is that the inside function, len(name), is executed first. The len() function returns the integer 5, which is then passed to the print function, which prints it on the screen. This kind of function nesting is pretty common in programming. Just remember that the order of execution always starts with the inner-most one.

So, in this case, as you've seen, I first start by executing len(name), and then printing the result of that execution. Of course, if this is confusing, you can also instead write name_length = len(name) and then print(name_length). It's the exact same thing.

# We could also create a variable for name length
name_length = len(name)

# When we run it, the result is the same.
# Still returns
# 5

You can see that the input function is very simple: it takes a string, which represents the prompt that I want to show the user when I ask them for their input.

One thing to be aware of is that the input function always stores the user's input as a string. Let me show you what I mean by that: let's ask for the user's age. I can do this by writing age = input('How old are you?'). In this case, I prompt the user with the question, "how old are you?" and then I am storing their answer in a variable called age. Let's say I enter 35. You might be tempted to think that age now stores an integer number, but that's not the case.

I can check the type of data stored in the variable called age by using type(age) and you can see that it's actually a string. That's right; input will always store the user's input as a string, so that's something you need to be aware of.

# Let's check the type of the data for age

# The output is
# str, for string


How to Add User Input in Python Script Files

Now, instead of using Jupyter notebook I'll use a code editor to create a Python script file, which I'll then run using the command line.

So far I have mostly been using Jupyter notebook for its ease of use, but as you start to write some more complex programs, you'll benefit from saving them as individual files that you can perhaps even email to your friends so they can run them too, provided that they have Python installed.


As an example of a program, I'll use the following: you want to write a program that prompts your friend to enter their name. If the name is longer than 7 letters, it'll print the message 'Your name is long!' Otherwise, it'll print the message 'Your name is not very long.'

I'm going to open a new Atom window - you can also use any other code editor that you prefer -  I'm going to create a new file by going to the File menu and clicking New File. It's an empty file, but I'll go ahead and save it so I know where I can find it later.

To save the New File, you can either use the keyboard shortcut command+s on Mac, or control+s if you're on a PC, or go to the File menu and then click Save.

I've created an i2p folder in my home directory, so I'll just put it there. I'm going to call it Remember, the .py extension is required for all Python programs.

Now you're ready to write your program.

The first thing you'll need to do is prompt your friend for their name, so let's do that: name = input('What is your name? '). Notice that I've left an extra space after the question mark. That's just so that when the user enters their response, there will be a space between the question and the answer.

Next, you will want to check the length of the name, so you can write if len(name) > 7:". If that's True, you'll print('Your name is long!'), or you can print('Your name is not very long.')

# Let's create our program:
name = input('What is your name? ')

if len(name) > 7:
    print('Your name is long!')
    print('Your name is not very long.')

That's your whole program.

Now, you save it by using the keyboard shortcut command+s for Macs, or control+s for PCs, or by going to the File > Save menu.

Now, you'll remember from my articles about Python environments that you can run your Python program from the command line. If it's been a while since you last used the command line, it may be a good idea to refresh your memory by reviewing the article where I covered how to use the command line:



I'm going to open my Terminal app since I'm using a Mac. If you're using a PC, you'll need to launch the Command Line application.

If you remember, the Terminal app always takes me to my home directory, but my code is saved in the i2p directory, so I'll first need to navigate there. I can do that by typing cd i2p, and then hitting Enter. If I list the files I have here, I can see the

To run it, all I'll have to do is type python followed by a space, and the name of the file I want to run, python

If you're following along and don't have any typos, you should now see the question What is your name? My name is Claudia, so let's enter that.

When I hit Enter, the program reads my input, determines that my name is not that long and prints the message Your name is not very long.

# Let's run our code

# We should see the question
# What is your name?
# Let's enter Claudia
# Our output is:
# Your name is not very long.

Perfect, let's run it again. I can again type python Or, I can just hit the up arrow key on my keyboard, which will automatically show me the last command I executed, so I don't have to do all that typing again.

Either way, if I run my program again, I'll again get the question: What is your name? Let's say my name is Elizabeth. Now I get the message Your name is long!

# Let's run our code again
# What is your name?
# Let's enter Elizabeth
# Our output is:
# Your name is long!


Why You Should Plan for Things to Go Wrong With User Input

When it comes to user input, there is one fundamental rule that you should learn early on: do not ever, under any circumstances, assume that the user of your program will give you correct data.

Humans are just human - they will make mistakes. Some humans are also natural trolls and will try to mess with your program for fun, while others for profit, and yet others just because they want to crash it. Therefore, you must always verify that the user passed the correct input to your program.

Having said that, let's go back to your user input here. Given that the input function always stores the user input as a string, how can you convert it to other data types? More specifically, you asked for the age of the user, but what you got from the input function is a string. This is a bit annoying, because you know that age is just a number, and you would like to do some math with it. How do you do that?

To convert a string that represents an integer number to the actual integer number you can use the built-in int function. int takes as input a string and will return the actual number that the string represents.

For example, in your case, you can write years_old = int(age). If you now check the data type of the variable years_old using type(years_old), you'll see that it's actually a number.

Now, because it's a number, you can do math with it.

# Let's change our input to an integer
years_old = int(age)

# Now let's check our data type
# And our output is
# int

But what happens if you assume that the user is always nice and you don't check their input?

Someone could take advantage of that to crash your program. Let's go back to our code here where you ask for the age and run it again by clicking inside the Jupyter notebook cell and hitting Shift and Enter. You will again prompt for user input, so let's enter i'm a troll.

Now execute the next line of code, and you'll get that the data type of the variable age is a string, which is not surprising of course, as the input function always stores user input as a string. But what happens on the next line? You are basically trying to convert the string i'm a troll to an integer number and, of course, you will get an error, because that's not a valid number.


# Let's update our input to a string of letters
age = input('How old are you?')
How old are you?i'm a troll

# Now let's try to update the string to an integer:
years_old = int(age) ␣

# We get an error

        ValueError                                                                      Traceback (most recent call last)

<ipython-input-12-7b149e9a8bd5> in <module>()

----> 1 years_old = int(age)

    ValueError: invalid literal for int() with base 10: "i'm a troll"

So, remember, don't ever assume that the user is nice and always be prepared for user misbehavior. I'll later share one strategy you can use to handle such scenarios in an upcoming article. For now, just remember this lesson.

Alright, there you have it: you now know how to get data from someone who runs your program (maybe your friend or a customer, etc.), and how to use this data to do something interesting with it.

That's it for user input. Before I end, I wanted to also mention the fact that, if you do a Google search for user input in Python, you will occasionally see people mention a function called raw_input. That was the old name of the function, in Python 2. In Python 3, it got renamed to simply input.

Thanks for reading, and don't forget to keep practicing! Now that you are familiar with data types, loops, if statements, for loops, functions, and getting user input, you can write much more interesting programs. 


Ciprian Stratulat

CTO | Software Engineer

Ciprian Stratulat

Ciprian is a software engineer and the CTO of Edlitera. As an instructor, Ciprian is a big believer in first building an intuition about a new topic, and then mastering it through guided deliberate practice.

Before Edlitera, Ciprian worked as a Software Engineer in finance, biotech, genomics and e-book publishing. Ciprian holds a degree in Computer Science from Harvard University.