【问题标题】:How do i return to the beginning of my code/have a nested loop?我如何返回到我的代码的开头/有一个嵌套循环?
【发布时间】:2016-02-05 16:20:31
【问题描述】:

我希望我的代码运行,以便如果条件不满足(在 if 循环中),它将返回到代码的开头,要求用户输入另一个句子。我如何添加这个嵌套循环(如果这就是它的名字)?

sentence = input("Please input a sentence: ")
word = input("Please input a word: ")
sentence = sentence.lower()
word = word.lower()
wordlist = sentence.split(' ')
print ("Your word, {0}, is in positions:".format (word))
for position,w in enumerate(wordlist):
    if w == word:
        print("{0}".format(position+1))

【问题讨论】:

    标签: python string loops nested


    【解决方案1】:

    您可以在您的代码和breakcontinue 周围放置一个while 循环,具体取决于输入:

    while True:
         sentence = input("Please input a sentence: ")
         if bad(sentence): # replace with actual condition
             continue
         ...
         for position, w in enumerate(wordlist):
             ...
         break
    

    【讨论】:

      【解决方案2】:

      只要做:

      while True:
          sentence = input("Please input a sentence: ")
          if sentence.lower() == "quit": break
          word = input("Please input a word: ")
          sentence = sentence.lower()
          word = word.lower()
          wordlist = sentence.split(' ')
          print ("Your word, {0}, is in positions:".format (word))
          for position,w in enumerate(wordlist):
              if w == word:
                  print("{0}".format(position+1))
      

      【讨论】:

      • 这绝对是一个无限循环
      • @cricket_007 关于您在现已删除的 Mohammed 的答案中的问题,break 位于嵌套的 for 循环内,它脱离了 for 循环,而不是外部 while 循环跨度>
      • 是的,当然……Po 可以很容易地询问或退出循环,不是吗?
      • @Aprillion - 是的,我在你评论之前就意识到了
      • 我已经为循环添加了一个出口
      猜你喜欢
      • 2016-05-08
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多