How to alter the value of a variable with a function and store it permanently.
tried the code below but it doesn't alter the value of variable.
n=2
def f(x):
x+=2
return x
f(n)
print n #the output is 2 instead of 4 I want
Think of variable as labels to values, n is labeling 2, if you want n to label the value of the f function just label it again:
n=2
def f(x):
x+=2
return x
n = f(n)
print n
def f(x):
return x + 2
n = 2
n = f(n)
print(n)
This is how functions should be used. They receive values as arguments and return new values. When/where/how that is assigned to a variable is the caller's problem, since the variable is in the caller's scope.
If you want "self modification", a class is probably the better option:
class Foo:
def __init__(self, n):
self.n = n
def inc(self):
self.n += 2
f = Foo(2)
f.inc()
print(f.n)
Related
Trying to learn python as a java programmer. I would really appreciate some insight into why my program is telling me that my "isPrime" function isn't defined, especially with the use of 'self.'
import math
class Problem10:
def sumOfPrimesX(self, number):
sum = 0
for i in range(0, number):
if isPrime(i):
sum += i
return sum
def isPrime(self, x):
for n in range(0, math.floor(x/2)):
if x % n == 0:
return False
return True
print(sumOfPrimesX(input()))
all functions need it as their first parameter in a python program
No, only the instance methods, the methods related to a specific instance of a class. A simple function can need to parameter.
And you won't see the parameter self filled with the classic way of calling it, if you call the method on a instance it'll be filled by it
p = Problem10()
p.sumOfPrimesX(int(input("Give a value"))) # call on instance, one paramater given
# same as
Problem10.sumOfPrimesX(Problem10(), int(input("Give a value")))
# call on class itself, need to pass an instance as first to fill 'self
Also you need to wrap the input in an int, also start the loop at 2
p = Problem10()
print(p.sumOfPrimesX(int(input("Give a value"))))
class Problem10:
def isPrime(self, x):
for n in range(2, math.floor(x / 2)):
if x % n == 0:
return False
return True
The issue is both isPrime and sumofPrimesX are methods of the class Problem10.
Try the following:
import math
class Problem10:
def sumOfPrimesX(self, number):
sum = 0
for i in range(0, number):
if self.isPrime(i):
sum += i
return sum
def isPrime(self, x):
for n in range(0, math.floor(x/2)):
if x % n == 0:
return False
return True
pv = Problem10()
print(pv.sumOfPrimesX(input()))
How to create a functinon in Python such that for example:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def x(x):
return x
lni=[]
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (x(x)-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
I think I need it to return the function such that the formula variable is a function by x in its own right and so later i can call upon it in the fashion
formula(10)=output
Set the results of a function call equal to your desired variable.
def f(x):
"A function that changes nothing"
return x
a = f(5) # same as a = 5
To avoid confusion, I recommend that you don't give functions the same name as their arguments, (i.e., don't do def x(x): ...).
If you want formula to be a function, then declare it as one, after which the correct syntax would be output = formula(10).
formula(10) is instance of a function and hence only has a value not a variable name to assign to.
A good way to write above code will be:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def y(x):
return x
def formula_calc(X):
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (X-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
return formula
# now formula is a function of x. X can itself be a function.
print(formula(y(7))
# this will print value of formula at 7 as x(7) is 7.
I am trying to write a closure with two inner functions, but I am getting the below error
def factory(n=0):
#n=0
def current():
return n
return current
def counter():
n=n+1
return n
return counter
f_current,f_counter = int(input())
print(f_counter())
print(f_current())
I have the below error:
>>4
Traceback (most recent call last):
File "C:/Users/lokesh/Desktop/python/closure3.py",
line 13, in <module>
f_current,f_counter = int(input())
TypeError: 'int' object is not iterable
My requirement is after giving input 4,it should display:
4
5
I am new to python, can somebody help me here... thanks in advance
That looks more like what you want:
def factory(n=0):
def current():
return n
def counter():
nonlocal n
n += 1
return n
return current, counter
f_current, f_counter = factory()
print(f_current())
print(f_counter())
print(f_current())
print(f_counter())
Output:
0
1
1
2
With 4 as input:
f_current, f_counter = factory(4)
print(f_current())
print(f_counter())
4
5
factory() returns both inner functions. You need to use nonlocal to increment the n form the enclosing function. Without nonlocal you would not be able to modify n but would get:
UnboundLocalError: local variable 'n' referenced before assignment
because n is just a local variable. nonlocal n makes n from the enclosing function modifiable inside the inner function. Assessing n in current is fine, because Python's scoping rules allow read access to variables form an outer scope, here from the scope of the enclosing function.
Hi Mike ,I think non-local does'nt make any sense,I am giving the
solution which worked in my case.
def factory(n):
def current():
return n
def counter():
n=int(current())
n=n+1
return n
return current, counter
n=0
f_current, f_counter = factory((input()))
print(f_current())
print(f_counter())
def factory(n=0):
def current():
return n
def counter():
return n+1
return current, counter
f_current, f_counter = factory(int(input()))
print(f_current())
print(f_counter())
Mike's Nonlocal usage is very nice,but we can also access the variable value of n from enclosing scope by a new variable m inside Counter inner function and return it after incrementing.In that way,Nonlocal is not needed.
def factory(n=0):
def current():
return n
def counter():
m=n
m=m+1
return m
return current,counter
f_current,f_counter=factory(int(input()))
print(f_current())
print(f_counter())
`
You can simply use a new variable as the argument for the inner function which is equal to that of the outer function and proceed.
def factory(n=0):
def current():
return n
def counter(x=n):
return x+1
return current, counter
f_current,f_counter =factory(int(input()))
print(f_current())
print(f_counter())
If Python does not support method overloading (besides *args and **kwargs or PEP 3124), then why does this overload work?
# the sum from 1 to n
def sum(n):
if n > 0:
return n + sum(n - 1)
else:
return 0
print(sum(3))
# the sum from n to m, inclusive
def sum(n, m):
if n <= m:
return n + sum(n + 1, m)
else:
return 0
print(sum(3,5))
... while more baffling, this one does not:
# the sum of elements in an array
def sumArray(A):
return sumArray(A, len(A)-1)
# a helper for the above
def sumArray(A, i):
if i < 0:
return 0
else:
return A[i] + sumArray(A, i-1)
print(sumArray([1,2,3]))
You aren't overloading. You're hiding one thing behind another by using the same name for different objects. Try
sum = 42
and see how print(sum(3, 5)) ceases to work.
Function definitions are variable assignments. They create a function and assign it to the variable matching the name you used. You're seeing the ordinary effects of reassigning a variable.
def sum(n):
...
This assigns a function of 1 argument to the variable sum.
print(sum(3))
This uses the function assigned to that variable.
def sum(n, m):
...
This assigns a new function to the variable sum, replacing the first function.
print(sum(3,5))
This uses the new function. If you had tried to use the old function, you wouldn't find it.
# the sum of elements in an array
def sumArray(A):
return sumArray(A, len(A)-1)
# a helper for the above
def sumArray(A, i):
if i < 0:
return 0
else:
return A[i] + sumArray(A, i-1)
print(sumArray([1,2,3]))
This assigns a function to sumArray, then assigns a different function to sumArray, then tries to use the value from the first assignment. It finds the second function, and fails.
In your first example, you define function and use it, then overwrite it with another, and use the new one, just like with regular variables:
a = 1
print(a)
a = 2
print(a)
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.