Nicolas2020
Nicolas2020

Reputation: 11

What is wrong with my counter in my for loop?

I'm a newbie in Python but I don't understand why I'm getting an error at this line, thanks in advance!

    bands = ("Journey", "REO Speedwagon", "Styx",
"Mr. Mister", "The Cure", "The Doobie Brothers",
"Neil Diamond", "The Beatles")

bandRatings = {}

for band in bands:
  print("Please rate this band: " + band + " (1-10)")
  answer = input (": ")
  bandRatings.update({band: answer})

counter = 0
numRatings = 0

print("\nHere comes a summary of your ratings:\n")
for band, rating in bandRatings.items():
  print(band + ": " + str(rating))
  counter = counter + rating
  numRatings = numRatings + 1

print("\nYour average rating is:", numRatings)
If I do that, that works perfectly, but I uncomment the line, I get this error:

    File "main.py", line 19, in <module>
        counter = counter + rating
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

I don't understand why? Thanks! Have a good one!

Upvotes: 0

Views: 86

Answers (4)

shril
shril

Reputation: 152

The error you are getting is,

TypeError: unsupported operand type(s) for +: 'int' and 'str'

If you look closely in your code you will realize that you are trying to combine an int datatype with a string datatype which is not possible.

Hence, to make your code syntactically correct, you can change that line to,

counter = counter + int(rating)

Upvotes: 0

Sandy
Sandy

Reputation: 109

I guess the rating is string, not an int. Try:

counter = counter + int(rating) # (line commented)

Upvotes: 0

Ajay A
Ajay A

Reputation: 1053

Its simple, whatever you enter input it will be in the form of string, so you need to typecast your answer

answer = int(input (": "))

Upvotes: 0

ingvar
ingvar

Reputation: 4375

Your counter is a number, but rating is a string (input() returns string). You should convert it to int:

for band in bands:
  print("Please rate this band: " + band + " (1-10)")
  answer = input (": ")
  bandRatings.update({band: int(answer)})

Upvotes: 1

Related Questions