What is the function of the semicolon in Python?

14

I found some codes that had variables inside classes, ending in semicolons. I did not understand why, and also did not find anything on the internet about it.

    class exemplo():

      self.variavel_teste = 0;
    
asked by anonymous 13.09.2018 / 16:13

2 answers

17

It is only necessary if you want to put an extra command on the same line, so it works as a command separator. Obviously it is allowed to put it and then leave nothing, which makes it seem like an equal terminator of C and its descendants. In fact it is a terminator, but optional in almost all situations. And in this particular case it seems abuse of the resource.

This is called compound statements .

x = 5; print(x);
if x > 0: print("maior que zero"); print(x);

It's the same as

x = 5
print(x)
if x > 0:
    print("maior que zero")
    print(x)

See running on ideone . And in Coding Ground . Also I put GitHub for future reference .

    
13.09.2018 / 16:18
12

In the example, for nothing.

It can be used to separate expressions on the same line, and optionally at the end of it:

a = 1; b = 2

print(a+b)  # 3

See working at Repl.it

But this usually affects readability and in Python it almost is always prioritized, so you will hardly ever use the semicolon.

In Python grammar is planned:

simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE

Where a simple_stmt is made up of a small_stmt , which can be followed by countless other small_stmt separated by the semicolon, with the character being optional at the end before the line break. >

In your example, there is only one expression that precedes the character, so it has no use whatsoever.

    
13.09.2018 / 16:20