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()
defkeyword to define a function.==and not=for comparisons.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:
Here, we are passing an ‘argument’ to the function. we call it with
am_i_alive(x)wherexcan be any number. In the code for the functionam_i_alive, whatever we put in place ofxbecomes the value referred to byhit_points.A function can take two arguments as well. (in fact, up to 255 arguments)
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.