所以我只是想用python写一些东西,我需要使此代码循环直到指定“ Yes”或“ yes”,但即使未指定“ Yes”或“ yes”,它也会不断中断。请帮助我解决此问题,并在此先感谢。
print("Please now take the time to fill in your DOB:")
DOB_day = raw_input ("Date of month:")
DOB_month = raw_input ("Month:")
DOB_year = raw_input ("Year:")
DOB_confirmation = raw_input ("Please confirm, is this correct?")
while DOB_confirmation != "No" or "no":
DOB_day = raw_input ("Date of month:")
DOB_month = raw_input ("Month:")
DOB_year = raw_input ("Year:")
DOB_confirmation = raw_input ("Please confirm, is this correct?")
if DOB_confirmation == "Yes" or "yes":
break
答案 0 :(得分:1)
看看您的while DOB_confirmation != "No" or "no":
行。您正在尝试说“虽然确认答案不是,但继续要求生日”……但这不是您写的。您还错误地使用了or
。
尝试以下操作:while DOB_confirmation.lower() != "yes":
。实际上就是说“您没有在用户输入任何形式的'是'”。
您可以在末尾消除if
语句-while
循环将其覆盖。
尝试一下:
print("Please now take the time to fill in your DOB:")
DOB_day = input("Date of month:")
DOB_month = input("Month:")
DOB_year = input("Year:")
DOB_confirmation = input("Please confirm, is this correct?")
while DOB_confirmation.lower() != "yes":
DOB_day = input("Date of month:")
DOB_month = input("Month:")
DOB_year = input("Year:")
DOB_confirmation = input("Please confirm, is this correct?")
答案 1 :(得分:0)
尝试这样运行代码
print("Please now take the time to fill in your DOB:")
while True:
DOB_day = raw_input("Date of month:")
DOB_month = raw_input("Month:")
DOB_year = raw_input("Year:")
DOB_confirmation = raw_input ("Please confirm, is this correct? (Yes/No)")
if DOB_confirmation.lower() == "yes":
break
我喜欢做这种类型的循环,它可以替代Java中的do-while。
.lower()
将您的字符串变成小写。因此,如果用户键入“是”或“ yEs”等,它将像“是”一样读取字符串。
您还可以使用.upper()
将字符串变成大写。希望这会有所帮助。
答案 2 :(得分:0)
raw_input
在我的Python版本(3.7.0)中未定义,因此我将其替换为常规input
。此外,一旦我缩进了所有内容,除了接受“是”之外,它似乎都可以正常工作。
代码:
print("Please now take the time to fill in your DOB:")
DOB_day = input ("Date of month:")
DOB_month = input ("Month:")
DOB_year = input ("Year:")
DOB_confirmation = input ("Please confirm, is this correct?")
while DOB_confirmation != "No" or "no":
DOB_day = input ("Date of month:")
DOB_month = input ("Month:")
DOB_year = input ("Year:")
DOB_confirmation = input ("Please confirm, is this correct?")
if DOB_confirmation == "Yes" or "yes":
break
print("broke (the good way)")
输出:
================= RESTART: C:/work/stackoverflow/laksjdfh.py =================
Please now take the time to fill in your DOB:
Date of month:asdf
Month:fasd
Year:3232
Please confirm, is this correct?q
Date of month:asdf
Month:fasd
Year:gggf
Please confirm, is this correct?YES
broke (the good way)
>>>