Python: Why else statement can be discarded in this simple expression? - python

I apologize for how obvious this answer must be, but I just can't seem to find out why an else statement isn't needed in the following function which returns True -
def boolean():
x = 1
if x == 1:
return True
return False
boolean()
My beginner coding mind is confused why False isn't being returned. The if statement returns True, then outside of that if statement, False is returned. I would've thought to write -
def boolean():
x = 1
if x == 1:
return True
else:
return False
boolean()
Why isn't the else statement needed here? Thank you very much for enlightening me on this.

The execution of a function always ends as soon as a return statement is run. Nothing past that point is even evaluated. For example, if you added a print statement immediately after the return statement, you would not see it printed in the console.
Similarly, the execution of this function never reaches return False because True was already returned.

Related

Return in the function is working incorrect

Hey Stackoverflow community,
I am a python newbie.
So, I am trying to build the function any() from scratch. However the output I get is not what I expected. My code is working fine without the second if statement:
def anys(lst):
for i in range(0,len(lst)):
if bool(lst[i])==True:
return True
anys([False,True,False]) executes True as expected.
However, when I am adding a second if statement I get a different outcome:
def anys(lst):
for i in range(0,len(lst)):
if bool(lst[i])==True:
return True
if bool(lst[i])==False or len(lst)==0:
return False
anys([False,True,False]) executes False.
Can anyone help me what I am doing wrong? Any help would be greatly appreciated.
When you are using a return statement, the function will stop executing and, as instructed, return to the place where the function was called from. This means that the function will return at the first elemt in the list since it was False. If you want the function to return false if all of the elemts are false, I would recomend that you put the return False statement after the for loop.
To clearify, the loop starts with the first elemnt in the list, which in this case is False. The element satisfies the condition:
if bool(lst[i])==False or len(lst)==0:
And the function will then return False.
To answer the comment, if you loop through the entire list, and none of the elements are true (in other words "any"), you then want to return false instead.
def anys(lst):
for i in range(0,len(lst)):
if bool(lst[i])==True:
return True
return False
The code now goes through the list, if it ever encounters a True value, it returns True, however if none of the elements are True, it instead returns False.
The basic answer is that with both conditional return statements, you were always returning on the first iteration and ignoring the rest of the values from the list (or other iterable).
But aside from that, a few other hints that could be useful:
You do not need to loop by index number - just loop over the elements in the list directly.
To test whether an expression (here x) would be True if converted into a boolean, all you need to do is if x:
In the correct form with a single conditional return in the loop, it was returning None if no true values were found and the end of the function was reached. But the builtin any returns False in that situation, so an explicit return False is needed if you want to emulate this behaviour.
def anys(lst):
for x in lst:
if x:
return True
return False
Let us execute your second any() function line by line.
First element of input argument is False.
When you check first if condition, if bool(False) == True, it fails.
It reaches to your second if condition.
if bool(False) == False or len(lst) == 0, bool(False) == False is true hence this if condition is executed and your method returns False.

isPalindrome recursion string

