-1

What I'm trying to do is make a function that subtracts the total value of another variable from the main one. I tried to create this but failed... I tried doing this.

  def punch():
    b = random.randint(0,100)
    goblinhp = 100
    goblinhp = goblinhp - int(b)
    print("Goblin's HP is Now: " + goblinhp)
  opt = input("What do you want do? (punch/kick/heal): ")
  if opt == "punch":
    punch()

but, in return, it showed these error messages.

Traceback (most recent call last):
  File "main.py", line 79 in <module>
    punch()
  File "main.py", line 76 in punch
    print("Goblin's HP is Now: " + goblinhp)
TypeError: can only concatentate str (not "int") to str

what caused these errors, and how can I fix them.

vehn
  • 49
  • 9

3 Answers3

1

The problem is that you are trying to concatenate a String with an Integer as shown in the error.

TypeError: can only concatentate str (not "int") to str

Try the following

print("Goblin's HP is Now: " + str(goblinhp))

This will convert your integer to a string.

0

Corrections below. + needs two strings (for concatenation) or two integers (for addition). Can't add a string and an integer. print automatically prints the str() of each argument, so pass the integer as an argument.

import random

def punch():
    b = random.randint(0,100)  # this returns an int, so b will be int    
    goblinhp = 100
    goblinhp = goblinhp - b    # don't use int(b) here, redundant
    print("Goblin's HP is Now:",goblinhp) # use a comma to print string, then int

opt = input("What do you want do? (punch/kick/heal): ")
if opt == "punch":
    punch()
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

Using f-strings is a good way to avoid these kinds of issues

print(f"Goblin's HP is Now: {goblinghp}")

This approach has two main advantages:

  1. better readability
  2. letting Python handle the necessary conversions automagically behind the scenes.
Jivan
  • 21,522
  • 15
  • 80
  • 131