Introduction to Python (12) while loop (2)

Author: xiou

1. Use a while loop to process lists and dictionaries

So far, we've only processed one piece of user information at a time: get the user's input, print it out or respond to it; when the loop runs again, learn another input value and respond to it. However, to log a large number of users and information, you need to use lists and dictionaries in a while loop.

A for loop is an efficient way to traverse a list, but the list should not be modified in the for loop, otherwise it will make it difficult for Python to keep track of the elements in it. To modify a list while iterating over it, use a while loop. By using while loops with lists and dictionaries, large amounts of input can be collected, stored, and organized for later review and display.

2. Moving elements between lists

Suppose there is a list of newly registered but not yet authenticated website users. Once these users are authenticated, how do I move them to another list of authenticated users? One way is to use a while loop to extract the user from the list of unauthenticated users while the user is being authenticated, and then add it to another list of authenticated users. The code might look something like this:

  # 首先,创建一个待验证用户列表
  # 和一个用于存储已验证用户的空列表。
  unconfirmed_users = ['alice', 'brian', 'candace']
  confirmed_users = []

  # 验证每个用户,直到没有未验证用户为止。
  # 将每个经过验证的用户都移到已验证用户列表中。
  while unconfirmed_users:
      current_user = unconfirmed_users.pop()

      print(f"Verifying user: {
      
      current_user.title()}")
      confirmed_users.append(current_user)

  # 显示所有已验证的用户。
  print("\nThe following users have been confirmed:")
  for confirmed_user in confirmed_users:
      print(confirmed_user.title())

First create a list of unauthenticated users, which contains users Alice, Brian, and Candace, and an empty list to store authenticated users. The while loop will keep running until the list unconfirmed_users becomes empty. In this loop, the method pop() removes unconfirmed users from the end of the list unconfirmed_users one at a time. Since Candace is at the end of the list unconfirmed_users, its name will be deleted first, assigned to the variable current_user and added to the list confirmed_users. Next came Brian, then Alice.

To simulate the user authentication process, we print an authentication message and add the user to the list of authenticated users. The list of unverified users gets shorter and shorter, while the list of verified users gets longer. End the loop after the list of unauthenticated users is empty, and then print the list of authenticated users:

insert image description here

3. Delete all list elements with a specific value

We use the function remove() to remove a specific value from the list. This works because the value to be removed appears only once in the list. What if you want to delete all elements with a specific value in the list?

Suppose you have a list of pets with multiple elements with value 'cat'. To remove all these elements, run a while loop until the value 'cat' is no longer in the list, like this:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

First create a list with multiple elements with value 'cat'. After printing this list, Python enters the while loop because it finds that 'cat' appears in the list at least once. After entering that loop, Python deletes the first 'cat' and returns to the while line of code, then finds that 'cat' is also contained in the list, so enters the loop again. It keeps removing 'cat' until the value is no longer contained in the list, then exits the loop and prints the list again:

insert image description here

4. Populate the dictionary with user input

You can use a while loop to prompt the user for any amount of information. Let's create a survey program in which the loop prompts for the respondent's name and response each time it executes. We store the collected data in a dictionary to associate responses with respondents:

  responses = {
    
    }

  # 设置一个标志,指出调查是否继续。
  polling_active = True

  while polling_active:
      # 提示输入被调查者的名字和回答。
      name = input("\nWhat is your name? ")
      response = input("Which mountain would you like to climb someday? ")

      # 将回答存储在字典中。
      responses[name] = response

      # 看看是否还有人要参与调查。
      repeat = input("Would you like to let another person respond? (yes/ no) ")
      if repeat == 'no':
          polling_active = False

  # 调查结束,显示结果。
  print("\n--- Poll Results ---")
  for name, response in responses.items():
      print(f"{
      
      name} would like to climb {
      
      response}.")

The program first defines an empty dictionary (responses) and sets a flag (polling_active) indicating whether polling should continue. Python runs the code in the while loop as long as polling_active is True.

In this loop, the user is prompted to enter their name and which mountain they like to climb. Store this information in a dictionary responses, then ask the user whether to continue the survey. If the user enters yes, the program will enter the while loop again; if the user enters no, the flag polling_active will be set to False, and the while loop will end. The last code block displays the survey results.

If you run this program, and enter some names and answers, the output will look like this:

insert image description here

Guess you like

Origin blog.csdn.net/qq_41600018/article/details/130774374