Problem with function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Incoming
    New Member
    • Jun 2010
    • 1

    Problem with function

    Ok, so i've been trying to learn how to use def function. I tried to make a simple archery game based on chance.

    Code:
    import random
    loop=1
    HP=100
    def shot(z):
      if z<50:
       return 50
       print ("Direct Hit")
      elif z >= 50:
       print ("Missed")
    while loop==1:
     h=random.random()*100
     n=shot(h)
     choice=raw_input("Pick a shot type(shot, headshot)")
     if choice == "shot":
      HP=100-n
     if HP<=0:
      print ('You win')
      loop=0
     print (HP)
     print (h)
    If the shot misses, then this happens

    Traceback (most recent call last):
    File "/home/usr/Desktop/archery.py", line 15, in <module>
    HP=100-n
    TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
    I have no idea what I did wrong. Any help would be much appreciated.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    shot() returns None when "z" >= 50, therefore the error. You must return a number. Example:
    Code:
    >>> def x():
    ... 	print "X"
    ... 	
    >>> 100-x()
    X
    Traceback (most recent call last):
      File "<interactive input>", line 1, in ?
    TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
    >>> def x():
    ... 	print "X"
    ... 	return 50
    ... 
    >>> 100-x()
    X
    50
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      If you are trying to update a score then it would be done like this.
      Code:
      def shot(z, score):
          if z < 50:
              score += 50
              print ("Direct Hit")
      
          ## z >= 50 is redundant as that is the only possibility
          else:
              print ("Missed")
      
          return score
      
      score = 0
      loop = 1
      while loop==1:
          h=random.random()*100
          score=shot(h, score)
      ## etc.

      Comment

      Working...