Does the following sample code end directly after the return statement?

def speak(message):
  return message

if happy():
  speak("I'm happy!")
elif sad():
  speak("I'm sad.")
  speak("I don't know what I'm feeling.")

The above code is from the exercise:
Cause I’m happy, pharrell!

Note that this code is the sample instructions. What I don’t understand is why you can issue a return statement and then continue with an if statement…
I am saying that I think there is an error here, but want to check if python is the code exception where you can have a return statement and then continue more commands in the function.


I wouldn’t worry too much about the structure of the example code, as in a lot of cases it’s there more as a reminder of how to structure things in Python rather than as a functional example. That code specifically won’t run, it’ll throw an error. (This is because the functions happy() and sad() are not defined.)

The function definition for speak() ends after the return statement. The if-else structure underneath is not part of the function, which you can tell by the indentation level. If it were part of the function, it would be indented to the same position as the return statement. :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.