Input From the User

This lesson will focus on Python's built-in input function.

Introduction to input

Python has a wide array of excellent built-in functions, such as the len(my_list) command, which returns the length of a list.

Similarly, to ask the user for input, you can use the built-in function input(_prompt_).

Note: If you omit the prompt, the user will be left staring at a blank screen and wondering why the program isn’t doing anything.

An example of this can be:

name = input("What is your name? ")
print("Hello,", name)

The result of a call to input is always a string. If you are expecting an integer or a float, you can use the int or float functions to convert the string to the desired type. For example:

age = int(input("How old are you, " + name + "? "))

If the user types in something that can’t be made into an integer, this will result in an error. We deal with error handling later on in the course.

Input function example

To understand the built-in input function, let’s look at an example.

Below, there is a blue colored Run button on your screen. Click on it to run the following code (the example given above):

name = input("What is your name? ")
print("Hello,", name)

Over here, this will prompt the “What is your name?” message. Enter your name there. After this, you will see an output displaying your name along with a “Hello” message.

Get hands-on with 1200+ tech skills courses.