why does this not work?
It works for False palindrome; however, for anything True it never returns True..
I don't understand why this function does not return True?
And how I should improve this same answer so that it returns True.
My logic was that after the function completes iterating through the entire string, it will return True.
def isPalindrome(string, i = 0):
if i == len(string):
return True
if string[i] != string[len(string)-1-i]:
return False
isPalindrome(string,i+1)
Problem is with your last line:
isPalindrome(string,i+1)
That last line will eventually resolve to either True or False -- but how is that value being returned? (It isn't.)
Try:
return isPalindrome(string,i+1)
Check out the visualization here
My hint would be check what you are returning (i.e. what does isPalindrome return).
If you want just the answer, it is here

I am not able to fix a code issue in python

I am trying to define 2 functions, but only has_33 is working and myfunction is not working.
I am trying this code in jupyter notebook:
def myfunction(num):
for i in range(0, len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
and this code:
def has_33(nums):
for i in range(0, len(nums)-1):
if nums[i:i+2] == [3,3]:
return True
return False
myfunction([1,2,4,3,3]) should give true but it is giving false result but has_33([1,2,4,3,3]) is giving the true result. Why is this happening?
Hi there is indent difference in both code:
in first function second return is inside of for loop where as in second function it is out of for loop:
So in first function when if condition is false and it is going on second return and returning false for first value 0
In second function if evaluation keep false till i is 3 and for loop is not executing return. Once if evaluation become true on i=0 it is executing return of if and returning true so control goes out of function and second return out of for is not getting executed:
corrected first function:
def myfunction(num):
for i in range(0,len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
Indentation error! Just needed to erase a whitespace from the last line of your first code. The for loop will return False now. Try like this:
def myfunction(num):
for i in range(0,len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
Posting my comment as an answer as suggested by #quamrana.
This behavior is because of indentation. In myfunction, if the condition nums[0:2] == [3,3] is not satisfied, then the function immediately returns False. Whereas in has_33, it iterates through entire list and then only will return False if there are no consecutive [3,3].
e.g.
nums = [1,2,3,3,5]
myfunction(nums)
False
Let's go step by step in the function
for i in range(0,len(num)-1)
i is initialized to 0, i.e. i = 0.
nums[i:i+2]
Since i is 0, becomes nums[0:2] i.e. [nums[0], nums[1]].
if num[i:i+2] == [3,3]
Becomes if num[0:2] == [3,3]. Since nums[0] = 1 and nums[1] = 2, [nums[0], nums[1]] != [3,3]. Thus, if block will not be executed.
Since return False is in the for loop and if condition was not satisfied, the next line is executed, which is return False. The function execution stops here.
Now, second function:
nums = [1,2,3,3,5]
has_33(nums)
True
Step by step
Same as myfunction.
Same as myfunction.
Same as myfunction.
Now here is the catch. Since return False is written outside for loop, i increases by 1.
i = 1
nums[i:i+2] is nums[1:3] which is [nums[1], nums[2]].
The loop continues until you get a [3,3] OR i = len(nums) - 1.
Hope this helps you understand what went wrong.

A statement that has the same indentation with its previous "if" statement will always be executed?

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?
That's because you can't return twice from a function. When if is satisfied, it will return and won't execute any more statement. So, the next return statement is unreachable.
The next return will only execute when if is failed. else is also executed when if is failed.
That's why your teacher says, both of them are same.

Python does not allow multiple return() statements in ternary; possible alternative that is also aesthetically pleasing?

I am developing a text based RPG (graphics will be implemented later) and I am writing a method to determine whether a room a player is trying to go to exists or not. In this method I have multiple logic statements that determine what room the player is trying to get to based on the direction they enter and whether that "room" == 0 (my place holder for an empty space in the world/dungeon array). Although I can write a conventional logic statement for this:
if condition:
if otherCondition:
return(True)
else:
return(False)
a ternary is much more aestheticaly pleasing:
if condition:
return(True) if otherCondition else return(False)
But of course, that does not work. I am looking for something that functions as the conventional logic statement but is also "pleasing to the eye", like a ternary. In my code the logic statement is repeated four times, and the conventional logic statement would be displeasing to read.
I am using Python 3.5.1 on Windows 7.
The issue with your statement isn't the ternary part, it's the repeated return. Instead use:
if condition:
return True if otherCondition else False
Here, the result of the expression True if otherCondition else False is returned.
This could be written more concisely as:
if condition:
return bool(otherCondition)
Use just a single return with ternary statement:
return 'something' if someCondition else 'something else'
For you case is enough just :
if condition:
return otherCondition
# or if "otherCondition is not bool you can use: return bool(condition)
z = x if success else y
# this tallies z = success ? x : y, where success is a bool. Either True or False
Here the expression on the right returns x or y depending on if success evaluates to True or False respectively. As this is an expression it can be used with a return statement
return x if success else y
if condition:
return othercondition
Perhaps you should illustrate with an example, because it can be simplified to return the result of the other condition.
if condition:
return otherCondition
What ever happened to just:
if condition:
# tis very simple; if room is equal to 0, the operation is true, thus `True` will be returned
# otherwise `False`.. no mystery
return room == 0

Categories