Recognizing and Avoiding Dead Code
00:00
In this lesson, you’ll learn how to identify dead code in your functions. When a function reaches a return
statement, it immediately ends execution of that function and returns a value to the calling environment.
00:15
Any code that follows that return
statement is often referred to as dead code. The Python interpreter completely ignores this dead code when executing your functions.
00:26
This code is essentially useless, and having it in your programs is confusing. Here’s an example. We’re going to define a function called dead_code()
.
00:39
It’s going to return 42
and have a print statement, "Hello, World!"
But that print statement will not execute because the function will end when it hits the return 42
statement.
00:56
See? Hello, World!
isn’t printed, so there’s no reason to have that code in this function at all.
01:06
This isn’t the same thing as when there are multiple return
statements in multiple paths of your function using if
statements.
01:14
Recall our version of the absolute value function. Even though there was a second return
statement after a first one, the second one isn’t considered dead code because there is a path of execution which can arrive there.
01:30
The first one is inside this if
statement, so it won’t be executed if the condition is False
. So be careful to watch for what is and what isn’t dead code in your functions, and then always correct your functions so that they don’t have any dead code.
01:49 Next, we’ll see how to use multiple named objects to improve the use of your functions.
Become a Member to join the conversation.