Python- Day 22- Using a While Loop with Lists and Dictionaries
Handling Multiple User Inputs:
- While loops can collect and manage multiple inputs by storing them in lists or dictionaries.
- Unlike for loops, while loops can modify lists during execution, making them useful for dynamically managing data like user inputs.
Moving Items Between Lists:
You can transfer items from one list to another using a while loop.
In this example, we start with a list of unverified users and an empty list for confirmed users. As we verify each user, we move them from the unverified list to the confirmed list using a while
loop.
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop() # Remove the last unverified user
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user) # Add the user to the confirmed list
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
>>
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
- The
while
loop runs as long asunconfirmed_users
is not empty. - The
pop()
method removes the last user fromunconfirmed_users
and assigns it tocurrent_user
. - Each verified user is added to
confirmed_users
usingappend()
. - Once all users are confirmed, the loop ends, and the program prints the confirmed users.
Removing Specific Values from a List:
To remove all instances of a specific value (e.g., removing all ‘cat’ entries from a list), use a while loop.
Suppose we have a list with multiple instances of a specific value, like ‘cat’, and we want to remove all occurrences. The while
loop repeatedly removes 'cat' until none remain.
# List of pets with multiple 'cat' entries
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print("Original list of pets:", pets)
# Remove all instances of 'cat' from the list
while 'cat' in pets:
pets.remove('cat')
print("Updated list of pets:", pets)
>>
Original list of pets: ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
Updated list of pets: ['dog', 'dog', 'goldfish', 'rabbit']
- The
while
loop checks if 'cat' is still present in thepets
list. - If ‘cat’ is found, it removes the first occurrence of it using
remove()
. - The loop repeats until all instances of ‘cat’ are removed.
Filling a Dictionary with User Input:
A while loop can gather input from users and store it in a dictionary, associating a user’s response with their name.
In this example, we create a polling program where users are asked a question, and their answers are stored in a dictionary. Each user’s name is the key, and their response is the value.
# Empty dictionary to store responses
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# Store the response in the dictionary
responses[name] = response
# Ask if another user wants to respond
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat.lower() == 'no':
polling_active = False
# Polling is complete, display the results
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
>>
What is your name? Nidhi
Which mountain would you like to climb someday? Mount Everest
Would you like to let another person respond? (yes/no) yes
What is your name? Nid
Which mountain would you like to climb someday? Eastern Himalaya
Would you like to let another person respond? (yes/no) no
--- Poll Results ---
Nidhi would like to climb Mount Everest.
Nid would like to climb Eastern Himalaya.
- The
while
loop keeps running as long aspolling_active
isTrue
. - The program prompts the user for their name and the mountain they would like to climb.
- The response is stored in the
responses
dictionary, where the key is the user’s name, and the value is their response. - The user is then asked if they want to allow another person to respond. If they type ‘no’, the loop ends by setting
polling_active = False
. - After polling ends, the program prints all responses.
If you found this guide helpful then do click on 👏 the button.
Follow for more Learning like this 😊
If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!