I wrote a function to calculate the square root, though the function must operate with the while loop at the top.
Additionally, if I type in an input value which has no square root, the function goes into infinite loop.
def square(x):
return x * x
def qrt(n):
i = 100
while True:
if square(i) != n:
i -= 1
else:
return i
If you use while(i>0): instead of while True: the loop will end after i reaches 0. However, I would suggest to use math.sqrt() from pythons builtin math module. That would look like this:
import math
math.sqrt(n)
def fact(n):
if n==1:
return
else:
return (n * fact(n-1))
d=int(input("Enter the number"))
print(fact(d))
I am trying to learn recursive functions in python but I am getting an error in the above code
In the case of n==1, you have a bare return, which means you're implicitly returning None. From there on, errors ensue. Instead, you should explicitly return 1:
def fact(n):
if n==1:
return 1 # Here
else:
return (n * fact(n-1))
Side note:
Mathematically speaking, you should probably return 1 for n==0, not n==1. See https://en.wikipedia.org/wiki/Factorial#Factorial_of_zero for details.
So I'm making a simple program that gets 2 functions(a and k) and one integer value(b), then it gets the formal parameter in the two functions(a and k) which is "x" and applies a condition x < b then based on the condition makes a function call, either a or b. But when I run the program it gives an error that x is not defined in the global frame. I want it to get "x" from the formal parameter assigned to the functions a and b and then get the condition based on that.
Here's my code
def square(x):
return x * x
def increment(x):
return x + 1
def piecewise(a, k, b):
if x<b:
return a
else:
return k
mak = piecewise(increment,square ,3 )
print(mak(1))
I guess you want to do something like this:
def piecewise(a, k, b):
def f(x):
if x < b:
return a(x)
else:
return k(x)
return f
However, I am not sure if it is a good practice. So, I leave my answer here to see the comments and learn if there is any problem with it.
My problem is that I want:
and then I want it to get evaluted in the calc_energy function 360 times
and then store the result so I could count the year average, I want to calculate the energy average..
Should I call the function instead of return in def_decide(v)???
Could someone help me get in on the right track?
def calc_v(latitud):
for t in range(0,360):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitud)/90
decide_v(v):
def decide_v(v):
if 0<v<1:
return(v**2)
if v>=1:
return(1)
if v<=0:
return(0)
def calc_energy(v):
W=self.area*random(0,1)*self.sundigit*v
return W
def sort(self,W):
W+=100/360
You can make a generator from calc_v and then use it as you would use a list of values (notice yield instead of return):
def calc_v(latitude):
for t in range(0,360):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitude)/90
yield v
def decide_v(v):
if 0<v<1:
return v**2
elif v>=1:
return 1
else:
return 0
for v in calc_v(latitude):
print decide_v(v)
You can use recursion which is a function calling itself. Below you can see the function factorial is called within itself. http://www.python-course.eu/recursive_functions.php
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
I get the feeling that you don't really want to know how to loop a function. I think you just want to call your function in the example that you gave.
def calc_v(latitud):
for t in range(0,366):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitud)/90
decide_v(v) # return v
def decide_v(v):
if 0<v<1:
print(v**2)
if v>=1:
print(1)
if v<=0:
print(0)
When you use the return statement in a function then you will leave the loop and the function, so your for loop will only run through t=0 then it will break out of the function. I think you just want to call your function and give it the variable v.
I'm a beginner to CS, and I've been trying to work through a Python book (Think Python) on my own.
I'm currently on recursion, but I'm a bit stuck.
The exercise asks for me to write a function called do_n that takes a function object and a number, n, as arguments, and that calls the given function n times.
This is my code:
def countdown(n):
if n<= 0:
print 'Blastoff'
return
else:
print n
countdown(n-1)
def do_n(f(n), x):
if x<=0:
return
else:
f(n)
do_n(f, x-1)
do_n(countdown(3), 3)
When I do this, there's an error because of invalid syntax in def do_n(f(n), x). If I change it to:
def do_n(f, x):
if x<=0:
return
else:
f(n)
do_n(f, x-1)
There is an error because n is not defined in the else statement.
How can I make this work?
You are almost there with your second example. It takes a function f and a max count x. n doesn't exist because you haven't written the loop to generate values for n yet. Turns out python has a builtin for that
def do_n(f, x):
for n in range(x):
f(n)
Now do_n takes a function object f and a count x, then calls the function count times. Notice the difference between f (the function object) and f(n) (the result of calling f with the value n). When you want to call do_n, you do it like this:
do_n(countdown, 3)
Not like
do_n(countdown(3), 3) # badness
That last one calls countdown and then calls do_n with its result.
def print_n(s,n):
if n<=0:
return
else:
print(s)
print_n(s,n-1)
def do_n(f,s,n,x):
if x<=0:
return
else:
f(s,n)
do_n(f,s,n,x-1)
do_n(print_n,'Hello',2,2)
It's a tricky one.
Basically, the solution is:
def do_n(f, n):
if n <= 0:
return
f(n)
do_n(f, n-1)
However, if you actually try combining it with print_n then all hell breaks loose.
First of all, we have to add one more argument, s, to the above code to be able to pass any string that we want to print out n times.
Second of all, the above do_n should be able to repeat any passed function n times so long as the function doesn't mess with do_n. Unfortunately, this is exactly what happens here.
The assignment from the book seems clear: "...write a function called do_n that takes a function object and a number, n, as arguments, and that calls the given function n times..." or in other words do_n calls any function passed to it n times. You'd think if we pass s = 'Hello' and n = 3 then do_n(f, s, n) should output 'Hello' 9 times... because print_n('Hello', 3) prints 'Hello' 3 times and do_n(print_n, 'Hello', 3) is supposed to triple that result... gotcha.
What actually happens is in the first instance of recursion do_n does indeed print out 'Hello' 3 times, because print_n says so. But in the next instance do_n prints out 'Hello' only two times, because it has subtracted 3-1 in the previous instance and now print_n('Hello', 2). In the last instance do_n prints 'Hello' only once, for the same reason. So the total amount of 'Hello' output is 6.
Finally, if you use FOR LOOP instead of recursion to define do_n, you will actually get the correct result of 9 outputs:
def print_n(s, n):
if n <= 0:
return
print(s)
print_n(s, n-1)
def do_n(f, s, n):
for i in range(n):
f(s, n)
do_n(print_n, 'Hello', 3)
P.S.
On Page 52 of Think Python 2E we are encouraged to use recursion over for loop:
"For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early."
However, in this particular exercise, using recursion forces an output which clashes with the assignment, seeing that do_n and print_n are at odds with each other because constructing do_n with the help of recursion wrongly reduces n in each instance.
Did I get it right?
thinkpython2e
recursion