Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Applying Booleans and Conditionals

00:00 As we continue discussing Booleans, you’ll look at some of their more complex uses. Short circuit evaluation, an optimization Python uses to stop evaluating Boolean expressions early.

00:10 Compound logical expressions, the combination or chaining of multiple Boolean expressions. And a quick look at conditional expressions, a way to return values based on a condition.

00:21 It’s also called the ternary operator because it has three operands, two expressions, and one condition. Here’s the syntax when used to assign a variable.

00:30 Variable equals expression one if condition else expression two. If condition is truthy, expression one is returned. Otherwise, expression two will be assigned to variable.

00:40 And as you saw at the end of the last lesson, when evaluating and and or, Python actually returns the operands themselves. It’s really only when the operands are Boolean that you should expect Booleans to be returned.

00:53 With that in mind, an updated version of the last table looks like this: and used in expressions, x and y returns y if x is truthy, and x if x is falsy; or used in x or y expressions returns x if x is truthy, and y.

01:10 If x is falsy. And because not applies negation, the expression not x will return Boolean True if x is falsy and False if x is truthy. Meet me in the REPL to dig into some more examples.

01:25 Let’s look at Boolean expressions again with this new understanding. 3 and 4. Now you know this returns 4 because both 3 and 4 are truthy.

01:35 So the right-hand operand is returned. 0 and 4 return 0 because 0 is falsy and the evaluation short circuits, ending there.

01:45 And if the left-hand side is truthy, while the right-hand side is falsy, 3 and 0, the right-hand side, in this case, 0 is returned.

01:54 Using or, 3 or 4 returns 3 because 3 is truthy, while 0 or 4 returns 4.

02:04 And with two falsy items, 0 or empty list, the right-hand side, the empty list is returned. With this short-circuiting behavior, Python only ever evaluates as much of the expression as it needs to to determine the overall truth value. Understanding this is key when thinking about compound logical expressions, expressions that involve multiple logical operators.

02:27 Consider this: 0 or False or 1 or 2. Because these are ors, 1. The first true value in the chain, is returned. But it might not be totally clear what’s happening.

02:40 To dive a little deeper, start by defining a function called f: def f(arg): print(f"f of arg = {arg}")

02:53 and then return arg.

02:56 So f takes an argument, uses string interpolation to print that argument so you can see, and then it uses that argument as the function’s return value.

03:04 When you call this function f(0), the print function runs showing you that it was called and it returns its argument. Now you can see what happens when you chain these function calls together with or operators: f(0) or f(False) or f(1) or f(2).

03:22 You see f(0) = 0, f(False) = False. f(1) = 1, and then 1 is returned. So not only does Python return the first true value, short circuiting saves time.

03:33 That last function call, f(2), didn’t even run. Using the and operator: f(1) and f(False) and f(2) and f(3), you see f(1) = 1 and f(False) = False, and False, the first falsy value, is returned, leaving the f(2) and f(3) calls ignored.

03:54 One great use of this is actually to create guards preventing potential errors. For example, say you’ve got a finance app and you want to calculate income versus expenses.

04:05 income = 10, expenses = 5. If income / expenses is greater than 1, you have a positive savings ratio.

04:12 Otherwise, you’re heading towards bankruptcy. Combining arithmetic and comparison operators, you can test this with income / expenses > 1 and the result is True.

04:24 That’s good news, but you have to be careful because if expenses were set to zero, expenses = 0

04:33 income / expenses > 1

04:36 triggers a ZeroDivisionError, not allowed. This is where you could use short circuiting to your advantage. Rewrite the conditions like so: expenses == 0 or income / expenses > 1.

04:53 True. So if you reduced expenses to zero, short circuiting will prevent the ZeroDivisionError otherwise, you’ll calculate the income to expense ratio and return True if it’s greater than 1.

05:04 An even simpler use of short circuiting is to set a default value. Create two variables: country and default_country. country can hold the string Canada and default_country can be the string United States.

05:18 And as a Canadian who fills out forms, this is a very common pattern. Anyway, if you need to provide a country, you can do the following: country or default_country.

05:30 Because country is not an empty string, its value is returned, Canada. Alternatively, country = ""

05:40 country or default_country now returns United States because country is falsy. And finally, in a similar vein, what if you wanted to provide an alternate value based on a condition instead?

05:53 This is where you would use the conditional expression. Set country back to Canada.

05:59 And let’s see what’s for lunch: lunch = "poutine" if country == "Canada" else "burgers",

06:10 examine lunch and it’s poutine. If country were set to anything else. for instance, United States, again, lunch = "poutine" if country == "Canada" else "burgers",

06:26 look at lunch and it’s burgers. But to be honest, I’d be happy having both. And those are the Boolean operators. Next lesson, we’ll get philosophical and discuss identity.

Become a Member to join the conversation.