首页 > 解决方案 > 为什么在这个日期检查条件的 if-else 阶梯中“正确”不更改为 False?

问题描述

我已经correct = bool()在脚本开头的任何函数或循环之外声明。我定义了一个函数并具有以下条件。这是我的代码。

correct = bool()

...

def part1():
    global date, now, m, d, query


    #getting the date
    raw = input("Date: (MM/DD) ")
    #splitting the date by /
    m, d = raw.split("/")
    #checking for invalid date


    if int(m) > 12 or int(m) < 1:
        print("Something's wrong with your date.1")
        correct = False
    #February 29
    if int(m) == 2 and int(d) > 29:
        print("Something's wrong with your date.2")
        correct = False
    if int(m) in thirties and int(d) > 30:
        print("Something's wrong with your date.3")
        correct = False
    if int(m) in thirty_ones and int(d) > 31:
        print("Something's wrong with your date.4")
        correct = False
    if int(d) < 1:
        print("Something's wrong with your date.5")
        correct = False
    else:
        correct = True

    print(correct)
    #creating string of date from numbers
    if correct == True:
        date = months[m] + " " + d
        print("Date = ", date)
        #creating query
        query = months[m] + " " + d
        print("Query: " + query)

如果我输入 01/35(1 月 35 日,显然是无效的日期),它会检查条件并打印“您的日期有问题。4”,告诉我条件有问题if int(m) in thirty_ones and int(d) > 31:thirty_ones是代表月份的数字列表31 天与correct = bool()) 一起宣布。既然它打印了那个声明,那么它就会做出correct = False. 但是,即使correct = False. 这是为什么?

(为代码中的缩进问题道歉)

标签: python

解决方案


你需要使用elif.

if int(m) > 12 or int(m) < 1:
    print("Something's wrong with your date.1")
    correct = False
    #February 29
elif int(m) == 2 and int(d) > 29:
    print("Something's wrong with your date.2")
    correct = False
elif int(m) in thirties and int(d) > 30:
    print("Something's wrong with your date.3")
    correct = False
elif int(m) in thirty_ones and int(d) > 31:
    print("Something's wrong with your date.4")
    correct = False
elif int(d) < 1:
    print("Something's wrong with your date.5")
    correct = False
else:
    correct = True

推荐阅读