在python中使用continue如何跳出单个循环?

2024-09-27 00:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一些代码,其中包含几个while循环。你知道吗

    answer = "yes"
    while answer == "yes":
        name = input("what is your name?")
        while len(name) > 0 and name.isalpha():
            print("okay")
            break
      else:
          print("error")
          continue
      job = input("what is your job?")
      while job.isalpha():
          print("great")
      else:
          print("not so great")
          continue 
      age = input("how old are you?")
      while age.isnumeric():
          print('nice')
      else:
          print("not so nice")
          continue

我想让代码做的是检查一个有效的名称条目,如果它是无效的,请重新询问用户的名称。我希望他们的工作也一样。不幸的是,当我在job语句之后使用continue时,它不仅会重新询问他们的工作,还会重新询问他们的姓名。有人知道如何使它只重新要求的工作,而不是重新做整个程序吗?有人知道我怎么能复制多个while循环,比如问工作、姓名、年龄、星号等。?你知道吗

谢谢你。你知道吗


Tags: 代码answernameinputyourisjobwhat
2条回答

我把问题移到一个单独的函数中去重复代码。只要答案不令人满意,它就会一次又一次地问。你知道吗

def ask(s):
    r = ""
    while not r or not r.isalpha():
        r = input(s)
    return r

name = ask("What is your name?")
print("Okay. Your name is {}.".format(name))
job = ask("What is your job?")
print("Great. Your job is {}.".format(job))
  1. 您可以使用while True,因为答案永远不会改变。你知道吗
  2. 一次表情一次休息都没用。你知道吗

你应该把每件事都说得对一点,然后检查一下:

 while True:
     name = input("what is your name?")
     job = input("what is your job?")
     if len(name) > 0 and name.isalpha() and job.isalpha():
         print("great")
         break
     print("error")

相关问题 更多 >

    热门问题