Chaining Function Calls Conditionally
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.
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
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.
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,
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,
Become a Member to join the conversation.