Python essay 7 (while loop)

Source: Internet
Author: User

Use while loop
You can use a while loop to count.

current_number = 1
while current_number <= 5:
    print (current_number)
    current_number + = 1
Let users choose when to exit
The while loop can be used to allow the program to run continuously when the user wishes.

prompt = "\ nTell me something, and I will repeat it back to you:"
prompt + = "\ nEnter‘ quit ‘to end the program."
message = ""
while message! = ‘quit’:
    message = input (prompt)
    print (message)
We create a variable-message, used to store the value entered by the user. We set the initial value of the variable message to the empty string "", so that when Python first executes the while code, there is something to check. When Python executes the while statement for the first time, it is necessary to compare the value of message with ‘quit’, but the user has not yet entered it. If there is nothing to compare, Python will not be able to continue running the program. To solve this problem, we must specify an initial value for message. Although this initial value is just an empty string.

Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program.Hello again!
Hello again!

Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program.quit
quit
If you do n’t want to print the word ‘quit’, you only need a simple if test.

prompt = "\ nTell me something, and I will repeat it back to you:"
prompt + = "\ nEnter‘ quit ‘to end the program."
message = ""
while message! = ‘quit’:
    message = input (prompt)

    if message! = ‘quit’:
       print (message)
The program will do a simple check before displaying the message and print it only if the message is not an exit value.

Use logo
In the previous example, we let the program perform specific tasks when the specified conditions are met. But in a more complex program, many different events will cause the program to stop running, and it will be complicated and difficult to check all events in a while statement.

In a program that requires many conditions to be met before it can continue to run, a variable can be defined to determine whether the entire program is active. This variable is called the logo.

You can let the program continue to run when the flag is True, and stop the program when any event causes the flag to be False. In this way, only one condition needs to be checked in the while statement-the true or false of the flag. So that the program will be simple.

prompt = "\ nTell me something, and I will repeat it back to you:"
prompt + = "\ nEnter‘ quit ‘to end the program."

active = True
while active:
    message = input (prompt)

    if message == ‘quit’:
       active = False
    else:
        print (message)
We set the variable active to True to keep the program active. This simplifies the while statement.

Use break to exit the loop
To immediately exit the while loop and no longer run the code in the loop, use the break statement. The break statement is used to control the program flow, which can be used to control which code is executed and which is not executed.

For example, consider a program that lets the user indicate where he has been. In this program, we can use the break statement to exit the while loop immediately after the user enters ‘quit’:

prompt = "\ nPlease enter the name of a city you have visited:"
prompt + = "\ n (Enter‘ quit ‘when you are finished.)"

while True:
    city = input (prompt)

    if city == ‘quit’:
        break
    else:
        print ("I ‘d love to go to" + city.title () + "!")
Use continue in the loop
To return to the beginning of the loop and decide whether to continue the loop based on the results of the conditional test, use the continue statement.

For example, consider a loop that counts from 1 to 10, but only prints the odd ones.

current_number = 0
while current_number <10:
    current_number + = 1
    if current_number% 2 == 0:
        continue
    print (current_number)
Avoid infinite loops
Every while loop must have a way to stop running, so that it will not be executed endlessly.

Use a while loop to process lists and dictionaries
The for loop is an effective way to traverse the list, but the list should not be modified in the for loop, otherwise it will make it difficult for Python to track the elements. To modify the list while iterating through the list, use a while loop. By combining the while loop with lists and dictionaries, a large number of inputs can be collected, stored, and organized for later viewing and display.

Move elements between lists
Suppose there is a list of newly registered website users who have not yet received verification; after verifying these users, how to move them to another verified user list? One way is to use a while loop to extract users from the list of unverified users while verifying them, and then add them to another list of verified users.

#First, create a list of authenticated users and an empty list of stored authenticated users.
unconfirmed_users = [‘alice’, ‘brain’, ‘candace’]
confirmed_users = []

#Verify each user until there are no verified users
#Move each verified list to the verified users list

while unconfirmed_users:
    current_user = unconfirmed_users.pop ()

    print ("Verifying user:" + current_user.title ())
    confirmed_users.append (current_user)

#Show all verified users
print ("\ nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print (confirmed_user.title ())
We first created a list of unauthenticated users, and also created an empty list for storing authenticated users. The while loop keeps running until the list of unconfirmed_users becomes empty. In this loop, the function pop () removes unauthenticated users from the end of the list unconfirmed_users one at a time.

Verifying user: Candace
Verifying user: Brain
Verifying user: Alice

The following users have been confirmed:
Candace
Brain
Alice
Remove all list elements containing a specific value
Suppose you have a pet list that contains multiple elements with a value of 'cat'. To delete all these elements, you can keep running a while loop.

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

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

print (pets)
[‘Dog‘, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]
[‘Dog‘, ‘dog’, ‘goldfish’, ‘rabbit’]
Populate the dictionary with user input
The while loop can be used to prompt the user to enter any amount of information. Let's create a survey program, in which the loop prompts for the name and answer of the respondent each time it is executed. We store the collected data in a dictionary in order to associate the answers with the respondents.

responses = {}
#Set a flag to indicate whether the investigation continues
polling_active = True

while polling_active:
    #Prompt to enter the name and answer of the respondent
    name = input ("\ nWhat is your name?")
    response = input ("Which mountain would you like to climb sunday?")
    #Store the answer in a dictionary
    responses [name] = response
    #See if anyone else wants to participate in this survey
    repeat = input ("Would you like to let another person respond? (yes / no)")
    if repeat == ‘no‘:
        polling_active = False
#End of survey, display results
print ("\ n --- Poll Results ---")
for name, response in responses.items ():
    print (name + "Would like to climb" + response + ".")
Python essay 7 (while loop)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.