0

I am doing a pygame physics tutorial. However, when I try putting Round Bracket inside Round Bracket in Def Function, it says "Invalid Syntax". I could not find a answer anywhere.

def addVectors((angle1, length1), (angle2, length2)):
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
ChinDaMay
  • 204
  • 1
  • 11

3 Answers3

1

That only works in Python 2 sadly:

>$ python2
Python 2.7.18 (default, Mar  8 2021, 13:02:45) 
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def addVectors((angle1, length1), (angle2, length2)):
...   pass
... 
>>> 
>$ python3
Python 3.8.8 (default, Apr 13 2021, 19:58:26) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def addVectors((angle1, length1), (angle2, length2)):
  File "<stdin>", line 1
    def addVectors((angle1, length1), (angle2, length2)):
                   ^
SyntaxError: invalid syntax

I suggest using a namedtuple:

from collections import namedtuple

Vector = namedtuple('Vector', ['angle', 'length'])

v1 = Vector(angle=1, length=1)
v2 = Vector(angle=2, length=1)

def addVectors(v1, v2):
    return Vector(v1.angle + v2.angle, v1.length + v2.length)
Caridorc
  • 6,222
  • 2
  • 31
  • 46
1

You are trying to pass a tuple by parameter but this way is the wrong syntax way. Try something like that:

def addVectors(*angles):
    for i in angles:
        print(i)

# addVectors((angle1, length1), (angle2, length2))
# (1, 2)
# (3, 4)

The * will unpack like a list and you can pass any size of parameters

Franz Kurt
  • 1,020
  • 2
  • 14
  • 14
  • 1
    How would I Integrate that with: `def addVectors(angle1, length1, angle2, length2): x = math.sin(angle1)*length1 +math.sin(angle2)*length2 y = math.cos(angle1)*length1 +math.cos(angle2)*length2 angle = 0.5*math.pi -math.atan2(y,x) length = math.hypot(x,y) return(angle, length)` – ChinDaMay Jan 16 '22 at 17:05
  • Thats is another question! – Franz Kurt Jan 16 '22 at 17:09
1

Given your specific example, you can hopefully see why the syntax you are looking for is error prone. Imagine what happens when you accidentally mess up a single parenthesis 6 months from now. You have a couple of options to implement the same functionality trivially in Python 3 with fewer parentheses.

If you want the input to be four objects:

def addVectors(angle1, length1, angle2, length2):
    ...

and call as

self.angle, self.speed = addVectors(self.angle, self.speed, *gravity)

If you want two inputs, you can specify an explicit unpacking:

def addVectors(vector1, vector2):
    angle1, length1 = vector1
    angle2, length2 = vector2
    ...

and call it as

self.angle, self.speed = addVectors((self.angle, self.speed), gravity)

As you can see, there's no reason to give up on Python 3 just because of this syntax.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264