We have used a 'for loop' in our examples for looping through Lists and Dictionaries. But if we modify a list inside a for loop, Python will have trouble keeping track of the items in the list. Thus to modify a list as you work through it, use a while loop. Using while loops with lists and dictionaries allows you to collect, store, and organize lots of input to examine and report on later. Let us see some of the uses of a 'while loop' with Lists and Dictionaries.
1. Moving Items from One List to Another
In our example we have a car service station which receives car for servicing. We have a list in_cars which contains all the cars which came for servicing. After a car's servicing is done it should be moved to a separate list out_cars which initially is empty. Here is the program:
in_cars =['audi','bmw','chervolet']
out_cars = []
while in_cars:
current_car = in_cars.pop()
print("The car " + current_car +" is under servicing....")
out_cars.append(current_car)
print("Servicing for " + current_car +" done!\n")
print ("\nThese cars are ready for delivery to customers\n")
for out_car in out_cars:
print(out_car)
print("\nServicing of all the cars scheduled for today completed")
Our program has a list in_cars which contains all the cars scheduled for servicing on a particular day and other list out_cars to store those cars whose servicing is done. Using a while loop we check if the in_cars list has items, thus it runs until the in_cars list is not empty.
Within the loop we pick one car from the in_cars list using a pop() and store it in a variable current_car which signifies this particular car is under servicing. Using a print () we have printed this message. After the servicing is done this current_car item is appended to the out_cars list. Again a confirmation message is printed.
When the in_cars list is empty the while loop stops and the program enters the for loop which prints the name of all the cars in out_cars list containing cars for which servicing has been done.
The output for the program is shown in the screen shot below-
2. Removing all instances of specific items from a List
We have a list used_languages which contains all the programming languages used by the programmers. Now the company stopped using Python and wants to remove all occurrences of Python from the list.
You might have thought about of using the remove() method we have used before with lists. Lets see if your thinking was right or not. The program below shows removing Python language from the list used_languages which has multiple occurrences of Python .
used_languages = ['Python','Java','Python','Perl','Python','C','Python','C++','Python','C#','Python']
print("List before modification:\n")
print(used_languages)
used_languages.remove('Python')
print("List after modification:\n")
print(used_languages)
If we run the program we get the output shown below-
As you may have noticed only the first occurrence of Python has been removed and the list still contains Python as it's item. Since our aim was to remove all occurrences of Python we will use a while loop here. See the program below -
used_languages = ['Python','Java','Python','Perl','Python','C','Python','C++','Python','C#','Python']
print("List before modification:\n")
print(used_languages)
while 'Python' in used_languages:
used_languages.remove('Python')
print("List after modification:\n")
print(used_languages)
If we run the program we get the output shown below-
Python enters the while loop because it finds the value 'Python' in the list and removes the first instance of 'Python', returns to the while line, and then reenters the loop when it finds that 'Python' is still in the list. It removes each instance of 'Python' until the value is no longer in the list, at which point Python exits the loop and prints the list again.
Now the list used_languages doesn't contain Python hence our target has been achieved.
3. While loop for filling a Dictionary with User Input
Let's collect data for some people by asking their name and their favorite programming language. See the program below:
favorites = {}
question = True
while question:
name = input("\nWhat is your name? ")
answer = input("\nYour favorite programming language ")
favorites[name] = answer
ask_again = input("\nWant more inputs? (y/n)")
if ask_again == 'n':
question = False
print("\nThe info your collected\n")
for name,answer in favorites.items():
print(name + " likes to program in " + answer + ".")
Here we started by defining an empty dictionary favorites and define a flag question to indicate that our questionnaire is active. As long as question is True, Python will run the code in the while loop. Within the loop, the user is prompted to enter their name and their favorite programming language which are collected in respective variables name and answer.
This information is then stored in favorites dictionary. Within the loop, the user is prompted if he wants to collect more inputs, if 'y' is entered, the program enters the while loop again but if 'n' is entered, our flag question is set to False and the program exits the while loop. Finally we printed the collected information. If we run the program we get the output shown below-
Now we know how to use while loops to make your programs run as long as your users want them to. The three uses of looping we saw today needs more and more practice because of their high utility in real world projects. So make more programs and play around with the for and while loops.
Keep practicing and learning Python as Python is easy to learn.
1. Moving Items from One List to Another
In our example we have a car service station which receives car for servicing. We have a list in_cars which contains all the cars which came for servicing. After a car's servicing is done it should be moved to a separate list out_cars which initially is empty. Here is the program:
in_cars =['audi','bmw','chervolet']
out_cars = []
while in_cars:
current_car = in_cars.pop()
print("The car " + current_car +" is under servicing....")
out_cars.append(current_car)
print("Servicing for " + current_car +" done!\n")
print ("\nThese cars are ready for delivery to customers\n")
for out_car in out_cars:
print(out_car)
print("\nServicing of all the cars scheduled for today completed")
Our program has a list in_cars which contains all the cars scheduled for servicing on a particular day and other list out_cars to store those cars whose servicing is done. Using a while loop we check if the in_cars list has items, thus it runs until the in_cars list is not empty.
Within the loop we pick one car from the in_cars list using a pop() and store it in a variable current_car which signifies this particular car is under servicing. Using a print () we have printed this message. After the servicing is done this current_car item is appended to the out_cars list. Again a confirmation message is printed.
When the in_cars list is empty the while loop stops and the program enters the for loop which prints the name of all the cars in out_cars list containing cars for which servicing has been done.
The output for the program is shown in the screen shot below-
2. Removing all instances of specific items from a List
We have a list used_languages which contains all the programming languages used by the programmers. Now the company stopped using Python and wants to remove all occurrences of Python from the list.
You might have thought about of using the remove() method we have used before with lists. Lets see if your thinking was right or not. The program below shows removing Python language from the list used_languages which has multiple occurrences of Python .
used_languages = ['Python','Java','Python','Perl','Python','C','Python','C++','Python','C#','Python']
print("List before modification:\n")
print(used_languages)
used_languages.remove('Python')
print("List after modification:\n")
print(used_languages)
If we run the program we get the output shown below-
As you may have noticed only the first occurrence of Python has been removed and the list still contains Python as it's item. Since our aim was to remove all occurrences of Python we will use a while loop here. See the program below -
used_languages = ['Python','Java','Python','Perl','Python','C','Python','C++','Python','C#','Python']
print("List before modification:\n")
print(used_languages)
while 'Python' in used_languages:
used_languages.remove('Python')
print("List after modification:\n")
print(used_languages)
If we run the program we get the output shown below-
Python enters the while loop because it finds the value 'Python' in the list and removes the first instance of 'Python', returns to the while line, and then reenters the loop when it finds that 'Python' is still in the list. It removes each instance of 'Python' until the value is no longer in the list, at which point Python exits the loop and prints the list again.
Now the list used_languages doesn't contain Python hence our target has been achieved.
3. While loop for filling a Dictionary with User Input
Let's collect data for some people by asking their name and their favorite programming language. See the program below:
favorites = {}
question = True
while question:
name = input("\nWhat is your name? ")
answer = input("\nYour favorite programming language ")
favorites[name] = answer
ask_again = input("\nWant more inputs? (y/n)")
if ask_again == 'n':
question = False
print("\nThe info your collected\n")
for name,answer in favorites.items():
print(name + " likes to program in " + answer + ".")
Here we started by defining an empty dictionary favorites and define a flag question to indicate that our questionnaire is active. As long as question is True, Python will run the code in the while loop. Within the loop, the user is prompted to enter their name and their favorite programming language which are collected in respective variables name and answer.
This information is then stored in favorites dictionary. Within the loop, the user is prompted if he wants to collect more inputs, if 'y' is entered, the program enters the while loop again but if 'n' is entered, our flag question is set to False and the program exits the while loop. Finally we printed the collected information. If we run the program we get the output shown below-
Now we know how to use while loops to make your programs run as long as your users want them to. The three uses of looping we saw today needs more and more practice because of their high utility in real world projects. So make more programs and play around with the for and while loops.
Keep practicing and learning Python as Python is easy to learn.
0 comments:
Post a Comment