0

why is second output Hello Welcome. instead of Good Bye!! ?

https://code.sololearn.com/c0Y5ZyCendgQ/#py

26th Jun 2022, 7:52 AM
Khalif Baby👶
Khalif Baby👶 - avatar
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 .
26th Jun 2022, 8:11 AM
Abhay
Abhay - avatar
+ 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
26th Jun 2022, 1:20 PM
A͢J
A͢J - avatar
+ 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:
27th Jun 2022, 10:11 AM
Faisal
Faisal - avatar
+ 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.
26th Jun 2022, 8:15 AM
Dama Dhananjaya Daliman
Dama Dhananjaya Daliman - avatar
+ 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
26th Jun 2022, 11:03 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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
27th Jun 2022, 4:26 PM
Ben Rogers