user1021726
user1021726

Reputation: 648

declare multiple variables to same value

Using Python 3.3.3 and the pywin32 api.

I'm new to python and trying to simplify my script. I'm trying to assign a single value to multiple variables but it says

Illegal expression for augmented assignment

import win32api
import win32con
import time

#makes sure your computer doesnt lock when idle for too long...
def move(x, y):
    for i in range(10):
        win32api.SetCursorPos((x,y))

        if(i % 1 == 0): x, y += 10 #this is where it crashes
        if(i % 2 == 0): x, y -= 10

        time.sleep(5)

move(500, 500)

Upvotes: 0

Views: 190

Answers (3)

nio
nio

Reputation: 5289

You could do:

if(i % 1 == 0): x+=10; y+=10
if(i % 2 == 0): x-=10; y-=10

Anyway be careful with i%1, it will always evaluate to 0 and therefore your first if will always execute. Maybe you wanted to write it like this to alternate the direction of cursor movement:

if(i % 2 == 1): x+=10; y+=10
if(i % 2 == 0): x-=10; y-=10

More reading: How to put multiple statements in one line?

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361565

You can chain together multiple plain assignments like:

a = b = 5

That doesn't work for augmented assignments like += though. You'll have to write those separately.

if i % 1 == 0:
    x += 10
    y += 10

(Also, if doesn't require parentheses.)

Upvotes: 1

James Mills
James Mills

Reputation: 19030

if(i % 1 == 0): x, y += 10 #this is where it crashes
if(i % 2 == 0): x, y -= 10

It's not possible to do this. When you unpack tuples in Python the number of variables on the left-hand-side must equal the no. of items in the tuple on the right-hand-side.

Upvotes: 2

Related Questions