def foo():
if 1 > 0:
print('Works first condition!')
# This is a 'else' block which supposed not to be
# executed cause of the above 'if' condition is True, but
# despite the code executes both of them and return None!`
return print('Works second condition!')
print(foo())
Output:
Works first condition!
Works second condition!
None
Let's take a closer look at your code:
def foo():
if 1 > 0:
print('Works first condition!')
return print('Works second condition!')
print(foo())
In this code, you have defined a function foo(). The function contains an if statement:
if 1 > 0:
print('Works first condition!')
Since 1 > 0 is always True, the code inside the if block will be executed, and it will print 'Works first condition!'.
Next, you have a return statement with a print() function inside it:
return print('Works second condition!')
The print() function will print 'Works second condition!', and then the return statement will return the value of print(), which is None.
So, when you call the foo() function with print(foo())
, it will execute the function, print both messages, and then the return statement will return None, which is printed as well.
That's why you see the following output:
Works first condition!
Works second condition!
None
If you want to avoid printing None, you can remove the print() around the foo() function call like this:
foo()
This will only print:
Works first condition!
Works second condition!
Remember that in Python, every function implicitly returns None if there's no explicit return statement or if the return statement doesn't have a value.
So, in your case, the return print('Works second condition!') statement is equivalent to return None
.
In addition, this code is not using the else condition properly. The current code will always execute the if block because the condition 1 > 0 is always True. Consequently, the code inside the else block will never be reached.
If your intention was to use both the if and else blocks, they need to set a proper condition so that only one of the blocks will execute depending on the condition.
Here's an example of how the code could be modified to demonstrate the use of both blocks:
def foo(some_condition):
if some_condition:
print('Works first condition!')
else:
print('Works second condition!')
foo(some_condition=True)
foo(some_condition=False)
In this modified version, the function foo() takes a parameter some_condition. Depending on the value of some_condition, either the if block or the else block will execute. When calling the function with some_condition=True
, it will print 'Works first condition!', and with some_condition=False
, it will print 'Works second condition!'.