Code skips the loop even though the condition evaluates to true - python

I cannot get this portion of my program to enter the while loop. After plugging in values for poly, x_0, and epsilon, the program calculates a value for ans using the function evaluate_poly() which works correctly and in my specific instance gives the answer -13.2119. My epsilon value used is 0.0001. Since the abs(ans) is in fact greater than epsilon why is it skipping the loop?
I put a print ans statement right below the x_01 = 0 line to make sure it was calculating correctly before the while loop and also a print epsilon statement to make sure it was taking in my epsilon value correctly (which it does).
def compute_root(poly, x_0, epsilon):
"""uses newton's method to find a root of a polynomial function"""
ans = evaluate_poly(poly, x_0)
x_01 = 0
while abs(ans) > epsilon:
Dpoly = compute_deriv(poly)
Fprime = evaluate_poly(Dpoly, x_01)
return ans
x_01 = x_0 - (ans/Fprime)
print x_01
return x_01
print ans

You put two return statements inside your loop. When the first one is hit, the function exits instantly only. So, not only is the while loop being exited on the first loop, but the print statements are never being reached.

You have return ans inside your loop. So at that point the function will exit, and the print will never be reached.
If ans is really -13.2119 then it does enter the loop, it just doesn't perform everything in it because of the return.
Even if you remove the return ans line inside the loop, there is also return x_01 at its end. So in that case the loop will run at most once, which will make it the same as an if statement.

Related

How does this while-loop compute? (x = function(x))

I'm doing a quiz from "Automate the Boring Stuff with Python", and after tinkering with the problem for a bit, I finally found a solution that worked (with a little help from a comp-sci buddy of mine). The quiz asks me to make program that executes a Collatz-sequence.
I understand the logic behind all of the code, EXCEPT for the final line.
Here's my code with a few comments:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
guess = input("Your guess please ")
while guess != 1:
guess = collatz(int(guess))
The output of the program is a sequence of numbers, as the while-loop somehow re-iterates over the returned value of the function, and uses that for another computation.
My problem is with the last line. Here's how I understand it:
Once I enter the while-loop, my function "collatz" is called, using my input-value
The function is run, and my input is computed, and based on the input, I get either the even or odd calculation in return
Here's where my brain hurts!
Is the line "guess = collatz(...)" now constantly updating "guess" to be equal to the retuned value from the function? If this is the case, then I completely understand the flow. If it's not the case, then I don't understand how the returned value is constantly being used for new calculations.
Also, is this what is called "recursion"?
Short answer:
Yes.
Longer answer: (still short)
The collatz function is returning a value which is assigned to guess.
Also, this is not called recursion, recursion is a function which calls itself.
First, no, this is not a recursion. Recursion is a function that calls itself.
For instance this is a recursion:
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
As you can see here fibonacci function will call fibonacci function ... But it also has an exit condition (n == 0, and n == 1). Without that, this would cause runtime error with message that maximum recursion depth exceeded. But if I am not mistaken, you can check what is the maximum depth of recursion with following command:
import sys
print(sys.getrecursionlimit())
On my computer, this number is 1000. If this number is to small for you, you can also set it with this command:
sys.setrecursionlimit(n)
About other thing. Your function is returning some calculated value and in your main loop, this is assigned to variable guess. So everytime, that main loop will go through, value of guess will also update

What's happening when I indent 'return' incorrectly

