【问题标题】:Is there a way to loop back to the beginning of a certain part of the code in python有没有办法循环回到python中某个部分代码的开头
【发布时间】:2021-12-18 20:14:40
【问题描述】:

我正在编写一个脚本来检查输入单词的长度是否等于某个数字,如果不等于则再次循环回到输入问题。

我使用了以下代码,

x=input("input a word")

y=len(x)

while y<8 or 8<y:

  print("word must have 8 
         characters")

    continue

  print("word accepted")

    break

但问题是当使用“继续”循环时,它不会循环回输入的问题。输入问题也不能写在while循环中,因为它给出了一个错误“x is not defined”。

那么我怎样才能循环回到这里的输入问题。无论如何要这样做。

【问题讨论】:

  • 将所有内容包装成while True。或者使用递归

标签: python loops input while-loop back


【解决方案1】:

while 循环之前已经分配了长度,所以你永远不会得到新的输入。您必须在while 循环中获取输入,这样您才能一次又一次地获取新输入。

这如你所愿:

while True:
    x = input("input a word: ")
    if len(x) != 8:
        print("word must have 8 characters")
        continue
    else:
        print("word accepted")
        break

【讨论】:

  • 可能值得一提的是,对于 python >= 3.8,您还可以使用 := 运算符进行简化:while len(x := input("input a word:")) != 8: print("word must have 8 characters")
【解决方案2】:

两种方法,使用while True

while True:
    x=input("input a word: ")
    if len(x) == 8:
        break
    print("word must have 8 characters")

使用递归:

def get_input():
    x=input("input a word: ")
    if len(x) == 8:
        return x
    print("word must have 8 characters")
    return get_input()

【讨论】:

  • 我怀疑你的递归解决方案。您忽略了递归调用中的返回值。
  • 你是对的。我的错。
【解决方案3】:
while True==True:
  x=input("input a word")
  y=len(x)
  if y==8:
    print("word accepted")
    break
  else:
    print("word must have 8 characters")
    # continue

【讨论】:

  • ...请不要使用while True == Truewhile True 更加地道。
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多