假设你已经写了一个新的函数来检查你的游戏角色是否还有生命。如果字符没有任何剩余生命,则函数应打印'dead',如果剩余生命点小于或等于5,则函数应打印‘any’,否则应打印'alive‘。
am_i_alive():
hit_points = 20
if hit_points = 0:
print 'dead'
else hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive()发布于 2010-09-17 13:48:22
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()对于使用elif.的comparisons.
def关键字来定义函数。
==而不是=除此之外,它看起来还不错。如在正确的,并将编译。不过,它始终会产生相同的值。
一种更好的方法是:
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)你能理解最后一个版本是做什么的吗?
我没有读它,因为python不是我的第一语言,但有人告诉我这是一个非常好的introduction to python and programming。
https://stackoverflow.com/questions/3732899
复制相似问题