Home > Blockchain >  Simple If-Else concept of Python 3
Simple If-Else concept of Python 3

Time:12-31

Why is the following code resulting in just True? Shouldn't the output be something like this:

True False

coz there's no else statement. So once it verifies and executes the if command, shouldn't it read th e command as well. Coz this command is not within the 'If' indentation and it's not even mentioned with else.

def is_even(number):
    if number % 2 == 0:
        return True
    return False
    
print(is_even(2))

CodePudding user response:

Executing 'return' terminates function execution immediately, with the specified value as the value of the function call.

It does not mean something like 'add this to what is to be returned at some future time, meanwhile carry on execution', which is what would be needed for your apparently understanding.

This is how 'return' works in most procedural languages.

CodePudding user response:

return statement is used to return a value to the caller and exit a function. A function will stop immediately and return a value if it meets with return statement. Also note that if statement does not requires else clause every time. It can stay alone to handle specific cases. As an example:

x = 44

if x>46:
    print("hello")
print("hi")
  • Related