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.
From the official documentation;
So returning multiple values from a function like you do here returns them in a tuple by definition.
Try explicitly unpacking the tuple returned by d()
:
In [1]: import math
In [2]: x=10.01
In [3]: y=9.01
In [4]: def d():
...: b = 2.00 * x / math.sqrt(7)
...: q=round(y-b,2)
...: r=round(y+b,2)
...: return q,r
...:
In [5]: a, b = d()
In [6]: print a, b
1.44 16.58
math.sqrt return a complex number with a real and an imaginary part. Change it into math.sqrt(7).real and the complex number is a real number only. This make the print do as you expect
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.