adding variable to python function using other variable - python

I would like pass the variables into the function that uses range(). How do I pass variable C that has more then one number via one variable. Something like range(5, 10, 2)?
Here is my example code:
a = 0
b = 10
c = 2
def num_count(a, b, c):
for number in range(c):
a += b
print("New Count is: {0}".format(a))
I tried passing it as a string and converting it to an integer as well as by using a list. Nothing worked.

you can pass in the range like you mentioned with only a small change to the
for loop
a = 0
b = 10
c = range(5, 10, 2)
def num_count(a, b, c):
for number in c:
a += b
print("New Count is: {0}".format(a))
num_count(a,b,c)
or, as khelwood* mentioned, pass in a list/tuple and expand it with *
a = 0
b = 10
c = (5, 10, 2)
def num_count(a, b, c):
for number in range(*c):
a += b
print("New Count is: {0}".format(a))
num_count(a,b,c)
both output 30 which is expected

Related

wrong result on adition of numbers larger than epsilon using numpy.float128

Considering that epsilon is the smallest number that you can add to one.
I'm getting 1 instead of 1+epsilon when I perform the addition and print the result.
I've implemented a getEpsilon function. I added a print statement for debugging.
The function is implemented as follows:
def getEpsilon():
a = np.float128(1)
b = np.float128(1)
c = np.float128(2)
while a + b != a:
b = b / c
d = a+b
print (F"b={b:3.50f}, d={d:3.50f}")
return b * c
After some iterations of the while loop the value of d is just 1, but a + b != a still evaluates as True.
This is the output:
b=0.5000000000000000000000000, d=1.5000000000000000000000000
b=0.2500000000000000000000000, d=1.2500000000000000000000000
...
b=0.0000000000000004440892099, d=1.0000000000000004440892099
b=0.0000000000000002220446049, d=1.0000000000000002220446049
b=0.0000000000000001110223025, d=1.0000000000000000000000000
b=0.0000000000000000555111512, d=1.0000000000000000000000000
...
b=0.0000000000000000001084202, d=1.0000000000000000000000000
b=0.0000000000000000000542101, d=1.0000000000000000000000000
Why does a + b != a have a different behavior than d = a+b
It looks like some operation is done with 64 bits instead.
If I repeat it with the float64 equivalent type the result is (last 2 lines):
b=0.0000000000000002220446049, d=1.0000000000000002220446049
b=0.0000000000000001110223025, d=1.0000000000000000000000000

Is this possible to use += to add a single value into two variables at the same time?

Following this logic :
a,b = 0,0
I was expecting this to work :
a,b += 1,1
SyntaxError: illegal expression for augmented assignment
so here i am.
Is there anyway to achieve this in one line ?
Think of it like a list of "how to update each variable" (variables to the left, formulas to the right).
a, b = a+1, b+1
As already mentioned by others, you could combine two statements into one line as a += 1; b += 1.
But, if you prefer a single statement in the same "spirit" as a, b = 0, 0 then try this:
a, b = a + 1, b + 1
The way these assignments work is that a list of variables is assigned a list of values:
variable
value
a
0
b
0
→ a = 0; b = 0 → a, b = 0, 0
variable
value
a
a + 1
b
b + 1
→ a = a + 1; b = b + 1 → a, b = a + 1, b + 1
You can either use multiple statements, one per table row, or a single statement where all the values in the left column go on one side of the = and all the values in the right column go on the other side.
This works only for = though. Your idea a, b += 1 firstly wouldn't work for the same reason a, b = 0 doesn't (there is only one right-hand side value), but a, b += 1, 1 unfortunately also doesn't work, just because Python doesn't support this concept. + with tuples would concatenate them into a larger tuple, not add each of their elements ((1, 2) + (3, 4) is (1, 2, 3, 4) and not (4, 6)).
If you want it in 1 line here is what you can do.. a,b=0 is not the right way , it should have been a=b=0 or a,b=0,0
a=b=0
a+=1;b+=1
You can use map to apply your increment or other operation
a,b=0,0
a, b = map( lambda x : x+1, [a,b])
output
1,1

Accessing only one of the return values from a function

How do I only access one of the values:
my code:
def test():
a = 4
b = 5
c = 6
return a, b, c
a = test().a # only want "a" from the function
You can ignore the other values by using a placeholder _
def test():
a = 4
b = 5
c = 6
return a, b, c
#Ignore b and c
a, _, _ = test()
print(a)
#4
Or you could return a dictionary of values and access a from the dictionary
def test():
a = 4
b = 5
c = 6
return locals()
print(test()['a'])
#4
Or you could just use indexing to find the first element of the returned tuple, given you know a is the first element, as per Tim's Answer above
def test():
a = 4
b = 5
c = 6
return a, b, c
print(test()[0])
#a
The function test() returns a tuple so in order to access a you would have to use the following code:
a = test()[0]
You could return a dictionary instead:
def test():
a = 4
b = 5
c = 6
return {"a":a, "b":b, "c":c}
print(test()["a"])
4
If you want to stick with your current approach, then the best you might be able to do would be to just print the first element from the tuple returned:
print(test()[0])
But this of course means that the caller would have to know that a happens to coincide with the first value.
There are a few ways to do this.
a, b, c = test() # ignore b and c
a, *_ = test() # ignore _ which captures b and c
a = test()[0]
a = test()
a[0] # which is equal to the 'a' inside the test function.

