2

I am following a tutorial and I am getting an error.

My code should be this:

salaries = {'John':'20','Sally':'30','Sammy':'15'}
print(salaries['John'])

salaries['John'] = salaries['John'] + 30
print(salaries['John'])

I am getting back an error like this

Traceback (most recent call last): File "print.py", line 9, in salaries['John'] = salaries['John'] + 30 TypeError: can only concatenate str (not "int") to str

Can you help me with this?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Alex
  • 33
  • 1
  • 3

3 Answers3

1

If you wanted to include the 30 you'd have to put something like str(30). That's why it's giving you that error cause 30 is an int and the rest are strings you can't combine strings and ints. Hope this helps

  • Thank you Alex , seems we're from the same country :) I tried that but at the end I get the first salary of John and then when changing 30 to str(30) I am getting the previous salaty put together like 2030. – Alex Nov 25 '18 at 08:53
  • Oh. I misunderstood. If you want to add them then leave the 30 as an int and then try this int(salaries['John']) to print that you would str() the whole thing. Where are you from? – Alex Tănăsescu Nov 25 '18 at 08:57
  • Thank you Alex, Tobias made a little bit more clear for noobs like me ;))) it's my first time among this python and I feel like an idiot . – Alex Nov 25 '18 at 08:59
  • No worries. We all have to start somewhere. Just be sure to accept the answer you like as it can help other beginners learn too. – Alex Tănăsescu Nov 25 '18 at 09:00
1

This should fix it:

salaries['John'] = str(int(salaries['John']) + 30)

You need to convert the salaries of John to an int add 30 and then convert it back to a string.

This will change salaries['John'] from 20 to 50

Tobias Wilfert
  • 919
  • 3
  • 14
  • 26
0

The "+" operator is using for concatenate strings, adding numbers, etc. in your case you trying to add two integers but in your dictionary "salaries" the values are strings. you can convert the value to int, adding the numbers and then convert to string to store the value.

Try this:

salaries['John'] = str(int(salaries['John']) + 30)
print(salaries['John'])
Lior
  • 508
  • 3
  • 18