You can combine logical operators in a conditional statement. Here's an example:
>>> color = 'white'
>>> age = 10
>>> if age <= 14 and (color == 'white' or color == 'green'):
... print(f'This milk is {age} days old and looks {color}')
... else:
... print(f'You should better not drink this {age} day old milk...')
...
This milk is 10 days old and looks white
This time around, you will run the code in the first half of the if
statement if the age is smaller than or equal to 14 and the color of the milk is white or green. The parentheses around the 2nd and 3rd expressions are very important because of precedence, which means how important a particular operator is. and
is more important than or
, so without the parentheses Python interprets the above code as if you had typed if (age <= 14 and color == 'white') or color == 'green':
. Not what you had intended! To prove this to yourself, change color
to 'green'
, age
to 100
, remove the parentheses from the if
statement, and run that code again.