-1

I'm starting with some basic stuff to get a feeling for how to make a text based game. After creating the .py file in my IDE, I open terminal and use bash to open the .py file.

hpGanon = 10
damage = input("How much damage did you do with the Master Sword?")
hpGanon = hpGanon - damage
print("Ganon now has " + hpGanon + "hit points.")

At the end when I want it to print, bash tells me it cannot concatenate 'str' and 'int' objects. I tried following what was said in the following post, Python: TypeError: cannot concatenate 'str' and 'int' objects But I'm not getting the result I want.

I just want it to say: "Ganon now has x hit points." Any ideas?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
aalink
  • 33
  • 1
  • 3
  • 1
    Try `"Ganon now has " + str(hpGanon) + "hit points."` – Patrick Haugh Jun 26 '17 at 23:07
  • 2
    You seem to be on Python 2, not Python 3. – user2357112 Jun 26 '17 at 23:08
  • 1
    Why do you think `bash` is giving you that error? It should be coming from Python. Bash has nothing to do with what happens when you're running a Python script. – Barmar Jun 26 '17 at 23:57
  • oh thanks for pointing that out Barmar, I didn't even think of it that way. Now that i think about it, python is the one saying the error before the program ends and then it returns me to the bash prompt. Is that what you mean? – aalink Jun 27 '17 at 00:27
  • "I tried following what was said in the following post... But I'm not getting the result I want." It is not useful to say things like this in a question on Stack Overflow. Instead, **show exactly what changes were made to the code**, and then **explain what happened as a result**. – Karl Knechtel Sep 09 '22 at 07:34

2 Answers2

0

I'm not entirely sure (I have never coded with Python before) but it seems that the hpGanon variable is an integer and not a string, so it cannot put the two together. To convert an integer to a string in Python (I searched this up :P), you need to do str(integer).

So, to implement this in your example, try something like this:

print("Ganon now has " + str(hpGanon) + "hit points.")

aimorris
  • 436
  • 3
  • 18
-2

You can do your mathematical calculation and convert it into string, for example

a = x*3
str(a)

and now if you call it in your print statement, it will work.

a = x*3
str(a)
print("3 x {} = {} ").format(x,a)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • `str(a)` on its own doesn't save its result, so that doesn't help. Using `str.format()` would work, but in the last line, the closing parenthesis is in the wrong place (assuming you're running Python 3, which you should be). Anyway, this question is a duplicate of [How can I concatenate str and int objects?](/q/25675943/4518341), and the top answer there already covers `str.format()`, so no point duplicating that info here. – wjandrea Jul 30 '22 at 02:43