User Input

So far, all the programs we've written generate output, like text in the console window or blocks in the game. Sometimes the programs also need to collect user input. For example, a map program can ask you which city you are interested in. There are several different ways to collect user input. Python's built-in input() function is used to get a piece of text from user.

The input() function takes a string as an argument and displays it to the user as a prompt message. Then it waits for the user to type something into the console window and press the return/enter key. The input() function will then returns your text to the computer as a string value.

Example:

name = input('Please enter your name here: ')

print('Hello, ' + name + '!')
print(type(name))

Now try it out and see what you get. Remember, the type() function shows you what data type name is.

Input a number

A lot of times, we need the user to input a number, but the input() function always returns a string. In order to use this value in a math calculation, we have to first convert it into a number type:

num = input("Please enter a number: ")
print(5 + num)

If you run the code and input number 3, you'll get an error message in the console window like this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

To fix this error, we'll need to use type conversion. The int() function turns the input into an integer value. Of course, this can only work if the input has a value that can be turned into an integer.

print(int(num) + 5)

If you run the code after converting num into an integer, you'll get the correct result instead of an error.

Here is another way is to convert the returned string value that input() returns into number type before assigning to variable num :

num = int(input("enter a number: "))
print(type(num))

The console window will show <class 'int'> this time.

results matching ""

    No results matching ""