User Input in Python

Interactive programs are more engaging than others. Many programs need the user to type in some data. For example, if you want to use Facebook, you have to create a user account. To do that, you need to type in your name, age, and other details.

The website needs to take that input from you.

If you want to create a Python program to collect information from the user so that you can use the information as a variable. All you have to do is just as you use the print() function and the input () function.

That means the input () function will ask the user to provide some info.

input ("what is your favorite food?")

When you run this code, the program will display that question and leave a space for users to type their own input.

Using Input As a Variable

To make it useful in any program, you have to store the input as a variable for the computer to read. You will then use that variable later in the program.

For example, let’s say we want to use the input from the above question in the code to display a message. We can say:

food = input ("what is your favorite food?")
print ("Best food: "+ food)

Try it in the IDE and run the code. There you go!

By default, Python assumes that every result from user input is a string. Even if it was a number, it saves it as though it were a string. That means if you wanted to use a number in your code, for example, when coding a Guess the Number game.

You have to convert it first since you cannot use any math operation on a string (even if the string is a number).

How do you do that?

You need to add the special keyword int or float in front of the input parameter before running. That will convert everything in the output into a number you can use.

For example, let us say I need input on how many apps you have.

exp = input ("How many apps do you have?")
apps = int (exp)

print (apps)

In this script, the number of apps that return will automatically be converted to int if it is a number value.

What if you want to ask for a different kind of number? Like a number that is not an integer, maybe a float. For example, let’s say you want your user to provide their age and the current price of something or the temperature of their room.

You can use float instead of int because the user’s input may include fractions or decimals. Many programmers use float instead of int because that function can handle both kinds of numbers and convert them for the computer to operate efficiently.

What does the input () function do? Make a post about it on your social media page now. Make it fun.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials