Exit function based on the return parameter of an another function?

Viewed 91

I'm trying to understand the logic of this code below. Could someone please help me on below questions?

1) Does the for loop continues execution because of the return of check_cheese is False? As far as I know, either the outcome is True or False, a return command stops the execution of a function.

2) Does the if check_cheese(cheese) statement returns cheese variable only if the return parameter of check_cheese() function is True? I'm a bit confused here because there is no check like == or in or any other statement that indicates to return cheese only if the condition is True.

3) What would be the case if Gouda is not existent in the list? Is it going to be like every condition in the for loop returns False and at the end print statement you call yourself will be executed before termination?

Thanks in advance for any help you are able to provide.

def check_cheese(cheese):

    if cheese == "Gouda":
        print("ooh we have that one")
        return True
    print(f"we don't have any {cheese}")
    return False

def find_first_available_cheese():

    for cheese in ['Emmental','Gouda']:
        if check_cheese(cheese):
            return cheese
    print("and you call yourself a cheeseshop!")

find_first_available_cheese()
2 Answers
  1. A call to a return statement will always break the outer loop / function, even if it is return False. In your case, the if condition is preventing to call the return statement
  2. Your check_cheese function never returns a cheese variable, only booleans
  3. Why don't you try? ;)

1) Does the For loop continues execution because of the return of check_cheese is False? As far as I know, either the outcome is True or False, a return command stops the execution of a function

If you return inside of an if-statement, it will break from the function.

2) Does the "if check_cheese(cheese)" statement returns cheese variable only if the return parameter of check_cheese() function is True? I'm a bit confused here because there is no check like "==" or "in" or any other statement that indicates to return cheese only if the condition is True.

The for loop runs until it finds a Gauda cheese, as indicated in the check_cheese function.

3) What would be the case if Gouda is not existent in the list? Is it going to be like every condition in the for loop returns False and at the end print statement "you call yourself" will be executed before termination?

You'd get a printout "And you call yourself a cheese shop!". Try. :)

Related