This is the code that returns the value I expect:
python
def function1():
highest = 0
for x in range(100):
for y in range(100):
if x+y > highest:
highest = x+y
return highest
print(function1())
This code prints "198".
Now, if I indent the return statement under the if statement, like this:
def function1():
highest = 0
for x in range(100):
for y in range(100):
if x+y > highest:
highest = x+y
return highest
print(function1())
The code prints "1".
Why? What's happening behind the scenes?
Sorry if this is a trivial question, but don't know the basic structure and stuff, I'm only learning by experimenting...
it is terminated in the second step of the second loop.
highest = 0
x = 0
y = 0
if 0+0 > 0 (false):
increment y to 1:
the second run:
highest = 0
x = 0
y = 1
if 0+1 > 0 (true)
highest = 1
return # return command is called and therefore the execution of the function ends
A return statement ends the execution of the function call and "returns" the result.
The return statement stops a loop at the point when you call it. So in the first example it goes through the whole for loop and then returns the value of highest. In the second example it returns on the first entry of the for loop, so it doesn't go through the whole for loop.
A return statement ends the function. If you put it inside the if statement, the function stops as soon as the condition is true. So it will return the first value of x+y that's more than 0, which happens when x = 0 and y = 1, rather than continuing to look for higher values.
In the first example, the return statement is below both for loops, but is also indented outside of both of them. That means that it isn't reached until the nested for loop expression is evaluated for every possible combination of x and y.
On the other hand, in the second example, return is indented inside the if statement. Once the if statement is reached, the Python interpreter reads all lines indented at that level, including return highest. So the first time x+y > highest (which is when x+y==1, the if statement runs, and the function returns 1. The return acts as an early break, so even though there will be more values that it could process, it doesn't matter because you explicitly told it to return early.

Return inside if condition

def hi (n):
if n<=5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
1) In the above code i have declared a function hi() which takes an input n
2)I want to iterate inside the if condition until n is less than 5,totally execute the print statement 4 times
3)But it is not working after execution of one time inside the condition
4)I am thinking i have given return statement for if condition but the function is totally being exit
5)(i am thinking i am returning the n value to the if condition and it checks the condition and it will iterate ) if wrong correct me
Not sure exactly what you want to achieve, but based on the info you have provided:
def hi (n):
while (n < 5):
print("we are inside hi")
n -= 1
Briefly speaking, using return inside a function means to return the value that is followed or return None if there is no value. In addition, the execution of the function is terminated just after the return statement is executed.
You can use the return statement, but if you want to iterate it is not correct because your function will terminate its execution. Also remember that once you execute the iteration of the loop, there won't be more statements to execute inside your function which means an implicit return statement will be executed which returns None, and again function ends execution.
You need a loop for this. Try this instead
for _ in range(4):
print("we are inside hi")
Of course, you need a loop to make iteration. If you just want to print the statement 4 times, simply make a range of loop.
def hi ():
for n in range(4):
print(n+1," we are inside hi")
hi()
you can use this:
def hi (n):
while n <= 5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
you need a loop to iterate and return statement will exit from the function call.

Finding multiples using recursion

Given 1 to 100 numbers, for multiples of 3 it should print "he" ,for multiples of 5 it should print "llo" ,for both multiples of 3 and 5 it should print "hello".
This is what I have:
for i in range (1,100):
if(i%3==0):
print("he")
elif(i%5==0):
print("llo")
elif(i%3==0 and i%5==0):
print("hello")
How would I do this recursively?
How about the code below?
def find_multiples(current, last_num=100):
# Base Case
if current > last_num:
return
result = ""
if current % 3 == 0:
result += "he"
if current % 5 == 0:
result += "llo"
if result:
print(f"{current}: {result}")
find_multiples(current+1, last_num)
find_multiples(1)
Base case is if current reaches last_num or the maximum number you'd like to check.
Here is a general outline for doing simple recursive things in python:
BASE_CASE = 1 #TODO
def f(current_case):
if current_case == BASE_CASE:
return #TODO: program logic here
new_case = current_case - 2 #TODO: program logic here ("decrement" the current_case somehow)
#TODO: even more program logic here
return f(new_case) + 1 #TODO: program logic here
Of course, this doesn't handle all possible recursive programs. However, it fits your case, and many others. You would call f(100), 100 would be current_value, you check to see if you've gotten to the bottom yet, and if so, return the appropriate value up the call stack. If not, you create a new case, which, in your case, is the "decrement" logic normally handled by the "loop" construct. You then do things for the current case, and then call the function again on the new case. This repeated function calling is what makes it "recursive". If you don't have an "if then" at the beginning of the function to handle the base case, and somewhere in the function recall the function on a "smaller" value, you're probably going to have a bad time with recursion.
This recursive function prints multiples of a number! hope it helps
def multi(n,x):
if x == 12:
print(n*x)
else :
print(n*x,end =",")
multi(n,x+1)
print(multi(4,1));

how can i return something and break the loop same time in python

while True:
if abs(func_value) < epsilon:
return (x_0, itNum)
if abs(func_value) < epsilon:
break
else:
assert deriv_value != 0
x_0 = x_0 - (func_value / deriv_value)
itNum += 1
I do not want to write twice the condition. Is there another way to write this more appropriate?
i am so sorry guys,,
actually it continues with else statement that updates the func_value . i have just fixed
The return command immediately exits whatever function you're in, so if you're returning, there is no need to break out of a while loop. You've already broken out of it, along with that entire function.

Categories

Resources