+ 4
Does semicolon works in python? I have mistakenly typed a ';' after print function and its working... Can anyone explain this?
Semicolon in python https://code.sololearn.com/cPxoQFFr01q3/?ref=app
2 Antworten
+ 8
Python does not require semicolons to terminate statements but can be used to delimit statements if you wish to put multiple statements on the same line.
Don't terminate all of your statements with a semicolon. It's technically legal to do this in Python, but is totally useless unless you're placing more than one statement on a single line (e.g., x=1; y=2; z=3).
+ 2
Side note about M. Watney 's example.
If you want to assign multiple values at once, or even swap two values:
name1, name2, name3 = value1, value2, value3
How this works is the right hand side is evaluated first as a tuple:
(value1, value2, value3)
And then is unpacked at an exact 1:1 ratio since multiple names are used.
If the ratio is off, a `ValueError` is thrown at runtime.
So how this works is basically similar to this in ECMAScript:
[ name1, name2, name3 ] = [ value1, value2, value3 ]
// Except Python requires both sides to have the same length
It can be used for swapping / shifting variables:
a, b = b, a
a, b, c, d = 0, a, b, c
Also can be used to unpack sequences:
temp = [1, 2, 3]
a, b, c = temp
And a useful-to-many example if you use `sys.argv`, disliking to separate the program name (index 0) and actual args (index 1+):
import sys
# ...
arg0, args = sys.argv[0], sys.args[1:]