How to create a loop in Python [duplicate]

2020-05-10 11:11发布

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:
      print ('Good')
  else:
      print ('Wo thats to long')
  break

I'm trying to make the program ask the user continuously to write a sentence, until it is under 10 characters. I need to know how to have the program as for a sentence again, but I think the simplest way would be to have the code start from the top; but I'm not surte how to do that. Can someone help?

2条回答
三岁会撩人
2楼-- · 2020-05-10 11:53
longEnough = false
while not longEnough:
    sentence = raw_input("enter a sentence: ") # Asks the user for their string
    longEnough = len(sentence) > 10 # Checks the length
查看更多
Explosion°爆炸
3楼-- · 2020-05-10 12:12

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
查看更多
登录 后发表回答