Python basics – Common errors pt1

Can you guess what is wrong with this line of python code?

item='cabbage'
if item == 'banana' or item == 'apple' or 'kiwi':
    print("It is a fruit")
else:
    print (f"{item} is not a fruit!")

Try to run it yourself!

Spoiler alert – cabbage is not a fruit, but python interpreter will tell you otherwise. Why?

Be careful with OR and IF statements! Syntax above will ALWAYS return TRUE, no matter the variable it is checking! Why? Because of that pesky kiwi! We are not checking it against the variable “item”, so python will always return true – only the empty string is considered false!

Correct approach would be:

item='cabbage'
if item in ("banana", "apple", "kiwi"):
    print("It is a fruit")
else:
    print (f"{item} is not a fruit!")

Or even better, move the list you are comparing it against outside the if statement

# create a set
all_fruits = {"banana", "apple", "kiwi"}
if item in all_fruits:
    print("It is a fruit")
else:
    print (f"{item} is not a fruit!")
Scroll to Top