简体   繁体   中英

Simple If-Else concept of Python 3

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))

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM