0

Why is it that my code keeps returning yes in the code I've written?

def alphaToPhone(alpha):
    for i in range(len(alpha)):
        if i=="b" or "k" or "c":
            phone="yes"
        else:
            phone="no"
    return phone

print(alphaToPhone("23ht"))
Simon Bar
  • 116
  • 1
  • 6

4 Answers4

7

Because non-empty strings evaluate to True in Python. Solution for you problem could be one of the following

if i=="b" or i == "k" or i == "c":

or

if i in ["b", "k", "c"]:

Apart from that you are iterating over a wrong set of values. Replace your for with

for i in alpha:
mic4ael
  • 7,974
  • 3
  • 29
  • 42
3

You have missed the check

  def alphaToPhone(alpha):
        for i in alpha:
            if i == "b" or i == "k" or i == "c":
                phone="yes"
            else:
                phone="no"
        return phone

  print(alphaToPhone("23ht"))
Arun
  • 1,933
  • 2
  • 28
  • 46
2

Your condition i=="b" or "k" or "c" probably isn't what you wanted. It always returns true, because "k" (and "c" as well) is true. What you want is:

if i=="b" or i=="k" or i=="c":

or, better:

if i in {"b", "c", "k"}:
Błotosmętek
  • 12,717
  • 19
  • 29
1

You code should be like this:

def alphaToPhone(alpha):
    for ch in alpha:
        if ch == "b" or ch=="k" or ch=="c":
            phone="yes"
        else:
            phone="no"
    return phone

print(alphaToPhone("23ht"))
Nurjan
  • 5,889
  • 5
  • 34
  • 54