Chaining Function Calls Conditionally
00:00
In this lesson, you’ll learn how you can use and
to chain function calls, where the calling of one function depends on the success of a previous one.
00:10
What does that look like? Consider you have a sequence of related function calls. Each one depends on a previous one completing with the result True
.
00:20
In other words, you can’t call function two unless function one was true, you can’t call function three unless function two was true, and so on. You can chain them together connected by the word and
. Because of short-circuit evaluation, at any time when a function returns False
, that completes the evaluation of the ands.
00:42
Python knows the result is False
so none of the functions to the right of that function will be executed. This is similar to what you saw in a previous lesson. Here, the second part didn’t execute, which would’ve caused an error if the first part was False
.
01:00 But let’s look at an example specifically with function calls. File operations are ones that can cause program errors, so it’s a good example to look at. Suppose you want to rewrite an existing file.
01:13 There are certain conditions that need to be true for this to work. The file must first exist. Then you need to write the new contents to the file. Then you might want to read the file to verify the changes were made.
01:27
If any of those actions fail, then you don’t want to proceed to the next, because that will likely cause a program error. This slide shows the interactions using an if
statement.
01:40
The critical part is making sure the file exists before trying to do anything else to it. But this three-line if
statement can be condensed into a single-line and
expression.
01:54
Let’s indicate that we want to do some file operations … designate the filename … and create it. Let’s look to see that it’s empty. Now, chain the operations needed to rewrite the file together in a single statement using and
Make sure the file exists, and if it does,
02:44 and then examine its contents again.
02:49
Recall if either the first two calls return something false, the rest of the calls wont execute. But if they both return True
, then the result of the last operation is what the entire and
expression will compute to—the contents of the file, "Hello!"
.
Become a Member to join the conversation.