input()
The print()
function makes it easy to send your data as text to standard out (see also: print()). The Python function input()
goes the other direction, letting the user type something that goes in a Python variable.
Here is an example of input()
in the interpreter to see how it works:
>>> name = input('what is your name? ') what is your name? Guido >>> name 'Guido' >>>
The parameter to input()
is a prompt string that prints out, prompting the user what they are supposed to type. It looks best to add a space at the end of the prompt string.
String Conversion
The result from input()
is always a string, so it may need a conversion like int()
to convert it to a number
>>> age = input('what is your age? ') what is your age? 25 >>> age '25' >>> int(age) 25
Input In A Function
Inside a function, this looks like:
def get_age(): """ Prompt the user for their int age and return it as an int. """ age_str = input('What is your age in years? ') return int(age_str)
For a black-box function, the inputs are in the parameters, so this function is some other, informal form.
input() For Demos
Regular Python programs typically do not use input()
to get their data, instead using command line arguments. The input()
function is handy for making little demos where you want a quick way to let the user type something in with one line of code compared to the many lines needed to support command line arguments.
Copyright 2020 Nick Parlante