User input
input()
function
Python built-in input()
function is to used to get data from user.
The input()
function takes a string as argument
and displays it to the user as prompt message. Then it waits for the user to type something and press the return key. the input()
function will then return the text the user has entered as a string
value.
Example:
name = input('Please enter your name here: ')
print ('Hello, ', name)
print(type(name))
Run, a pop window shows up with message waiting for your response:
craft.buzzcoder.com says:
Please enter your name here:
You type in
Meepit
and click enter, then the console shows result:
Hello, Meepit
<class 'str'>
The first line calls the input( )
function, when it runs, the prompt message 'Please enter your name here: '
appears in the output window, followed by a blinking cursor, waiting until the user enters (something? a string?) and presses [Enter]
. So the variable name
gets what the user types in as a string.
Input a number
Next example, we take in a number from input()
, this number is returned as a string type. So to use this number in a math calculation, we have to first convert it into a number type:
num = input("Please enter a number: ")
print( num + 5 )
run the code, and you'll get:
Please enter a number: 3
Can't convert int to str implicitely # error message in the console
Use type conversion, int(num)
before putting in a math calculation:
print( int(num) + 5 )
Run, you get:
Please enter a number: 3 # pop up window
8 # console result
Another way is to convert the returned value(a string) from input()
into number type first:
num = int(input("enter a number: ")
print( type(num) )
Run, you get:
Please enter a number: 3 # pop up window
<class 'int'> # console result