Calling a function n times with two parameters - python

This is my first time around, so i would appreciate your patience with what might appear as a lame looking question :)
I'm trying to write a function called do_n that takes a function object and a number, n, as arguments and then call the given function n times. Here's the code:
def name():
print 'Jack'
def do_n(fo, x):
if x <= 0:
return
print fo
(fo, x-1)
When making a function call from within main:
do_n(name, 3)
I get the following outcome:
<function name at 0x01F93AF0>
I'm trying to get the program to print out:
Jack
Jack
Jack
Many thanks in advance

You are neither calling the function, nor are you actually doing the recursive call. Corrected version:
def name():
print 'Jack'
def do_n(fo, x):
if x <= 0:
return
fo()
do_n(fo, x - 1)
To call a function n times, you'd usually use a for loop instead of tail recursion in Python:
for dummy in range(10):
name()

Functions are first-class objects in Python.
fo()

Related

Python: Returning a function that runs a given function n times

I'm trying to write a function that takes a function as its argument and returns a new function that runs said function a given number of times.
For example, if I had a function:
def doubleNumber(num):
return num * 2
and I did the following:
doubleThrice = repeatFunction(doubleNumber, 3)
I should then get this:
doubleThrice(3) # Returns 18 but should it?
I have this so far, but I don't think it's doing what I want:
def repeatFunction(func, n):
def inner(inp):
return func(inp) * n
return inner
I get the impression that it is just running the function once and then multiplying the result by n, not running the function n times, though I'm not sure.
I just can't think of how to build the function I need inside the repeatFunction function and return it, nor has any of the online help really made sense to me.
If you want to apply a function several times, you probably need a loop that repeats that many times:
def repeatFunction(func, n):
def inner(inp):
for i in range(n):
inp = func(inp)
return inp
return inner

Python why do my nested functions give a Nonetype error?

