User Input

Written by: Anish Ahuja (9/11/2020)

Introduction

Up until this point, we've inputted values straight into the code. Here, we will learn how to receive input for our function through the console.

Basics of Receiving Input

The input function receives input as a string. To write the function, equate a variable to input(""). Here is an example:

name = input("What is the name of your character?")
print (name)

If you run this function, the console will output "What is the name of the character" and wait for you to provide an input. After you provide the input, the function will return your input through the variable name.

Specifying Input Data Type

In some situations, you will need your input as a specific data type. For example, if you wanted to receive an integer and add 7 to every number that you receive, you can not use a string. To specify the input type, you use an int() function around the input. Note: This is the same as using the int() function on the variable after receiving input. This just makes the process easier.

beans = int(input("How many beans do you want in your burrito?"))
print (beans + 7)
print ("Here you go! We added 7 more beans!")

In situations where you wish to specify an integer, it is recommended that you give a question where the user knows that only integers can be given. Otherwise, a type error occurs and breaks your code.

Taking Multiple Inputs

If you wish to receive multiple values from a user in a single input, you need to use the split() method. The syntax is written as follows: input().split()

cookies, cakes = input("How many cookies and cakes do you have").split()
print ("We have {} cookies!".format(cookies))
print ("We have {} cakes!".format(cakes))

In this example, cookies is assigned to the first number given, and cakes is assigned to the second number given. The split() function does not require any value between the parentheses as the lack of a separator is interpreted as a space. Therefore, simply putting a space between your two numbers will differentiate them. If you did want a different separator, you would put the separator in quotes in the parentheses of the split() function.

Note: The input is not turned into an integer as it needs to be written alongside a string, which means it could not be an integer.

Conclusion

In this lesson, we learned how to take user input in Python. User input is critical in writing programs that are interacted with through the console, such as mad libs or basic calculators.

Last updated