vendredi 14 août 2020

Why can I not "exit" my nested if else statement (Python)?

I am trying to break out of an if statement within a function, but it is not behaving as I expect. I am following answers on this previous SO question, How to exit an if clause, specifically the top rated answer.

Here is the code:

import random

def logic_function():
    if 1 == 0:
        random_number = random.randint(10, 20)
        return random_number
    return

def number_function(foo):
    if foo == 1:
        number = logic_function()
        print(number)
    elif foo == 2: #request drone
        number = 2
        print(number)
    else:
        print('Nothing will happen')

print(number_function(1))

What I expect:

I have a function, number_function, where a number is inputted as a parameter. If the parameter is 1, then the generated number uses a function called logic_function to generate a random number between 10 and 20, if 1 == 0. 1 will not be equal to 0, so I expect the the return at the end of the logic_function to be called and I go into the outer if else statements within number_function, specifically the else statement at the end where Nothing Will Happen is printed.

Current output for print(number_function(1)) is:

None
None

I expect it to be:

Nothing Will Happen

I am also curious why that second None is being printed. Let me know if more clarification is needed.

Aucun commentaire:

Enregistrer un commentaire