How Do We Read A List From The Keyboard?
We can read the values of a list and store them in a data collection of our program (a variable of type
list).
EXAMPLE
Analyze the following program:
DETAILS
Initially, the list is empty. At each step, an element is added using the
append() method, as previously presented.
At the end, the entire list is displayed.
We could have written the add statement more elegantly like this:
lista.append(input('element ' + str(x)+ ' = '))
and reading the data would have been cooler:
Running the program offline, in Python IDLE
If we want the list elements to contain
only numbers, we use
explicit conversion, for example to real numbers (class
float):
lista.append( float(input('element ' + str(x)+ ' = ')) )
You should warn the user with an appropriate message. If they enter a value that is not numeric, the program will immediately return an
error -
a text cannot be converted to a real number, right?
Moreover, you can also add elements using the
insert(index,value) method, as it suits you...
A List With A Variable Number Of Elements?
Well ... the
for loop is out of the question then! We use
while,
with
a stop condition - for example, when the entered element is empty (just press the
Enter key):
lst = []
# first read a value to be read
value = input()
# repeat while nothing is read
while value != "":
lst.append(value)
value = input()
# finally, display the list
print(lst)
This section is now over.