How to create a loop in Python [duplicate]

柔情痞子 提交于 2019-12-02 15:14:22
Sean Vieira

The pattern

The general pattern for repeatedly prompting for user input is:

# 1. Many valid responses, terminating when an invalid one is provided
while True:
    user_response = get_user_input()
    if test_that(user_response) is valid:
        do_work_with(user_response)
    else:
        handle_invalid_response()
        break

We use the infinite loop while True: rather than repeating our get_user_input function twice (hat tip).

If you want to check the opposite case, you simply change the location of the break:

# 2. Many invalid responses, terminating when a valid one is provided
while True:
    user_response = get_user_input()
    if test_that(user_response) is valid:
        do_work_with(user_response)
        break
    else:
        handle_invalid_response()

If you need to do work in a loop but warn the user when they provide invalid input then you just need to add a test that checks for a quit command of some kind and only break there:

# 3. Handle both valid and invalid responses
while True:
    user_response = get_user_input()

    if test_that(user_response) is quit:
        break

    if test_that(user_response) is valid:
        do_work_with(user_response)
    else:
        warn_user_about_invalid_response()

Mapping the pattern to your specific case

You want to prompt a user to provide you a less-than-ten-character sentence. This is an instance of pattern #2 (many invalid responses, only one valid response required). Mapping pattern #2 onto your code we get:

# Get user response
while True:
    sentence = input("Please provide a sentence")
    # Check for invalid states
    if len(sentence) >= 10:
        # Warn the user of the invalid state
        print("Sentence must be under 10 characters, please try again")
    else:
        # Do the one-off work you need to do
        print("Thank you for being succinct!")
        break
longEnough = false
while not longEnough:
    sentence = raw_input("enter a sentence: ") # Asks the user for their string
    longEnough = len(sentence) > 10 # Checks the length
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!