我编写了一些包含多个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
我想要的代码是检查有效的名称条目,如果它无效,请重新询问用户的名字。我希望它能够对自己的工作做同样的事情。不幸的是,当我在工作陈述后继续使用时,不仅仅是重新询问他们的工作,它还会重新询问他们的名字。有谁知道如何让它只重新询问工作,而不是重新做整个程序?有谁知道我如何能够复制多个while循环I.e.要求工作,姓名,年龄,星座等?
谢谢。
答案 0 :(得分:0)
while True
因为答案永远不会改变。你应该把所有东西都放一会儿,然后检查:
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")
答案 1 :(得分:0)
我将问题转移到单独的功能中以重复删除代码。只要答案不能令人满意,它就会一次又一次地问。
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))