views:

71

answers:

1

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()
+7  A: 
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()
  1. You need the def keyword to define a function.
  2. You need to use == and not = for comparisons.
  3. 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.

aaronasterling
oh! That makes sense now! Thank you!
Jostlyn Walton
You also need `elif` instead of `else if`.
Fred Larson
@Fred Larson. Good looking out. I'm taking a break from some C coding ;)
aaronasterling
@Jostlyn Walton, be sure that you take note of Fred Larson's comment.
aaronasterling
@AaronMcSmooth, Thank you again! Very helpful and clear answer.
Jostlyn Walton