0
why is second output Hello Welcome. instead of Good Bye!! ?
6 ответов
+ 2
in the following statement =>
if name == "Alex" or name == "John" and age >= 2:
------------------------------------
name == "John" and age >= 2 is false and name=="Alex" is true , so true or false is true .
+ 2
KB Is 🅿️
a or b and c is like
a or (b and c)
a and b or c is like
(a and b) or c
a and b or c and d is like
(a and b) or (c and d)
Now you can get your answer
+ 2
# Examples of Operator Precedence
# Precedence of '+' & '*'
expr = 10 + 20 * 30
print(expr)
# Precedence of 'or' & 'and'
name = "Alex"
age = 0
if (name == "Alex" or name == "John") and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
# Use parenthesis around Alex and john or write "Alex" and age>=2 or name == "John" and age >= 2:
+ 1
I think this is because the the precedence of "and" operator over the "or" operator, so the if statement evaluates the second half first,
"name == John and age >= 2", which evaluates to false.
then it evaluates the first half which is,
"name == Alex", and this evaluates to true.
Because those statements are joined by an "or" operator and one of them evaluates to true, the code that runs is the one in the if block.
Hope this helps.
+ 1
My opinion
That code line starts with:
if name == "alex" -> True
So the code won't bother examining the or condition, it has a True result, so will print the output associated to the if condition
+ 1
You need to separate the “or and the “and” operators, you can do this using using brackets.
if (name == “Alex" or name == "John") and age >= 2:
Should give you the correct output