Python while 循环

作者: 赵者也 | 来源:发表于2018-01-25 09:28 被阅读24次
    1. 让用户选择何时退出
    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)
    

    示例输出:

    让用户选择何时退出
    1. 使用标志
    prompt = "\nTell me something, and I will repeat it back to you:"
    prompt += "\nEnter 'quit' to end the program. "
    
    action = True
    
    while action:
        message = input(prompt)
        if message == "quit":
            action = False
        else:
            print(message)
    

    示例输出:

    使用标志
    1. 使用 break 退出循环
    prompt = "\nTell me something, and I will repeat it back to you:"
    prompt += "\nEnter 'quit' to end the program. "
    
    while True:
        message = input(prompt)
        if message == "quit":
            break
        else:
            print(message)
    
    1. 在循环中使用 continue
    current_number = 0
    while current_number < 10:
        current_number += 1
        if current_number % 2 == 0:
            continue
        print(current_number)
    

    示例输出:

    在循环中使用 continue
    1. 在列表之间移动元素
    unconfirmed_users = ['alice', 'brian', 'candace']
    confirmed_users = []
    
    while unconfirmed_users:
        current_user = unconfirmed_users.pop()
        print("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())
    

    示例输出:

    在列表之间移动元素
    1. 删除包含特定值的所有列表元素
    pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    print(pets)
    while 'cat' in pets:
        pets.remove('cat')
    print(pets)
    
    1. 使用用户输入来填充字典
    responses = {}
    
    while True:
        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':
            break
    
    print("\n--- Poll Results ---")
    
    for name, response in responses.items():
        print(name + " would like to climb " + response + ".")
    

    示例输出:

    使用用户输入来填充字典

    本文参考自 《Python 编程:从入门到实践

    相关文章

      网友评论

        本文标题:Python while 循环

        本文链接:https://www.haomeiwen.com/subject/cgqpaxtx.html