Skip to content Skip to sidebar Skip to footer

How To Create A Loop In Python

This is my code: my_Sentence = input('Enter your sentence. ') sen_length = len(my_Sentence) sen_len = int(sen_length) while not (sen_len < 10 ): if sen_len < 10: prin

Solution 1:

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)
        breakelse:
        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 responseswhileTrue:
    user_response = get_user_input()

    if test_that(user_response) is quit:
        breakif 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 responsewhileTrue:
    sentence = input("Please provide a sentence")
    # Check for invalid statesiflen(sentence) >= 10:
        # Warn the user of the invalid stateprint("Sentence must be under 10 characters, please try again")
    else:
        # Do the one-off work you need to doprint("Thank you for being succinct!")
        break

Solution 2:

longEnough = falsewhile not longEnough:
    sentence = raw_input("enter a sentence: ") # Asks the user for their string
    longEnough = len(sentence) > 10 # Checks the length

Post a Comment for "How To Create A Loop In Python"