• python随笔7(while循环)


    使用while循环

    你可以使用while循环来数数。

    current_number = 1
    while current_number <= 5:
        print(current_number)
        current_number += 1

    让用户选择何时退出

    可使用while循环让程序在用户意愿时不断地运行。

    prompt = "
    Tell me something,and I will repeat it back to you: "
    prompt += "
    Enter 'quit' to end the program."
    message = ""
    while message != 'quit':
        message = input(prompt)
        print(message)

    我们创建一个变量——message,用于存储用户输入的值。我们将变量message的初始值设置为空字符串””,让python首次执行while代码时有可供检查的东西。python首次执行while语句时,需要将message的值与’quit’进行比较,但此时用户还没有输入。如果没有可供比较的东西,python将无法继续运行程序。为解决这个问题,我们必须给message指定一个初始值。虽然这个初始值只是一个空字符串。

    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

    如果不想将单词’quit’打印出来,只需要一个简单的if测试。

    prompt = "
    Tell me something,and I will repeat it back to you: "
    prompt += "
    Enter 'quit' to end the program."
    message = ""
    while message != 'quit':
        message = input(prompt)
    
        if message != 'quit':
           print(message)

    程序在显示消息前将做简单的检查,仅在消息不是退出值时才打印它。

    使用标志

    在前一个示例,我们让程序在满足指定条件时就执行特定的任务。但在更复杂的程序中,很多不同的事件会导致程序停止运行,如果在一条while语句中检查所有的事件将复杂而困难。

    在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活跃状态。这个变量被称为标志。

    你可以让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止。这样while语句中就只需检查一个条件——标志的真假。从而让程序便简洁。

    prompt = "
    Tell me something,and I will repeat it back to you: "
    prompt += "
    Enter 'quit' to end the program."
    
    active = True
    while active:
        message = input(prompt)
    
        if message == 'quit':
           active = False
        else:
            print(message)

    我们将变量active设置成立True,让程序处在活跃状态。这样做简化了while语句。

    使用break退出循环

    要立即退出while循环,不再运行循环中的代码,可使用break语句。break语句用于控制程序流程,可使用它控制哪些代码执行,哪些不执行。

    例如,来看一个让用户指出他到过哪些地方的程序。在这个程序中,我们可以在用户输入’quit’后使用break语句立刻退出while循环:

    prompt = "
    Please enter the name of a city you have visited: "
    prompt += "
    (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() + "!")

    在循环中使用continue

    要返回到循环开头,并根据条件测试结果决定是继续执行循环,可使用continue语句。

    例如,来看一个从1数到10,但只打印其中奇数的循环。

    current_number = 0
    while current_number < 10:
        current_number += 1
        if current_number % 2 == 0:
            continue
        print(current_number)

    避免无限循环

    每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去。

    使用while循环来处理列表和字典

    for循环是一种遍历列表的有效方式,但在for循环中不应该修改列表,否则将导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集,存储并组织大量输入,供以后查看和显示。

    在列表之间移动元素

    假设有一个列表,其中包含新注册但还未收到验证的网站用户;验证这些用户后,如何将他们移动到另一个已验证用户列表中呢?一种办法是使用while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已经验证用户列表中。

    #首先,创建一个带验证用户列表和一个用户存储已验证用户的空列表。
    unconfirmed_users = ['alice','brain','candace']
    confirmed_users = []
    
    #验证每个用户,直到没有为验证的用户
    #将每个经过验证的列表都移到已验证用户列表中
    
    while unconfirmed_users:
        current_user = unconfirmed_users.pop()
    
        print("Verifying user: " + current_user.title())
        confirmed_users.append(current_user)
    
    #显示所有已验证的用户
    print("
    The following users have been confirmed:")
    for confirmed_user in confirmed_users:
        print(confirmed_user.title())

    我们首先创建了一个未验证用户列表,还创建一个空列表,用于存放已验证用户。while循环不断运行,直到列表unconfirmed_users变为空。在这个循环中函数pop()以每次一个的方式从列表unconfirmed_users末尾删除未验证的用户。

    Verifying user: Candace
    Verifying user: Brain
    Verifying user: Alice
    
    The following users have been confirmed:
    Candace
    Brain
    Alice

    删除包含特定值的所有列表元素

    假设你有一个宠物列表,其中包含多个值为’cat’的元素,要删除所有这些元素,可不断运行一个while循环。

    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']

    使用用户输入填充字典

    可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存在一个字典中,以便将回答同被调查者关联起来。

    responses = {}
    #设置一个标志,指出调查是否继续
    polling_active = True
    
    while polling_active:
        #提示输入被调查者的名字和回答
        name = input("
    What is your name? ")
        response = input("Which mountain would you like to climb sunday? ")
        #将答案存储在字典中
        responses[name] = response
        #看看是否还有人要参加这个调查
        repeat = input("Would you like to let another person respond?(yes/ no) ")
        if repeat == 'no':
            polling_active = False
    #调查结束,显示结果
    print("
    --- Poll Results ---")
    for name,response in responses.items():
        print(name + " Would like to climb " + response + ".")
  • 相关阅读:
    LeetCode 169. Majority Element
    Object-c block块
    Object-c动态特性
    Object-c基础(2)
    Object-c基础
    LeetCode171:Excel Sheet Column Number
    LeetCode242:Valid Anagram
    LeetCood8:String to Integer
    理解qsort 中的 cmp
    google goble cache
  • 原文地址:https://www.cnblogs.com/wf1017/p/9408971.html
Copyright © 2020-2023  润新知