python generators/ variable [duplicate]

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 9 years ago.
2 questions...
1) I am trying to wrap my brain around this...
I am to understand that variables can take values using such code syntax as this:
a ,b = 2, 3
and that this would be the same as coding:
a = 2
b = 3
I hope this is correct.
So here is my puzzlement. I have the following code using a generator:
def fibonacci_generator() :
a = b = 1
while True :
yield a
a , b = b , a + b
fib = fibonacci_generator()
for i in fib :
if i > 100 :
break
else :
print ('Generated: ', i)
print (next(fib))
(yes this is code from a python learning book)
If I were to rewrite this code and instead assign my a and b variables like so:
yield a
a = b
b = a + b
then I get different returns for a.
I am not understanding why this is??? Super frustrated about it!
2) When I run the code as written the first time above, I get the number 233 printed at the end. I also cannot figure out why??!!
In this code:
a, b = b, a + b
a is set to b, and b is set to a+b.
In this code:
a = b
b = a + b
a is set to b, and b is afterwards set to a+b. But since a is already set to b, then b is in fact set to b+b.
a , b = b , a + b
is not the same as
a = b
b = a + b
Because, when you say
a, b = b, a + b
It will first prepare the values on the right side b, a + b and assign them to the variables on the left.
Python computes the right hand side first and then assigns the value (or unpacks it) on the left hand side. So, in the example:
a, b = b, a+b
compared to:
a = b
b = a + b
You have different values for a when you go to compute a + b. In the second example, when you compute a + b it is equivalent to computing b + b!
You are probably missing the flow of data.
a = b ...eqI
b = a+b ...eqII
here, before executing b eqII, a has already stored bas a value of itself. Now when yow try execute b of eqII it comes like b=b+b. Because after executing eqI when it comes to eqII, a is bnow.
But in python you can avoid this conflict if you try a, b = b, a+b.
For your second question:
I am not sure about your code but this one will work fine in the sense of your code...
a = b = 1
while True :
a , b = b , a + b
if a and b > 100:
break
else: print a, b
try it !!
In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables. Because that you get different results
a, b = b, a+b
This line computes b and a+b before performing any assignment. Strictly speaking, it computes a tuple (b, a+b) and then unpacks the elements of the tuple to assign them to a and b.
a = b
b = a+b
This assigns a, then computes a+b using the new value of a.

How can I use the result from a function in another function? [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
Suppose I have a function like:
def eklid(p, a, b,):
x = [1, 0]
y = [0, 1]
r = [a, b]
q = [0]
n = 0
while r[n+1] != 0:
q.append(r[n] // r[n+1])
r.append(r[n] % r[n+1])
x.append(x[n] - x[n+1] * q[n+1])
y.append(y[n] - y[n+1] * q[n+1])
if p == 0:
print(r[n], "=", r[n+1], "*", q[n+1], "+", r[n+2])
elif p == 1: # extended print
print(r[n+2], "\t", x[n+2], "\t", y[n+2], "\t", r[n+2], "=", a, "*", x[n+2], "+", b, "*", y[n+2])
elif p == -1:
k =1
else:
print("wrong input")
n += 1
return x, y, r, q, n,
I want to use x and r from it in this function:
def cong_solv(x, r, b,):
result = x/r
int_result = int(result)
return int_result
How can I do that?
# Here, a=x, b=y, c=r, d=q, e=n
a, b, c, d, e = eklid(h, i, k)
# Assuming based on your function definitions you want the
# same value as the third argument
final_result = cong_solv(a, c, k)
You get the return values from eklid and save them into variables. You then use those variables to call the next function.
Of course, in a real code you should name your varialbes better than I did in this example. I deliberately did not call the variables the same names as inside the function to demonstrate that you don't have to.
One way would be to call the eklid() function from inside the cong_solv() function. Something like this should work:
def cong_solv(x, r, b):
p = "foo"
b = "bar"
x, y, r, q, n = eklid(p, a, b)
result = x/r
int_result = int(result)
return int_result
In python, when you return more than one variable, it returns a tuple.
You can retrieve the value by its index (returned_value[0], returned_value[1]) or unpack the tuple like Mike Driscoll said (a, b, c, d = eklid(h, i, k)).
Since I got two downvotes, I am going to give you better (I hope) explanation:
Everytime you return more than one value, it returns a tuple.
def my_function():
a = 10
b = 20
return a, b
print type(my_function()) # <type 'tuple'>
But if you return just one value:
def my_function():
a = 10
return a
print type(my_function()) # <type 'int'>
So if you want to use your value, you can:
Unpack tuple values like this
a, b = my_function()
This way you get your return values in the same order you return inside my_function.
Rewriting your code, you can simply do:
a, b, c = eklid(10, 20, 30) # it will return a tuple
And call your other function:
cong_solv(a, b, 20)
In my honest opinion I would return a dict. With dict you can be explicit because your values have key names.
Inside your eklid return function:
return d # d = {"what_x_means": x,
# "what_y_means": y,
# "what_r_means": r,
# "what_q_means": q,
# "what_n_means": n}
And retrieve for its key:
d["what_x_means"]
d["what_r_means"]
Similar to How do you return multiple values in Python?
Return as an tuple (x,y,r....) or an array and assign to tuple / array respectively.
Or assign them to class variables and access them

Categories

Resources