What is the Python semicolon function?

Asked

Viewed 2,035 times

20

I found some codes that had variables inside classes, finished in semicolons. I don’t understand why, and I haven’t found anything on the Internet about it either.

    class exemplo():

      self.variavel_teste = 0;

2 answers

23


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 on and then leave nothing, which makes it appear as an equal terminator of C and its descendants. In fact it is a terminator, but optional in almost every situation. And in this specific case seems abuse of the resource.

This is called compound statements.

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

Is the same as

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 1

    The same happens in Ruby. Only we do it for undefined methods, usually, that in Python we would use pass, for example. In Ruby: def method; end

15

In the example, for nothing.

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

a = 1; b = 2

print(a+b)  # 3

See working on Repl.it

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

In the python grammar anticipated:

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

Where a simple_stmt is composed of a small_stmt, may be followed by numerous others small_stmt separated by the semicolon, with the character being optional at the end, before the line break.

In his example, there is only one expression that precedes the character, so he had no use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.