Python: don't understand difference - python

I am really sorry about my python understanding and about my English.
I just started to learn Python and really dont understand difference between two next code:
def arrayCheck(nums):
"""
find nums
"""
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
result = arrayCheck([1, 1, 2, 3, 1])
print(result)
When run this code the result is True
And the next one:
def arrayCheck(nums):
"""
find nums
"""
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
else:
return False
result = arrayCheck([1, 1, 2, 3, 1])
print(result)
The second code return False.
Why?
Thanks in advance.

The first code can return only True or None. After the return statement the function ends so the first code never reach the return False statement.
The second code will return False if the first 3 items are not 1, 2 and 3 since if the condition does not hold it returns False.
I would actually assume this is the code you are interested in -
def arrayCheck(nums):
"""
find nums
"""
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
See Python control flow here.

In the first code, if condition has no else part. While in the 2nd code, if condition has a else part.
So when if condition is false in the first code, it is going for second iteration and if condition getting True as per the input and it is returning True.
But in the second code, if condition is false and it is going to else part and returning False.

In python the indentation matters, and return will break out the function so, in the first codeblock you have
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
The two return are on the same indent level so if the condition is met It will go to first line, return True,
see return and break out of the function ignoring everything afterwards
but in the second codeblock
you have
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
else:
return False
so if the condition is true it will return true and break out of the function
but if the condition is not true it will return false and break out of the function so it only does one of the iterations you are trying to do.
If I understand what you are trying to do correctly, this would be the solution :
def arrayCheck(nums):
"""
find nums
"""
found = False
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
found = True
return found
result = arrayCheck([1, 1, 2, 3, 1])
print(result)
This works because it allows the function to check over every iteration in the for loop and it will return true if the numbers were found

In first code return False will never execute because it is inside the if condition and before it another return statement return True. After returning the function execution will stop.
In the second code if condition fails for the first time the function execution will stop because of return False in else condition.

Related

Why Does My While Loop Inside Function Keep Returning True?

I am trying to learn while loops.
To practice, I created a simple while loop with an If statement inside a function to check and see if a word is a palindrome. For some reason, even if the word is not a palindrome, it keeps returning True.
I expected the output of the print function on the last line to be False:
from collections import deque
word = "tacrocat"
def check_palindrome(word):
d = deque(word)
while len(d) > 1:
if d.pop() == d.popleft():
return True
return False
print(check_palindrome(word))
NOTE: When I change the if statement evaluation to "!=", change the return statement inside the if statement to False, and change the return statement in the while loop to True, it seems to accurately detect palindromes - but I have no idea why.
If the program is written like this:
from collections import deque
word = "tacrocat"
def check_palindrome(word):
d = deque(word)
while len(d) > 1:
if d.pop() == d.popleft():
return True
return False
print(check_palindrome(word))
At iteration-1:
Since both the first character('t') and last character('t') in the deque are equal it will enter the if condition and return True. When a return statement is executed in a function, then the control comes out of the function. In other words, as soon as return True statement is executed, the control comes back to print statement without executing remaining iterations of while loop and since we returned True, so True will be printed as output.
Let's analyze second program:
from collections import deque
word = "tacrocat"
def check_palindrome(word):
d = deque(word)
while len(d) > 1:
if d.pop() != d.popleft():
return False
return True
print(check_palindrome(word))
At iteration-1:
Current deque: [t,a,c,r,o,c,a,t]
We are popping both first element and last element and checking whether they are not equal in if condition. Since 't' and 't' are equal, if condition will not execute and while loop will continue.
At iteration-2:
Current deque: [a,c,r,o,c,a]
Since 'a' and 'a' are equal, if condition will not execute and while loop will continue. Both first and last elements are popped (pop and popleft)
At iteration-3:
Current deque: [c,r,o,c]
Since 'c' and 'c' are equal, if condition will not execute and while loop will continue. Both first and last elements are popped (pop and popleft)
At iteration-4:
Current deque: [r,o]
Since 'r' and 'o' are not equal, if condition will execute and return False statement is executed. So, the function check_palindrome will terminate with return value as False and so we get output as False.
The second program is correct because to check if a word is palindrome or not, we need to check all letters whether they are satisfying the condition or not. Just checking only the first and last character of a word and if they are equal, then it doesn't mean the remaining letters are same. We need to check them too.
Once it finds a return True it will come out of the function.
In the first iteration it will compare t with t and exit the function.
In your case it comes out at first letter.
rather you can do as stated by #Goodies in comment
from collections import deque
word = "tacrocat"
def check_palindrome(word):
d = deque(word)
while len(d) > 1:
if d.pop() != d.popleft():
return False
return True
print(check_palindrome(word))
This is happening because it is returning True if any one of the characters on either side of centre are equal. This is probably confusing but basically it checks if any of the letters are mirrored not all of them because the return True exits early.
This means that, actually, your function does not always return True, for example a word like "word" would return false.
To fix this, rather than return True when one match is found and otherwise return False, you could return False if any do not match and else return True like so (see comment above by #Goodies):
from collections import deque
word = "tacrocat"
def check_palindrome(word):
d = deque(word)
while len(d) > 1:
if d.pop() != d.popleft():
return False
return True
print(check_palindrome(word))
which (correctly) outputs:
False

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.

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

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.

Categories