+ 1

If conditions

Hy guys, I just wanted to ask why I can't use the If statement like this: if a == "Hello" or "Good morning" or ... : Instead of it I have to write: if a == "Hello" or a == "Good morning" or a == ... : Do u know any shorter ways to do the same?

23rd Nov 2018, 9:45 PM
Bobur Ochilov
Bobur Ochilov - avatar
11 odpowiedzi
+ 2
Wait, there is a way! What you can ask for (in Python at least) is this: if a in ('Hello', 'Good Morning'): ... Like this you ask if a's value is one of the elements of that tuple.
23rd Nov 2018, 10:50 PM
HonFu
HonFu - avatar
+ 2
Everything that evaluates as True is already a complete condition. 'Good Morning' (since it is no empty string) is True, so if you write like you said, it actually means this: if a=='Hello' or ('Good Morning' evaluates as True (which it does))... You see the issue? So you have to write a=='Good Morning', because that's what you want to check.
23rd Nov 2018, 10:22 PM
HonFu
HonFu - avatar
+ 2
No, not really - your interpreter needs it this dumb. ;'D If you wrote a==(b or c), it would again mean something different.
23rd Nov 2018, 10:32 PM
HonFu
HonFu - avatar
+ 1
Hi! I always asked the same question, thinking that somehow it'll be like maths, Bool's Algebra, it goes like this: if a == ("Hello" or "Good morning" or ...) But unfortunately, that doesn't work, so you can write them all in one line or just divide them into different elif statements.
23rd Nov 2018, 10:09 PM
Hamza Alalach
Hamza Alalach - avatar
+ 1
do u know any shorter variants?
23rd Nov 2018, 10:29 PM
Bobur Ochilov
Bobur Ochilov - avatar
+ 1
Ok, thank u guys!!
23rd Nov 2018, 10:50 PM
Bobur Ochilov
Bobur Ochilov - avatar
+ 1
woow!!!
23rd Nov 2018, 10:54 PM
Bobur Ochilov
Bobur Ochilov - avatar
+ 1
Thanks
23rd Nov 2018, 10:54 PM
Bobur Ochilov
Bobur Ochilov - avatar
0
Genius!
23rd Nov 2018, 10:54 PM
Bobur Ochilov
Bobur Ochilov - avatar
0
Array is the key
23rd Nov 2018, 10:54 PM
Bobur Ochilov
Bobur Ochilov - avatar
0
:) Anytime!
23rd Nov 2018, 10:59 PM
HonFu
HonFu - avatar