Perplexed over a simple function in Python - python-3.x

Look at the code below:
def foo (x):
print("foo environment: x = {0}".format(x))
def bar (z, x = 0):
print("bar environment: z = {0} and x = {1}. Value to be returned: {2}".format(z, x, x+z))
return z + x
return bar(3)
foo(5)
foo environment: x = 5
bar environment: z = 3 and x = 0. Value to be returned: 3
3
Since in the foo environment x = 5, why bar uses the value 0?

You are only passing one argument here:
return bar(3)
The bar function accepts two values, one z and one x (x has a default value (0) and that is why only 1 argument is enough). By only passing the z, x=0.
Try this, and see what happens:
return bar(3, x)

Related

Python 3+: How to return for loop output value to function

I want to assign value to function of below code:
def adds(y):
for i in y:
z = i + 1
print(z)
x = [1, 2, 3]
adds(x)
output:
2
3
4
But when i tried to assigned the result to function with creating instance such:
# print(z) commented
p = adds(x)
print(p)
output:
None
expected output:
2
3
4
gives the return inside for loop gives output: 2
gives the return inside function block or set variable z to global inside the for loop block, and recall it in the outside gives same output: 4
How do to achieve the expected output: 2 3 4, from the return value to function of above code
As the function is printing the result, so no need to store the function value add(z) in variable so can return the value in function by using (return z) in function, Then you can store in a variable and print it.
Thanks
from
https://stackoverflow.com/a/39366192/18980456
def adds(y):
z = [i + 1 for i in y]
return z
x = [1, 2, 3]
p = adds(x)
print(p)

How the y is returning 1 without passing anything to it?

Can someone explain to me how the y is returning 1 in this code?
def f(x):
def g(y):
print(y)
return y + x + 3
return g
nf1 = f(1)
print(nf1(1))
Result:
1
5
You are basically calling print(f(1)(1)) in the last line. Hence both x and y are 1. Function g returns 5 and the print inside g prints y which is 1.

How to solve Equation without any Modules in Python?

I want to solve this equation without any Modules(NumPy, Sympy... etc.)
Px + Qy = W
(ex. 5x + 6y = 55)
Thanks.
It is a very crude way to do this, but you can use brute-force technique, as I said in comment under your question. It can probably be optimized a lot, gives only int outputs, but overall shows the method:
import numpy as np
# Provide the equation:
print("Provide a, b and c to evaluate in equation of form {ax + by - c = 0}")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
x_range = int(input("x-searching range (-a, a): "))
y_range = int(input("y-searching range (-b, b): "))
error = float(input("maximum accepted error from the exact solution: "))
x_range = np.arange(-x_range, x_range, 1)
y_range = np.arange(-y_range, y_range, 1)
for x in x_range:
for y in y_range:
if -error <= a * x + b * y - c <= error:
print("Got an absolute error of {} or less with numbers x = {} and y = {}.".format(error, x, y))
Example output for a = 1, b = 2, c = 3, x_range = 10, y_range = 10, error = 0.001:
Got an error of 0.001 or less with numbers x = -9 and y = 6.
Got an error of 0.001 or less with numbers x = -7 and y = 5.
Got an error of 0.001 or less with numbers x = -5 and y = 4.
Got an error of 0.001 or less with numbers x = -3 and y = 3.
Got an error of 0.001 or less with numbers x = -1 and y = 2.
Got an error of 0.001 or less with numbers x = 1 and y = 1.
Got an error of 0.001 or less with numbers x = 3 and y = 0.
Got an error of 0.001 or less with numbers x = 5 and y = -1.
Got an error of 0.001 or less with numbers x = 7 and y = -2.
Got an error of 0.001 or less with numbers x = 9 and y = -3.
I am using numpy, but not a built-in function to solve the equation itself, just to create an array. This can be done without it, of course.
There are thousands of ways to solve an equation with python.
One of those is:
def myfunc (x=None, y=None):
return ((55-6*y)/5.0) if y else ((55-5*x)/6.0)
print(myfunc(x=10)) # OUTPUT: 0.833333333333, y value for x == 10
print(myfunc(y=42)) # OUTPUT: -39.4, x value for y == 42
You simply define inside a function the steps required to solve the equation.
In our example, if we have y value we subtract 6*y to 55 then we divide by 5.0 (we add .0 to have a float as result), otherwise (means we have x) we subtract 5*x from 55 and then we divide by 6.0
with the same principle, you can generalize:
def myfunc (x=None, y=None, P=None, Q=None, W=None):
if not W:
return P*x + Q*y
elif not x:
return (W-Q*y)/float(P)
elif not y:
return (W-P*x)/float(Q)
elif not P:
return (W-Q*y)/float(x)
elif not Q:
return (W-P*x)/float(y)
print(myfunc(x=10, P=5, Q=6, W=55)) # OUTPUT: 0.833333333333, y value for x == 10
print(myfunc(y=42, P=5, Q=6, W=55)) # OUTPUT: -39.4, x value for y == 42
check this QA for some other interesting ways to approach this problem

Accessing global variable in function in python

I have two pieces of code:
def g(y):
print(x)
x = 5
g(x)
and
def h(y):
x = x + 1
x = 5
h(x)
The first piece of code works perfectly fine printing '5' while the second piece returns:
UnboundLocalError: local variable 'x' referenced before assignment
What does this actually mean? Is it trying to say that it tried to evaluate the line x = x + 1 before it evaluates the line x=5? If that is so, why has the first piece of code not generated any error? It similarly had to evaluate the line print(x) before x was assigned a value.
I think I might have an misunderstanding how functions are called. But I do not know what it is that I got wrong.
# first block: read of global variable.
def g(y):
print(x)
x = 5
g(x)
# second block: create new variable `x` (not global) and trying to assign new value to it based on on this new var that is not yet initialized.
def h(y):
x = x + 1
x = 5
h(x)
If you want to use global you need to specify that explicitly with global keyword:
def h(y):
global x
x = x + 1
x = 5
h(x)
Just as Aiven said, or you can modify the code like this:
def h(y):
x = 9
x = x + 1
print(x) #local x
x = 5
h(x)
print(x) #global x

How does in-place operation of list work

This is my code:
x=[1,3,2]
def foo(x):
x.sort()
x = x + [4,5]
x.extend([6,7])
return x
foo(x)
print(x)
i expect the printed list to be [1,2,3,4,5,6,7] but i got [1,2,3] instead. I read that this is due to in-place operation because it returns None, but ive included return x into my code but it still does not work.
There are two issues here: the scope of x, and the return value.
When you declare x = x + [4, 5], x isn't the same list anymore
>>> x = [1, 2, 3]
>>> id(x)
4501926472
>>> x = x + [4, 5]
>>> id(x)
4501926616
>>>
Thus, x inside foo refers to a local x, not the global x defined outside of the function.
Furthermore, you do not store the return x from foo, so it disappears, for all practical purposes.
You have to tell python to print the returned value of x after the foo method is executed , you told python to print x , witch you defined as x=[1,3,2] , you have to print the value of x after it goes through the foo method
x=[1,3,2]
def foo(x):
x.sort()
x = x + [4,5]
x.extend([6,7])
return x
print(foo(x))

Resources