Operators Precendence
Python has priorities in which order the operations are performed. You must use parentheses to change the order of calculations.
However, if you do not use parentheses, the priorities in the operators are as follows:
The precedence among logical operators:
Let's clarify this with example:
In the code above, you can see that the expressions only differ because of the parentheses, leading to completely different outcomes. Let's break it down:
first_result
is showing thatand
has higher precedence thanor
, resulting in True;second_result
uses parentheses to forceTrue or False
to evaluate first, then appliesand False
, resulting in False;third_result
shows thatnot
has the highest precedence, making the expression equivalent to (not True) or False, resulting in False.
Tarea
Create a program that checks whether a given year is a leap year. A leap year is divisible by 4 but not divisible by 100, except if it's also divisible by 400. The program should output either 'Leap year' or 'Not a leap year' accordingly.
- The main condition of the leap year is that year must be divided by 4. Use
year % 4 == 0
; - The second condition is that the year must not be divided by 100. Use
year % 100 != 0
; - But if the year is divisible by 400 is the leap year. Use
year % 400 == 0
.
¿Todo estuvo claro?
Contenido del Curso
Conditional Statements in Python
3. Python if-elif-else Statement
4. Python Ternary Operator
Conditional Statements in Python
Operators Precendence
Python has priorities in which order the operations are performed. You must use parentheses to change the order of calculations.
However, if you do not use parentheses, the priorities in the operators are as follows:
The precedence among logical operators:
Let's clarify this with example:
In the code above, you can see that the expressions only differ because of the parentheses, leading to completely different outcomes. Let's break it down:
first_result
is showing thatand
has higher precedence thanor
, resulting in True;second_result
uses parentheses to forceTrue or False
to evaluate first, then appliesand False
, resulting in False;third_result
shows thatnot
has the highest precedence, making the expression equivalent to (not True) or False, resulting in False.
Tarea
Create a program that checks whether a given year is a leap year. A leap year is divisible by 4 but not divisible by 100, except if it's also divisible by 400. The program should output either 'Leap year' or 'Not a leap year' accordingly.
- The main condition of the leap year is that year must be divided by 4. Use
year % 4 == 0
; - The second condition is that the year must not be divided by 100. Use
year % 100 != 0
; - But if the year is divisible by 400 is the leap year. Use
year % 400 == 0
.
¿Todo estuvo claro?