What if we used print instead of return for each if statement?


#1

Question

In the context of this exercise, if we had a similar function with multiple if statements, and used print instead of return for each one, what would happen?

Answer

In most of the exercises within this lesson, each if statement contains a return statement. A return statement immediately exits a function when it runs, so even with multiple if statements with True conditions, when one of them runs their code block, none of the other statements would run.

If instead, we used print functions in each if statement without using return, this can change how the code would behave. If you had multiple if statements with conditions evaluating to True, then each one would run their code block, because a print does not exit the function.

Example

# Using return statements
def evaluate(score):
  if score >= 9:
    return "Excellent"
  if score >= 5:
    return "Good"
  if score >= 1:
    return "Bad"

# returns "Excellent"
evaluate(10) 

# Using print statements
def evaluate(score):
  if score >= 9:
    print("Excellent")
  if score >= 5:
    print("Good")
  if score >= 1:
    print("Bad")

evaluate(10) 
# prints out in the console
# Excellent
# Good
# Bad