user2756101
user2756101

Reputation: 57

Could somebody please help me with this code?

Could somebody please help me? I have written this python code but for some reason it does not correctly respond to my if and elif statements.

print ('Welkom')
print("\n")

naam = input('Typ alsjeblieft je naam en druk vervolgens op enter: ')
print("\n")

if naam == 'Tim' or 'tim':
    print ('Hoi Tim')
elif naam == 'Mitch' or 'mitch':
    print ('Hoi Mitch')
elif naam == 'Tom' or 'tom':
    print ('Hoi Tom')
else:
    print ('Hoi vreemdeling!')

It does not matter what i input (like mitch) it will always print 'Hoi Tim'. I tried the same code with numbers and expressions like input == 20. In those cases it does respond to my if statements. Could somebody explain to me what i am doing wrong?

Upvotes: 2

Views: 150

Answers (2)

TerryA
TerryA

Reputation: 59974

if naam == 'Tim' or 'tim' is interpreted as:

if (naam == 'Tim') or ('tim')

Which will always be True, because bool('tim') is True (a string that isn't empty is considered True). And so, you have something like False or True, which will return True (because one of the values is True).

If you wanted to compare the input to two strings, you have to do something like:

if naam == 'Tim' or naam ==  'tim':

Or:

if name in ('Tim', 'tim'):

However, for your example, you can use str.lower():

if naam.lower() == 'tim':

This is the same for your other ones:

elif naam.lower() == 'mitch':
    print('Hoi Mitch')
elif naam.lower() == 'tom':
    print('Hoi Tom')

Upvotes: 12

thefourtheye
thefourtheye

Reputation: 239443

If the values to be compared increase, you can do something like this

if naam in ('Tim', 'tim'):
    print ('Hoi Tim')
elif naam in ('Mitch', 'mitch'):
    print ('Hoi Mitch')
elif naam in ('Tom', 'tom'):
    print ('Hoi Tom')
else:
    print ('Hoi vreemdeling!')

Upvotes: 1

Related Questions