If statement 决策树Python与异常2.7
我正在写一个脚本,计算1900-2099年复活节的日期。 问题是,在特定的4年(1954年、1981年、2049年和2076年)中,公式有一点不同(即日期为7天)If statement 决策树Python与异常2.7,if-statement,python-2.7,If Statement,Python 2.7,我正在写一个脚本,计算1900-2099年复活节的日期。 问题是,在特定的4年(1954年、1981年、2049年和2076年)中,公式有一点不同(即日期为7天) def main(): print“计算1900-2099年的复活节日期。\n” 年份=输入(“年份:”) 如果年份>=1900且年份则无法链接这样的表达式;使用和运算符链接测试,或使用不在表达式中: # and operators if year != 2049 and year != 2076 and year != 1981 a
def main():
print“计算1900-2099年的复活节日期。\n”
年份=输入(“年份:”)
如果年份>=1900且年份则无法链接这样的表达式;使用和
运算符链接测试,或使用不在
表达式中:
# and operators
if year != 2049 and year != 2076 and year != 1981 and year != 1954:
# not in expression
if year not in (2049, 2076, 1981, 1954):
表达式year!=2049 != 2076 !=1981 != 1954年
的意思有所不同,它被解释为((年份!=2049)!=2076)!=1981)!=1954年
;第一个测试是True
或False
,这两个值都不会等于任何其他数字,并且该分支将始终计算为False
尽管如此,您仍然会得到date
的UnboundLocalError
,因为您的else
分支引用了date
,但它从未在该分支中设置。当执行else
分支时,Python看到的所有内容都是:
def main():
print "Computes the date of Easter for years 1900-2099.\n"
year = input("The year: ")
if year >= 1900 and year <= 2099:
if False:
# skipped
else:
if date <= 31:
print "The date of Easter is March", date - 7
else:
print "The date of Easter is April", date - 31 - 7
def main():
print“计算1900-2099年的复活节日期。\n”
年份=输入(“年份:”)
如果年份>=1900,如果我正确阅读代码,那么需要做的就是将a=
行移到date=
行左侧一级,然后将if year not in
行移到date=
行下方。您用最后一个代码@Martijn揭示了本地错误,对此我再次表示感谢。您在@DSM处完美地阅读了代码,它起了作用!!!谢谢我欠你们很多人情。
def main():
print "Computes the date of Easter for years 1900-2099.\n"
year = input("The year: ")
if year >= 1900 and year <= 2099:
if False:
# skipped
else:
if date <= 31:
print "The date of Easter is March", date - 7
else:
print "The date of Easter is April", date - 31 - 7