Skip to content

Instantly share code, notes, and snippets.

@martin-martin
Created August 27, 2020 10:45
Show Gist options
  • Save martin-martin/5a4e0fd4370c9f8fef88845cb6dda409 to your computer and use it in GitHub Desktop.
Save martin-martin/5a4e0fd4370c9f8fef88845cb6dda409 to your computer and use it in GitHub Desktop.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment