python - 为什么在这个日期检查条件的 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
. 这是为什么?
(为代码中的缩进问题道歉)
解决方案
你需要使用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
推荐阅读
- samtools - 如何使用 pysam 在 bam 文件中添加带有读取质量分数的“OQ”标签作为附加字段
- c++ - 为什么我能够增加指向单个新 int 位置的指针?令人惊讶的是它运作良好
- python - 为什么我生成的 WHERE 子句不正确?
- playlist - 在 Android 中为 ExoPlayer 使用 ConcatenatingMediaSource
- python - 如何根据条件将数据框列拆分为单独的列
- angular - Ngrx 问题试图结合 DRY 原则和良好的动作卫生
- python - Python extract title from URL
- javascript - 我的节点服务器没有使用 browsersync 作为代理加载页面
- android - 如何在社交媒体(whatsapp、gmail 等)、android studio 上共享/发送音频文件
- reactjs - React Graphql Typescript - 类型“{}”上不存在属性