Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this piece of Python code doing?

This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for.

x, y = x + 3 * y, 4 * x + 1 * y

Is this a special Python syntax?

like image 734
Jordan Parmer Avatar asked Sep 02 '09 23:09

Jordan Parmer


People also ask

What is the code Python used for?

Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general-purpose language, meaning it can be used to create a variety of different programs and isn't specialized for any specific problems.

What does Pythonic code mean?

In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful. To help us better understand, let's briefly look at some aspects of the Python language.

How does Python code execute?

Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python Virtual Machine. This is a similar approach to the one taken by Java. There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM).

How is Python code used in the real world?

The major fields include Machine Learning and AI, Web Development, Data Analytics, Game Development, IoT, Application Development, and Game Development. Many sectors including the healthcare sector, finance sector, aerospace sector, and banking sector rely heavily on Python.


1 Answers

x, y = x + 3 * y, 4 * x + 1 * y

is the equivalent of:

x = x + 3 * y
y = 4 * x + 1 * y

EXCEPT that it uses the original values for x and y in both calculations - because the new values for x and y aren't assigned until both calculations are complete.

The generic form is:

x,y = a,b

where a and b are expressions the values of which get assigned to x and y respectively. You can actually assign any tuple (set of comma-separated values) to any tuple of variables of the same size - for instance,

x,y,z = a,b,c

would also work, but

w,x,y,z = a,b,c

would not because the number of values in the right-hand tuple doesn't match the number of variables in the left-hand tuple.

like image 81
Amber Avatar answered Nov 15 '22 21:11

Amber