Assume you have written a new function that checks to see if your game character has any life left. If the character does not have any life left, the function should print 'dead', if it has less than or equal to 5 life points left the function should print 'almost dead', otherwise it should print '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()
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()
- You need the
def
keyword to define a function. - You need to use
==
and not=
for comparisons. - You chain if statements using
elif
.
other than that, it looks good. As in correct and will compile. It will always yield the same value though.
A better way to do it is:
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)
Here, we are passing an 'argument' to the function. we call it with am_i_alive(x)
where x
can be any number. In the code for the function am_i_alive
, whatever we put in place of x
becomes the value referred to by hit_points
.
A function can take two arguments as well. (in fact, up to 255 arguments)
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)
Can you understand what the last version does?
I didn't read it because python is not my first language, but I'm told that this is a very good introduction to python and programming.
精彩评论