Progress so far
So far, we have studied a lot about Lists and ran some code with them. To make these concepts more clear, we will write a small code here that uses Lists and displays the final output. This is a rather easy unit and writing the code by yourself is recommended.
Let's start! What can we do with Lists? We know that they help us store values together. For starters, lets store car names in a list and then display them at the end. This is the task:
TASK: Input
n
car names from user (where user definesn
) and output them at the end.
Once again, you should try and do this yourself.
Lets see how we could go about doing this, without using Lists:
print('Enter Car number 1:')
nameOfCar1 = input()
print('Enter Car number 2:')
nameOfCar2 = input()
print('Enter Car number 3:')
nameOfCar3 = input()
print('Enter Car number 4:')
nameOfCar4 = input()
print('Enter Car number 5:')
nameOfCar5 = input()
print('Enter Car number 6:')
nameOfCar6 = input()
print('The car names are:')
print(nameOfCar1 + ' ' + nameOfCar2 + ' ' + nameOfCar3 + ' ' + nameOfCar4 + ' ' +
nameOfCar5 + ' ' + +Name6)
DO IT YOURSELF: Add a parameter
n
in the code above to limit the number of car inputs. (Hint: You could use Loops!)
The code above will work, type it in your Repl window and run the code, you will see the output. Now, the code looks fine, but there are some things that can be changed. For instance, using the same input statement and storing it in different variables is not very efficient. Also, these are too many lines of code for such a simple task. We can make it easier. Lets see how:
namesOfCars = []
while True:
print('Enter the name of car ' + str(len(namesOfCars) + 1))
name = input()
if name == '':
break
namesOfCars = namesOfCars + [name]
print('The cat names are:')
for name in namesOfCars:
print(' ' + name)
Type this program into your Repl window to find out the output!
As we can see, this program uses Loops and Lists together to give a much more efficient and better solution for us to work on.