I'm new to programming.
def start():
x = 4
def addition():
n = 3
def exponential():
z = 2
def multiplication():
l = 2
print(x + n ** z * l)
return multiplication
equals = start()
equals()
why am I getting a "Nonetype" object is not callable error?
You're confusing a bunch of programming concepts:
Don't declare a function whenever you only need a statement
You're confusing function declaration with function call (invocation), and also the nesting is pointless. Declaring nested fn2 inside of fn1 doesn't magically also call fn2 and also transmit its return-value back to fn1. You still have to use an explicit return-statement from each fn.(If you forget that, you're implicitly returning None, which is almost surely not what you want)
For now, just don't ever nest functions at all.
Functions with no arguments are essentially useless, they can't take inputs and compute a result. Figure out what their arguments should be.
Specifically for the code you posted, addition(), multiplication() don't have any return value at all, i.e. None. exponential() returns multiplication, i.e. a function which only returns None. But then, both addition() and start() ignore that anyway, since they don't have a return-statement either, hence they implicitly return None.
Calling start() just gives you None, so you're just assigning equals = None. Not the result of some mathematical expression like you intended.
So:
reduce every unnecessary function to just a statement
declare each of your functions separately (non-nested)
each fn must have args (in this case at least two args, to make any sense)
each fn must have a return statement returning some value
only declaring a function and never calling it means it never gets run.
put an empty line in between function declarations (Then it's obvious if you forgot the return-statement)
Credits goes to #BrenBarn for being first to answer this. But I wanna post the code to make it more clear, and point out to some ways to make it better.
def start():
x = 4
def addition():
n = 3
def exponential():
z = 2
def multiplication():
l = 2
print (x + n ** z * l)
return multiplication()
return exponential()
return addition()
equals = start()
print equals #Output: 22
However, this is not the best way to list different methods. You should learn how to use a class in your python code.
I am going to define a class called "mathOperations". I will define three methods (functions): addition,exponential, multiplication. These functions are reusable.
class mathOperations():
def addition(self,x,y):
return x+y
def exponential(self,x,y):
return x**y
def multiplication(self,x,y):
return x*y
m= mathOperations()
z=2
l=2
x=4
n=3
result= m.addition(x,m.multiplication(m.exponential(n,z),l))
print result #Output:22
You should learn how to make your code reusable, try to google "procedural programming"; "Oriented Object Programming", or check "Learn Python the hard way" book. These are first and most used approach to make your code reusable. Think of it like a generic mathematical function to solve problems.

Basic Python problems. ((self) parameter, for loop and bubblesort)

#!/usr/bin/python3
class BubbleSort:
def __init__(self):
self.x=[]
self.limit=0
def getElements(self):
self.limit=int(input("Enter the limit:"))
print("Enter {} number".format(self.limit))
for i in range(1,self.limit+1):
self.x.append(int(input()))
def sort(self):
for i in range(0,self.limit):
for j in range(0,(self.limit-1)-i):
if self.x[j+1] < self.x[j]:
temp1=self.x[j+1]
temp2=self.x[j]
del self.x[j]
del self.x[j+1]
self.x.insert(j+1,temp2)
self.x.insert(j,temp1)
print(self.x)
print("Sorted list is")
for i in self.x:
print(i)
def main():
b=BubbleSort()
b.getElements()
b.sort()
if __name__=="__main__":main()
This is a simple bubble sort program.
Problem 1: If I run the program, two same numbers come , for example, when i enter say -> 3 6 5 1 2
output -> 1 2 2 5 6
The 3 gets replaced by 2.
2: why do I see a lot of 'self' as parameter to a function in python? then what does self.x=[] and self.limit=0 do?
I am super new to methods as a concept and I tried reading, they do not help.
3.In the function getElements, what is self.limit ? why is it even required? we can just use a normal variable like 'x'
Ex: x= int(input("enter the limit:"))
print("enter {} number".format(x))
3.Explain the self.x.append(int(input())))
Doesnt append(int(something)) will add the value of something in the end of a list?
Check the for loop, say the self.limit is 5(entered value). then the loop requires 6 numbers right? equivalence in c++
for(i=1;i<=6;i++)
Assuming the left most number is not considered in python in the range function. right?
Mainly explain 'self' parameter in every function.
When you delete x[j], x[j+1] becomes x[j]. Replace:
del self.x[j]
del self.x[j+1]
with:
del self.x[j+1]
del self.x[j]
However, like #IanAuld said, deleting elements of an array while iterating over it is poor programming practice. Instead, try making a new array and copying the elements to the new array, leaving the original array unchanged in the process. Afterward, if you want, you can replace the old array with the new array.
And to answer your second question, self refers to the class so you can access other variables from the same class your function is in. For example, if you have:
#!/usr/bin/python3
class Foo:
bar = 3
def getValueOfBar(self):
return self.bar
x = Foo()
print( x.getValueOfBar() )
self refers to the parent class, so you can retrieve variables from the class that aren't in the scope of the function.

Python - how to define a variable using a function?

I have a function that returns a number. I want to assign a variable to have this value, but python gives a runtime error when I say temp = foo(i, j) : NameError: name 'foo' is not defined. Note that I've changed the function bodies of bar and foo around, obviously having a function that just returns 1 is useless, but it doesn't change my error.
sum = 0
for i in range(2, 100):
for j in range(2, i):
temp = foo(i, j)
if (temp > 100):
sum = sum + 1
print sum
def bar (n, a):
r = 1
return r
def foo (n, a):
s = bar(n, a)/factorial(5);
return s
def factorial (n):
r = 1
for i in range (2, n + 1):
r *= i;
return r
Names in Python do not exist until they are bound. Move the def foo(...): block above the code that uses foo().
Your definition of foo is AFTER you use it in the file. Put your function definition above the for loop.
As per other answers, your issue is the order in which you run your code: foo hasn't been defined yet when you first call it. Just wanted to add a comment about best practices here.
I always try to put everything in a function and then call any scripts at the bottom. You've probably encountered this pattern before, and it's a good habit to get into:
CONSTANT = 5
def run():
for i in xrange(CONSTANT):
print foo(i) # whatever code you want
def foo(n):
# some method here...
pass
if __name__ == "__main__":
run()
if you run this with python script.py or by hitting f5 in idle, run() will be executed after everything is defined.
By following this pattern you don't have to worry about the order you define your functions in, and you get the added benefit of being able to import foo with other functions without having your script execute during the import, which is probably not a desired behavior.

Python go to def

Hi there
First of all just let me say that I'm new in Python and this is for a school work so this should be done without advanced programing and global functions. Using Python 2.6.6 and WingIDE 101
I need a program to present the user with a menu. The user must pick an option and accordingly to is pick the program does what the user wants.
For example, in the code bellow (its not the actual code), if the user picks 1 it goes to the sum() function.
def menu():
print "What do you want? "
print " 1 for sum"
print " 2 for subtraction"
pick = raw_input("please insert 1 or 2 ")
if pick == "1":
return sum()
if pick == "2":
return subtraction()
else:
menu()
menu()
def sum():
return 8 + 4
def subtraction():
return 8 - 4
I what to know how do I send, after my pick, the program to execute an determined definition.
Thanks
P.S. - running this gives me this error:
Traceback (most recent call last):
File "/usr/lib/wingide-101-3.2/src/debug/tserver/_sandbox.py", line 12, in
File "/usr/lib/wingide-101-3.2/src/debug/tserver/_sandbox.py", line 7, in menu
TypeError: sum expected at least 1 arguments, got 0
There are lots of things wrong with this, so we will take up one by one.
sum is a built-in function in Python. So you cannot name your function sum. You have to call yourself something else, like sum_foo. Or _sum.
Also, your code is executed from top to bottom. So if you are calling a function say X in a function like Y.
def f():
y()
f()
def y():
print 'Y called'
Results in this error:
NameError: global name 'y' is not defined
Because at your program runs, it is not aware of y because the y has not been declared at that point, since the program jumps to f().
To fix this, you would do:
def f():
y()
def y():
print 'Y called'
f()
Also, call the function as func_name() and not return func. And since in your sum and subtraction, you are returning the values, save them in some variable and print them, or print them directly.
def sum():
return 8 + 4
No output
def sum():
print 8 + 4
sum is a builtin at the point you're calling menu(). If you move this call after defining sum and substraction, it won't give you this error.
Please place the sum and subtraction functions above the menu() function definition. You are calling into the built-in sum(iterable[, start]) function provided by python.
the error is because you're using the sum function before you declare it. it should raise a NameError, but the sum function is a builtin so you're calling that func ( that requires at least one argument) and not the func you've written...
to pass through you can call menu() after declaring the sum and subtraction func
ps it's not a good idea to overwrite python's builtin function..change name to your func, and call menu later, or you will get a NameError
You should wrap the call to menu() in a if __name__ == '__main__:' block. At the bottom of your code, just add
if __name__ == '__main__':
menu()
This will help prevent using variables before they're defined.

Categories

Resources