Задача | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Задача

Решение нашел но случайно. hour = int(input()) day = int(input()) if day==6 or day==7and hour<10 or hour>21: print ("Closed") if ((hour>=10) and (hour<=21)) and (day>=1 and day<=5): print ("Open") Но я не понимаю ведь в первом условии if разве не должны выполнится условие до and и после and и только тогда программа выдаст True и напишите Close Если к примеру написать 22 часа и 4 день . Программа напишет что магазин закрыт хотя первое условие не выполнено day ==6 or day ==7, а второе выполнено хотя межу ними стоит and который обязует к выполнению двух условий . Объясните пожалуйста почему первое условие if выполняется и выводит Closed Если hour=22 day=4

5th Feb 2022, 11:51 AM
Al Dente
Al Dente - avatar
1 Answer
0
It can happen that our code is wrong, but by accident it does the right thing in some situations :) The answer is related to the operator precedence rules. "and" has higher precedence than "or" so it sticks to its two sides and evaluates sooner. Let's examine your condition: day==6 or day==7 and hour<10 or hour>21 Python interprets it this way: day==6 or (day==7 and hour<10) or hour>21 When we have day=4, hour=22: day==6 # False day==7 and hour<10 # False hour>21 # True So the result is: (False or False or True) # True More on logical operator precedence: https://stackoverflow.com/questions/16679272/priority-of-the-logical-statements-not-and-or-in-python
6th Feb 2022, 5:38 AM
Tibor Santa
Tibor Santa - avatar