'How to remove parenthesis from output python
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)
Solution 1:[1]
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.
Solution 2:[2]
From the official documentation;
- The return statement leaves the current function call with the expression list.
- An expression list containing at least one comma yields a tuple.
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
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eliotn |
| Solution 2 | |
| Solution 3 | Eskil Mjelva Saatvedt |
