So I have a function that keeps spitting out:
(10.3,11.4)
when it should be spitting out:
10.3 11.4
I played around and wrote a simple python code and I seem to understand the concept
a=3
b=3
print a,b #returns 3 3
but it is not working for the function below, so I am wondering why it keeps returning the ()
import math
x=10.01
y=9.01
def d():
b = 2.00 * x / math.sqrt(7)
q=round(y-b,2)
r=round(y+b,2)
return q,r
print d() #returns (1.4399999999999999, 16.579999999999998)
print is (correctly) printing the tuple that is returned from d. To print the values individually, try this:
print '{} {}'.format(*d())
Or this:
dret = d()
print dret[0],dret[1]
print a,b doesn't interpret a,b as a tuple, but rather as a sequence of parameters to the print statement. Note that the print statement changes syntax in Python3 for added confusion.
To make the a,b case parallel to the q,r case, it would look more like this:
c = a,b
print c
In that case the print statement would receive a tuple, and not two individual values.
The reason is in the statement "return q, r"
You cannot return multiple values from a function. What python is doing is creating a tuple with q and r, and returning that, as return q, r is interpreted as return (q, r) Then print takes that and outputs a tuple. So it is really equivelent to print (q, r)
However, print q, r is executed differently, as a multi-argument print and will print all arguments with spaces in between.
Hope this clears up any confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With