0

I'm trying to solve a problem in my python book where you have to convert a string into a phone number. For example: a,b,c = 2 d,e,f = 3 ect. ect.

This is what I've come up with so far but it only ever prints 2, I've been fiddling with it for a while but it still only returns 2. Why?

    def thingie_thing (x) :
      for char in x:
          number = 0
          if char == 'a' or 'b' or 'c':
              number += 2
          elif char == 'd' or 'e' or 'f':
              number += 3
          elif char == 'g' or 'h' or 'i':
              number += 4
          elif char == 'j' or 'k' or 'l':
              number += 5
          elif char == 'm' or 'n' or 'o' or 'p':
              number += 6
          elif char == 'q' or 'r' or 's':
              number += 7
          elif char == 't' or 'u' or 'v':
              number += 8
          elif char == 'w' or 'x' or 'y' or 'z':
              number += 9
    print number
Ben Cravens
  • 163
  • 8

2 Answers2

1

If you write if char == 'a' or 'b' or 'c' that means:

if char == 'a'

if 'b':

if 'c':

Since 'b' and 'c' are non-zero characters, they are always true.

You have to see if char=='a' or char=='b' or char=='c'. Only then will you get the truth!

ProfOak
  • 541
  • 4
  • 10
0

Since you are using 'a' or 'b' or 'c' the first statement always evaluates to true as it means char == 'a' or 'b' or 'c'.Here 'b' and 'c' are evaluated as true hence it only adds + 2

Use instead char == 'a' or char =='b' or char == 'c'

or

char in ['a','b','c'] 
avinash pandey
  • 1,321
  • 2
  • 11
  • 15