0

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!

Niklas R
  • 16,299
  • 28
  • 108
  • 203
Billjk
  • 10,387
  • 23
  • 54
  • 73

2 Answers2

7

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
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
4
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.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • 1
    this gives me error ValueError: invalid literal for int() with base 10: 'a' – Billjk Feb 20 '12 at 20:02
  • sorry, dunno what I was thinking. what are you trying to do? your code does not make much sense. why are you adding the string to a counter? – Uku Loskit Feb 20 '12 at 20:03
  • i am converting letters to numbers – Billjk Feb 20 '12 at 20:03
  • 1
    The new version will error out if the user enters a string consisting of more than one character. I thought about all this before I wrote my answer -- this is why I did *not* use comparison operators, but `in`. – Sven Marnach Feb 20 '12 at 20:15
  • ok, sorry, the whole post has been a mess from the start. should not try to post on SO when i'm tired, made so many mistakes during so many edits. +1 to you. – Uku Loskit Feb 20 '12 at 20:17
  • @UkuLoskit: I've done much worse than this in some posts when I was tired. :) – Sven Marnach Feb 20 '12 at 20:22