def am_i_alive():
hit_points = 20
if hit_points == 0:
print 'dead'
elif hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive()
- 您需要
def
关键字来定义一个函数。
- 您需要使用
==
而不是=
进行比较。
- 如果使用
elif
表示陈述,则链接。
除此之外,它看起来不错。在正确和将编译。它将始终产生相同的价值。
一个更好的办法来做到这一点是:
def am_i_alive(hit_points):
if hit_points == 0:
print 'dead'
elif hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive(20)
am_i_alive(3)
am_i_alive(0)
在这里,我们传递一个“说法”的功能。我们称之为am_i_alive(x)
,其中x
可以是任何数字。在函数am_i_alive
的代码中,无论我们用什么来代替x
都成为hit_points
所指的值。
函数也可以带两个参数。 (实际上最多255个参数)
def am_i_alive(hit_points, threshold):
if hit_points == 0:
print 'dead'
elif hit_points <= threshold:
print 'almost dead'
else:
print 'alive'
am_i_alive(20, 5)
am_i_alive(3, 2)
am_i_alive(0, 10)
您能理解上一个版本的作用吗?
我没有读它,因为蟒蛇不是我的第一语言,但我被告知这是一个非常好的introduction to python and programming。
你的单元测试用例在哪里?如果你会写一些测试用例,你会知道错误是什么,不是吗? – 2010-09-17 10:02:31
@ S.Lott在代码显示的情况下,我会说它是它自己的单元测试;) – aaronasterling 2010-09-17 18:22:35