Python函数:回答是或否-出了问题

Python函数:回答是或否-出了问题,python,function,command,Python,Function,Command,测试通过的年份是否大于或等于1582 def gregyear(): try: year =raw_input("Pick a year greater than or equal to 1582. It has to be divisible by four.)\n") year =float(year) leapyear = "Yes" except: print "please, only numbers"

测试通过的年份是否大于或等于1582

def gregyear():

    try:
        year =raw_input("Pick a year greater than or equal to 1582. It has to be divisible by four.)\n")
        year =float(year)
        leapyear = "Yes"
    except:
        print "please, only numbers"
    else:
        year =float(year)
        if  year >= 1582:
            if year % 4:
                print year
                leapyear= "Yes"
            else:
                leapyear= "No"
        else:
            print "Wrong... print a year greater than 1582"


    return leapyear

gregyear()
print "leapyear is  "+ leapyear +"."

首先,在Python中,0是假的,而所有其他数字都是真的。因此,当您这样做时:

if year % 4:
…如果
year%4
不是
0
,也就是说,如果年份不能被4整除,则会触发该事件。所以你的逻辑是倒退的


第二,虽然
gregyear
确实返回了一个值,但如果要使用该返回值,则必须将其存储:

leapyear = gregyear()

第三,您不能将字符串添加到数字中,因此这将引发
类型错误

print "leapyear is  "+ leapyear +"."
您可能希望将字符串和数字传递给
print
,以便在打印时神奇地连接在一起,如下所示:

print "leapyear is", leapyear, "."
注意,我删除了额外的空格,因为带有逗号的
print
会自动在其参数之间加空格

但是,更好的编写方法是使用字符串格式:

print "leapyear is {}.".format(leapyear)


顺便说一句,你还没有找到1700年、1800年和1900年不是闰年(而1600年和2000年不是)的规则。

你的问题是什么?您所做的只是发布一些代码。请先了解python基础知识。这将是一个很好的机会,让您了解堆栈跟踪并了解发生了什么。示例:代码末尾的打印范围中未定义以
leapyear开始。(了解函数如何返回值等的良好起点)