如何在Python中创建循环[重复]

2024-04-08

这是我的代码:

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 个字符。我需要知道如何让程序再次成为一个句子,但我认为最简单的方法是让代码从顶部开始;但我不知道该怎么做。有人可以帮忙吗?


图案

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

# 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 https://stackoverflow.com/a/23294659/135978).

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

将模式映射到您的具体案例

您想要提示用户为您提供一个少于十个字符的句子。这是模式#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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中创建循环[重复] 的相关文章

随机推荐