Recognizing and Avoiding Dead Code
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.
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.
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
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.
Hello, World! isn’t printed, so there’s no reason to have that code in this function at all.
This isn’t the same thing as when there are multiple
return statements in multiple paths of your function using
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.
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.