I'm attending an online course on Python.
if <TestExpression>:
<block>
i=21
Regarding the above code ("code1"), the lecturer said that i=21 will execute, whether or not the test expression is true, because i=21 has the same indentation with the if statement, meaning i=21 is not part of the if statement.
However, the lecturer also said the following code ("code2"):
def bigger(a,b):
if a>b:
return a
return b
is the same as the following code ("code3"):
def bigger(a,b):
if a>b:
return a
else:
return b
Doesn't this contradict what he previously said? i=21 in code1 and return b in code2 both have the same indentation with their previous if statements, but why i=21 will always execute no matter the test expression is true or false, while return b will execute only when the test expression (a>b) is false?
How do you decide whether the statement immediately following the if construct which has the same indentation with the if line should execute? In another word, how do you decide whether that statement is part of the if construct?
This is a great question you have asked, and it's an issue a lot of new people have with functions specifically.
The issue lies with the return keyword. In a function, when it returns a value, the function immediately breaks. Thus, no subsequent code in the function is run. Because of this, we can short-hand our conditional statements to:
if a > b:
return a
# Function breaks here - no more code is executed.
# This bit is never reached if a is returned
return b
Observe:
def test():
if 10 > 5:
print("Hello!")
return True
print("Hi!")
return False
When we call test(), only Hello! is printed.
One reason this is helpful is to stop erroneous whitespace when having multiple conditional statements in Python. Of course, in most other programming languages, since whitespace isn't a feature, it's not as necessary.
Imagine you were writing a function to check if a number was prime, where lots of conditional statements were required. (Of course, for the sake of this example, this isn't efficient):
def is_prime(n):
if n == 1:
return False
else:
if n == 2:
return True
else:
for i in range(2, n):
if n % i == 0:
return False # A factor exists
else:
continue
return True
Knowing that a return breaks the function, we can re-write this as:
def is_prime(n):
if n == 1:
return False
if n == 2:
return True:
for i in range(2, n):
if n % i == 0:
return False # A factor exists
return True
See how the indentation is so much cleaner?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With