-2

I am trying to define a function which takes a string argument and yields 1 if the string is a, c, e or g and yields 0 if the string is b, d, f or h.

def ifodd_str(col):
    if col == 'a' or 'c' or 'e' or 'g':
        return 1
    elif col == 'b' or 'd' or 'f' or 'h':
        return 0

ifodd_str('a')

The problem is ifodd_str('b') returns 1. What is wrong with my if statements?

Marsroverr
  • 556
  • 1
  • 6
  • 23
Adi
  • 1
  • 2

1 Answers1

0

The problem with your code is you're not actually comparing col to the intended characters. You're checking the value of each character, which will always return true.

You have to compare equality for each individual case:

if col == 'a' or col == 'c' or col == 'e' or col == 'g':
    # do something

You can also use a list to test this:

if col in ['a', 'c', 'e', 'g']:
    # do something
Marsroverr
  • 556
  • 1
  • 6
  • 23