当某个输入异常时,如何使python中断

2024-06-09 21:55:51 发布

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

所以我只是想用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

Tags: ofinputdaterawisyearconfirmyes
3条回答

试着这样运行你的代码

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。你知道吗

.lower()将字符串转换为小写。因此,如果用户键入“YES”或“YES”等。。它将读取字符串作为“yes”。你知道吗

还可以使用.upper()将字符串转换为大写。希望这有帮助。你知道吗

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)
>>>

看看你的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?")

相关问题 更多 >