Why is the following code resulting in just True? Shouldn't the output be something like this:
True
False
because there's no else statement. So once it verifies and executes the if command, shouldn't it read thereturn False command as well? 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")
Related
i'm trying to update a default value in a combobox, after a function is called successfully, how could i do that?
my basic idea is this.
if xfunc return True : widget.set(updated_value)
return is a keyword that is used to return objects during runtime in a function, meaning if you write the word 'return' anywhere in the function (main or otherwise): the compiler will try to end the function with whatever follows as the return type. Therefore, when writing if statements: in your mind try to replace the function call 'xfunc()' with whatever you think it will return, and test to see if it is equal ('==') with the return you want ('True')
However, the job of a if-statement is to test if something is True. Therefore if xfunc() == True: would be redundant (as pointed out by all or None), so we can simplify this statement to if xfunc():
ex:
if xfunc():
#run success code here
I am very new to python and I have encountered the following code:
def function(array):
i = 0
j = 10
while i < j:
if array[i]!=array[j]
return False
i += 1
j -= 1
return True
I can't understand why the True value is not always assigned to the function no matter what happens in a while loop. The while loop just seems to check the if statement, and after finishing the loop, the True value should be assigned to the function anyway. But this code works as follows: the if statement checks for the condition and if it is true, we assign False to the function, if it is not true, we assign True to the function. But the assignment of True is not inside the while loop, so we should have assigned the True to function anyway, no matter what happens in while loop. I can't understand the logic here, can anyone enlighten me in this. Thanks a lot.
A return statement ends the execution of the function call and "returns" the result...
A return statement ends the function.
From https://www.python-course.eu/python3_functions.php
A return is used to hand the control of the program back to the calling function. So when you're in the while loop, and your condition in the if clause is evaluated to be true, your function terminates execution and the control of the program is handed back to the calling function. The only scenario in which your function will return true would be if the conditions in your if clause was never satisfied during the execution of your while loop.
Return exits the current function or method.
when you return False in if statement it will not continue the rest of the code and will always return false.
The condition is likely to have gotten executed before the rest of the loop has a chance to finish. When
if array[i]!=array[j]
is met, return False is called, exiting the loop and returning False.
This happens because
array[i]!=array[j]
is the condition that is met first, before the loop can finish and return with True.
Instead, you may want to 'skip' the part of the loop where this condition is met. If so, use the keyword
continue
This 'skips' the current iteration to the next one, and will continue on with your loop.
Code as follows:
while i < j:
if array[i]!=array[j]:
continue
I'm a beginner in Python, and I can't understand why we don't have to use else in cases like the one below:
def find_element(p,t):
i=0
while i<len(p):
if p[i]==t:
return i
i=i+1
return -1
In this code I thought I should use else return -1 if I wanted to return -1, but it seems that python understands this without else like in the code above.
Return terminates a function. Basically, if the "if" condition is satisfied within the "while" loop, the function will end. Alternatively, if the "while" loop is permitted to complete ("if" condition fails), then you force a return value. In this instance, you do not want an "else" statement if you expect to iterate through your entire "while" loop.
Well, in the exact case you provided, it's because you're "returning" after a match. Once a function returns, no code after the return is executed meaning if you ever pass the if conditional, the method breaks out of the loop and everything, making the else unnecessary.
Essentially: you don't need an else because if your conditional ever passes the code execution breaks out of method anyways.
You do not need else because you if the element t is found return i yields the index, otherwise you exit loop without encountering t, return -1 will be executed. But feel free to add else pass if it make you more comfortable.
As explained above, else: return -1, is an error, with such else clause the function will only the check the first element of the list being t
In Python the indentation decides the scope, so the return -1 is actually outside of the while loop. Your code will return -1 only if t is different from all p.
This is probably a total idiot mistake on my part, but I keep on getting the "SyntaxError: 'return' outside function" response when I try to run simple stuff like
if 5>7:
return True
else:
return False
I'm pretty sure my indentation is right, which is the only other answer I see for this issue, and it's happening with even ridiculously simple code. What am I missing?
I think you are mistaking print() with return. return is what will take the place of the function in an expression. So, let's say you have function returnOne()
If you had:
def returnOne():
return 1
print(5*returnOne())
that would print 5 because it would be multiplying 5 by the return value of returnOne.
If you are using return outside of a function, there is nothing to
replace with the return value. return can only be used in a function.
So let's take your code and inclose it in a function.
def greaterThan():
if 5>7:
return True
else:
return False
Then, we could use return, and we could see the result with print(greaterThan())
This is because you are calling a return outside of a function.
thy one of these instead:
#!/usr/bin/env python -w
import sys
def test_return():
return 5 > 7 # returns boolean
sys.exit(test_return())
I'm viewing the source code of a project now. In which I saw a function like this.
def func(x):
if condition_a:
return
if condition_b:
return
process_something
What does this return with nothing do here?
The "return with nothing" exits the function at that line and returns None. As Python's docs say:
If an expression list is present, it is evaluated, else None is substituted.
return leaves the current function call with the expression list (or None) as return value.
In flow control, I've seen it commonly used when some sort of condition is encountered that makes it impossible to execute the rest of the function; for example,
def getDataFromServer():
if serverNotResponding():
return
# do important stuff here which requires the server to be running