我有一个课程要做。我需要通过所有必需的6个测试。我已经通过了5,但是对于Python中的类有一个问题。
def doomsday(y):
"""
>>> doomsday(2012)
3
>>> doomsday(1899)
2
>>> doomsday(1923)
3
>>> doomsday(10000)
-1
>>> doomsday(1756)
-1
>>> type(doomsday(2010))
<class 'int'>
"""
try:
y
except ValueError:
return
if y in range (1800, 1899+1):
x = 5
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
print (t)
else:
print (t)
elif y in range (1900, 1999+1):
x = 3
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
print (t)
else:
print (t)
elif y in range (2000, 2099+1):
x = 2
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
print (t)
else:
print (t)
elif y in range (2100, 2199+1):
x = 0
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
print (t)
else:
print (t)
else:
x = -1
print (x)
我无法通过此测试:
type(doomsday(2010))
class 'int'
错误是:
Failed example:
type(doomsday(2010))
Expected:
class 'int'
Got:
0
class 'NoneType'
答案 0 :(得分:0)
只需要返回值而不是打印它们:
def doomsday(y):
"""
>>> doomsday(2012)
3
>>> doomsday(1899)
2
>>> doomsday(1923)
3
>>> doomsday(10000)
-1
>>> doomsday(1756)
-1
>>> type(doomsday(2010))
<class 'int'>
"""
try:
y
except ValueError:
return
if y in range (1800, 1899+1):
x = 5
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
return t
else:
return t
elif y in range (1900, 1999+1):
x = 3
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
return t
else:
return t
elif y in range (2000, 2099+1):
x = 2
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
return t
else:
return t
elif y in range (2100, 2199+1):
x = 0
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
return t
else:
return t
else:
x = -1
return x
答案 1 :(得分:0)
您的错误可能来自您认为print()
返回某些值的事实。它没有。
您的函数不返回任何内容,因此将返回返回值为None的隐式返回。如果希望函数返回一个整数,则需要显式执行。即将print()
替换为return
s
来自Python Documentation on functions:
[...]甚至没有return语句的函数都返回一个值[...],这个值被称为None(它是一个内置名称)。写入值None通常会被解释器抑制,如果它是唯一写入的值。 [...]
(强调我的)
def世界末日(y):
"""
>>> doomsday(2012)
3
>>> doomsday(1899)
2
>>> doomsday(1923)
3
>>> doomsday(10000)
-1
>>> doomsday(1756)
-1
>>> type(doomsday(2010))
<class 'int'>
"""
try:
y
except ValueError:
return
if y in range (1800, 1899+1):
x = 5
w = y%100
a = w//12
b = w%12
c = b//4
d = (a + b + c)%7
t = x + d
if t>6:
t = t - 7
return t
else:
return t
etc...