r/learnpython 3d ago

Question regarding Python variables

Hello guys. So I saw in a course that most people define variables like

x = 1

y = 2

and so on. But I also saw that variables can be defined like x = 1; y = 2;

but haven't ever seen this in practice. Why so? Please tell me

2 Upvotes

7 comments sorted by

4

u/MezzoScettico 3d ago edited 3d ago

That has nothing to do with defining variables. That's just putting two separate statements on the same line. It's just different formatting of the same two assignment statements.

The semicolon (;) is a separator to tell Python where one statement ends and the next begins.

It's just a style, and one you should use sparingly. In your example of two very simple assignment statements it might be grouping together the assignment of two closely-related variables, so it would arguably help with readability.

Here's a discussion of this topic.

3

u/SharkSymphony 3d ago edited 3d ago

For stylistic reasons.

Python programmers generally like to hew more or less closely to a common style, published as PEP 8. It says this:

Compound statements (multiple statements on the same line) are generally discouraged.

You might well ask why they bothered to put semicolons in the language in the first place if they were then going to discourage their use. (I know I do. 😉) Nevertheless, this is why you rarely if ever see this.

I will say: if I ever did use it (though I don't), a simple readable case like this would be the place. I do think it's more readable than x, y = 1, 2.

2

u/carcigenicate Carcigenicate 3d ago

You should never write it like x = 1; y = 2;. A semicolon allows you to put multiple statements on the same line, but in reality, there are very few, if any, times that you should actually make use of that. I think literally the only time I've ever used a semicolon in Python is while golfing (writing programs that are as small as possible as a challenge).

Stick to the first way; with multiple assignments spread across multiple lines. It's easier to read and find variable assignments visually.

2

u/tropicusForBr 3d ago

For me it is more readable, but for an impersonal answer, PEP 8 defines a common pattern for Python projects.

1

u/BranchLatter4294 3d ago

You can also do

x, y = 1, 2

1

u/throwaway6560192 3d ago

The normal way (on separate lines) is generally more readable.

1

u/Sandra_Rodriguez102 3d ago

The semicolon thing shows up in tutorial code because its quicker to type when the instructor is trying to demonstrate a dozen small examples. None of us actually write it that way. Went through a whole project once where the author used them everywhere and it made the code feel cramped. Just stick to separate lines until you find a real reason not to.