Billjk
Billjk

Reputation: 10686

Python TypeError

So I have the code:

intex = input("Enter in a letter of text\n")
if intex == 'a' or 'b' or 'c' or 'd' or 'e' or 'f' or 'g' or 'h' or 'j' or 'k' or 'l' or 'm' or 'n' or 'o' or 'p' or 'q' or 'r':
    counter += intex
    print(counter)

By the way, all the letters are defined, I just didn't think it was neccessary to put them in,(a = 1, b= 2, etc.) but whenever I run the code, it gives me the error TypeError: unsupported operand type(s) for +=: 'int' and 'str'

I know what this error means, that i cant add a letter to a number, but is there a way to do this without the error? i tried float(), but that gave me another error! please help!

Upvotes: 0

Views: 1934

Answers (2)

Uku Loskit
Uku Loskit

Reputation: 42030

if intex == 'a' or 'b' or 'c' 

should instead be intex == 'a' or intex == 'b' ...

An easier way to do this would be to use the in operator. I can only assume that you want something like this to store the values somewhere.

my_list = []
if ord(intex) >= ord("a") and ord(intex) <=ord("r"):
     my_list.append(ord(intex))

Could you specify what the code should do? It looks rather strange.

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 601351

The or operator does not work the way you think. The expression a or b returns a if it has a trucy truth value, and to b otherwise. You probably mean

if intex in "abcdefghijklmnopqr":
    ...

To translate the letter into an integer such that a maps to 1 etc, you can use ord():

counter += ord(intex) - ord("a") + 1

Upvotes: 7

Related Questions