0

I was making a short program just for fun that when my name is inputted, it will say 'hi programmer'. That worked but the other conditions with elif and else did not work, instead they only printed out the if condition. `a =input('What is your name')

a =input('What is your name')
if a == 'Hasan' or 'hasan':
    print('Hi programmer!')
elif a == 'Bob' or 'bob':
    print('Big fat boi')
else:
    print(a + ", i'm sorry to say this, but you suck!!!")

I was looking through StackOverflow but couldn't find the answer I was looking for. I also looked at other websites but they never seemed to really help. The output of my if statement should print out 'hi programmer!' and it does. However, When I checked my elif and else condition, it still outputted 'hi programmer' when the output for the elif condition should have been 'Big fat boi' and the output for the else statement should have been "(a), i'm sorry to say this but you suck!!!" I'm sorry if I haven't specified anything, this is my first question.

3 Answers3

1

The correct syntax for this example is:

a =input('What is your name')
if a == 'Hasan' or a == 'hasan':
    print('Hi programmer!')
elif a == 'Bob' or a == 'bob':
    print('Big fat boi')
else:
    print(a + ", i'm sorry to say this, but you suck!!!")

The way you written it at first is wrong. The statement:

a == 'Hasan' or 'hasan'

return True when a is equal to 'Hasan' and return 'hasan' in all other case. Basically, the first if branch is always used, because 'hasan' is evaluated to True by Python interpreter.

There is some resources on the Internet and StackOverflow to understand what happen in this case. For example, read answer for this question: Python boolean expression and or

Antwane
  • 18,008
  • 7
  • 43
  • 76
1

When you do

if a == 'Hasan' or 'hasan':

it checks:

if a == 'Hasan'

or

if 'hasan'

Since 'hasan' is not an empty string, it'll always return True. (See Truth value testing on Python docs for more objects with Boolean values.)

This leads to the code always returning True on your first if statement.

In order for your code to work as you intended, you want to check

if a == 'Hasan' or a =='hasan':

You could also check against the lowercase of your input like so

if a.lower() == 'hasan':
ooknosi
  • 374
  • 1
  • 2
  • 8
0

You need to change your if/elif/else statements :

if a == 'Hasan' or a == 'hasan':
    print('Hi programmer!')
elif a == 'Bob' or a == 'bob':
    print('Big fat boi')
else:
    print(a + ", i'm sorry to say this, but you suck!!!")

This is because if 'not_empty_string' : always evaluates to be true.

Jarvis
  • 8,331
  • 3
  • 26
  • 54