Monday, June 10, 2019

Reading User Input in Python

Reading Input From The Keyboard

In order to process user input you are going to need to retrieve keyboard data from the user. One of the most easy and straightforward ways of getting user input is to use the input function.


>>> a = input("Enter a number:")
Enter a number:23
>>> print(a)
23
>>> 

In the above example we use the input command to retrieve a number and store it in the variable a. We could have first used the print command and then called input() but it is more compact and easier to read to display the user input and retrieve it at the same time.

A common mistake would be to call input(a) expecting the input command to store the value in a.

>>> input(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> 

NOTE: The variable a is automatically declared in python and we don't even have to give it an initial value before retrieving it from the user.



No comments:

Post a Comment

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...