Why statements after the while loop are not always executed? - python

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

Related

Simple If-Else concept of Python 3

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")

Why do we not need "else" in an if-statement if it contains "return"?

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 need assistance with a python assignment

the instructions are: write a simple python program that is controlled by a while loop. The sentry variable must evaluate to something other than true or false. There must be an indication of whether the loop is continued or if it is exited.
I am having trouble understanding the part that says "sentry variable must evaluate to something other than true or false". I thought that all while loops evaluate to true or false.
Are you looking for something like this? The code below evaluates if the variable "i" is equalled to 100 and if it isn't, re-iterate over the loop adding one to the counter. It indicates if it is currently in the loop or if the loop is broken.
i = 0
while i != 100:
i += 1
print("Continued.")
print("Exited.")
Try something like this:
myList = range(10)
while myList:
print myList.pop()
print myList
It the sentry variable, myList, is list and will allow the loop to continue executing until it is empty. Note that pop will remove the last element from the list at each iteration of the loop.

Why does this indentation work? python [duplicate]

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.

Python Boolean error?

Ok so I'm creating a loop:
def equ(par1,par2):
con1=4/par1
ready=False
add=False
if ready==True:
if add==True:
par2+=con1
add=False
print("true")
elif add==False:
par2-=con1
add=True
print("False")
elif ready==False:
par2=con1
ready=True
input()
return par2
Every time I run the program it doesn't do what it's supposed to. I notice that it will NOT change ready to true. Could any one give me some help? THANKS! :)
First, you have no looping construct. You only have a linear flow of logic.
Second, ready==True will never be true, since it is explicitly set to False before that code block is ever hit.
If you're intending to reuse the boolean value ready, then you'd either want to preserve its state somewhere outside of the scope of the method - once you leave the method, it goes right back through and sets it to False again.

Categories