如何运行python循环,直到输入正确的输入字符串



我必须编写一个代码,只有当用户输入术语";Cyril";。

我是一个真正的新手,我只能想出以下解决方案,强制用户重新启动程序,直到他们输入正确的输入,但我希望它一直要求用户输入,直到他们输出正确的答案。也许有人能帮忙吗?我知道,一旦我意识到有一个简单的解决方案,我可能会踢自己。

number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("nThat is incorrect, please restart the program and try again.n")  
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("nYou have entered a number outside of the range, please try again.n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("nYou have entered a number outside of the range, please try again. n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("nThe average number you have entered is:", round(average_number, 0))

将代码开头更改为:

while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("nThat is incorrect, please try again.n") 

即使我不明白你的问题是否简单,或者我是个白痴,你也可以试试这个:

name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...

相关内容

  • 没有找到相关文章

最新更新