如何在Python中创建循环

时间:2014-06-11 23:35:20

标签: python loops python-3.4

这是我的代码:

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

我试图让程序要求用户连续写一个句子,直到它不到10个字符。我需要知道如何让程序再次成为一个句子,但我认为最简单的方法是让代码从顶部开始;但我不知道怎么做。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

模式

重复提示用户输入的一般模式是:

# 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

我们使用无限循环while True:而不是重复我们的get_user_input函数两次(hat tip)。

如果您想查看相反的情况,只需更改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()

如果您需要在循环中工作但在用户提供无效输入时发出警告,那么您只需要添加一个检查某种quit命令的测试,并且只有break那里:

# 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()

将模式映射到您的特定情况

您想提示用户为您提供少于十个字符的句子。这是模式#2的实例(许多无效响应,只需要一个有效响应)。将模式#2映射到我们得到的代码:

# 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

答案 1 :(得分:0)

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