This question already has answers here:
Else clause on Python while statement
(13 answers)
Closed 7 months ago.
here is my code:
def is_prime(x):
if x < 2:
return False
else:
for i in range(2,x):
if x % i == 0:
return False
else:
return True
print is_prime(508)
I don't understand why the last else: return true works with the indentation. If I type
else:
for i in range(2,x):
if x % i == 0:
return False
else:
return True
Then def is_prime(2) returns none? why?
Because in python, a for-loop can have an else-clause.
This clause is executed if the loop exits normally. If the loop is exited by using the break statement, the else is not entered.
I suggest you read up the official doc and if it's still unclear, this blog summarizes the concept fairly well.
for and while loops also know else clauses, not just if or try statements.
The else clause of a loop is executed when control leaves the loop, unless you have used break to abort the loop.
I must admit that this behavior puzzled me at first, as well, but it's actually quite sensible, and a useful feature (see this answer for a good example).
In the second example, the else is on the same indentation level as the if, so they both belong together. So for the first item in the loop, you will either return False or True depending on that value; i.e. the loop won’t continue.
Now in your original code, the else is on the same level as the for. So it’s a for..else which is actually a special construct:
When the items are exhausted, the suite in the else clause, if present, is executed, and the loop terminates.
So basically, the else block is executed, if the loop naturally finishes (without calling break). So in your case, it’s the same as leaving the else out:
for i in range(2,x):
if x % i == 0:
return False
return True
As others have said, a for loop can have an else clause. Read more in the docs
When used with a loop, the else clause has more in common with
the else clause of a try statement than it does that of if statements:
a try statement’s else clause runs when no exception occurs, and a
loop’s else clause runs when no break occurs.
Related
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")
No matter what it always outputs Spammer().
option = int(input("Enter the what you want to do: "))
<insert code not relevant>
if option == 1 or 'spam'.upper():
Spammer()
elif option == 1:
pcInfo()
Python 3.9.7
I've looked through several posts and nothing has worked.
edit: The typo was made while typing the code into StackOverflow. To fix the if statement I wrote it again but without ctrl-c and ctrl-v and it somehow worked.
'spam'.upper()
will always return
SPAM
which is a non-empty string and therefore is regarded as a truthy statement by Python.
Since an if statement checks for truthy expressions, the if block will always be triggered.
If you need more help, please specify what you actually intend to with that statement.
Also: The else if block contains the same condition as the if block which I suppose is a typo? Otherwise if would always catch that case first and then skip over else if in all cases. So you should definitely use another value of the else if statement.
As 'spam'.upper() will return 'SPAM',
which will always give True.
also, the pcInfo() will never execute,
as it has the same condition (option == 1) as the one above.
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.
I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.
Consider the following:
if condition:
do_something()
else:
do_something_else()
Here, do_something_else() is only executed if condition is false, as expected.
Similarly, in
try:
do_something()
except someException:
pass:
else:
do_something_else()
finally:
cleanup()
do_something_else() is only executed if no exception occurred.
But in for or while loops, an else clause is always executed, whether the contents of the for/while block have been executed or not.
for i in some_iterator:
print(i)
else:
print("Iterator is empty!")
will always print "Iterator is empty!", whether I say some_iterator = [] or some_iterator = [1,2,3]. Same behavior in while-else clauses. It seems to me that else behaves more like finally in these cases. What am I overlooking?
The for else construct executes the else clause if no break statement was executed for the loop, as described here For example, this else clause is never evaluated
for i in range(1,10):
if i % 5 == 0:
print i
break
else:
print "nothing divisible by 5"
Well, it depends how you see it. You can look at the elses like this (excuse the screaming, its the only way to make emphasis in code):
if condition:
do_something()
IF THE PREVIOUS CONDITION WAS FALSE:
do_something_else()
Now, there is an obvious similarity between if/else and try/except/else, if you see the else statement as an else to the except statement. Like this.
try:
do_something()
IF THERE WAS AN EXCEPTION:
pass:
IF THE PREVIOUS CONDITION WAS FALSE:
do_something_else()
finally:
cleanup()
Same goes for the else/for:
IF some_iterator IS NOT EMPTY:
i = next(some_iterator)
print(i)
IF THE PREVIOUS CONDITION WAS FALSE:
print("Iterator is empty!")
So here we see that the else in some fundamental way do work exactly the same in all three cases.
But you can also see the else in this way:
try:
do_something()
except someException:
pass:
IF NO EXCEPTION:
do_something_else()
finally:
cleanup()
And then it's not the same anymore, but the else because a sort of "if nothing else". You can see for/else in the same way:
for i in some_iterator:
print(i)
IF NO MORE ITERATING:
print("Iterator is empty!")
But then again, considering the elif, then this way of seeing it works for if/else as well:
if condition:
do_something()
elif otherconditaion:
do_anotherthing()
IF NO CONDITION WAS TRUE:
do_something_else()
Which way you want to look at the else is up to you, but in both ways of viewing, else do have similarities in all three cases.
Yes, as Eli mentioned, the else clause is executed only if you don't break. It stops you from implementing code like this:
for i in range(1,10):
if i % 5 == 0:
print i
break
if i % 5 != 0:
print "nothing divisible by 5"
Which is roughly equivalent here, but handy if the conditions for quitting are a bit more complicated (like checking various possible conditions or combinations of conditions).