I got a function online to help me with my current project and it had semicolons on some of the lines. I was wondering why? Is it to break the function?
def containsAny(self, strings=[]):
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
for string in strings:
for char in string:
if char in alphabet: return 1;
return 0;
The function I got online with little modification:
for string in strings:
for char in string:
if char in alphabet: return 1;
Is the above saying the following?
if char in alphabet:
return 1
break
The semicolon does nothing in the code you show.
I suspect this is someone who programs in another language (C, Java, ...) that requires semicolons at the end of statements and it's just a habit (happens to me sometimes too).
If you want to put several Python statements on the same line, you can use a semi-colon to separate them, see this Python Doc:
A suite is a group of statements controlled by a clause. A suite can
be one or more semicolon-separated simple statements on the same line
as the header, following the header’s colon, or it can be one or more
indented statements on subsequent lines
The semicolon here does not do anything. People who come from C/C++/Java/(many other language) backgrounds tend to use the semicolon out of habit.
In general the semicolon does nothing. But if you are using the Jupyter Notebook (depending on your version), you might get a figure plotted twice. The semicolon at the end of your plot command prevents this:
df.plot();
Programmers of C, C++, and Java are habituated of using a semicolon to tell the compiler that this is the end of a statement, but for Python this is not the case.
The reason is that in Python, newlines are an unambiguous way of separating code lines; this is by design, and the way this works has been thoroughly thought through. As a result, Python code is perfectly readable and unambiguous without any special end-of-statement markers (apart from the newline).
As other answers point out, the semicolon does nothing there. It's a separator (e.g. print 1;print 2). But it does not work like this: def func():print 1;print 2;;print'Defined!' (;; is a syntax error). Out of habit, people tend to use it (as it is required in languages such as C/Java...).
Related
I can join lines in Python using semi-colon, e.g.
a=5; b=10
But why can't I do the same with for
x=['a','b']; for i,j in enumerate(x): print(i,":", j)
Because the Python grammar disallows it. See the documentation:
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
Semicolons can only be used to separate simple statements (not compound statements like for). And, really, there's almost no reason to ever use them even for that. Just use separate lines. Python isn't designed to make it convenient to jam lots of code onto one line.
The short (yet valid) answer is simply "because the language grammar isn't defined to allow it". As for why that's the case, it's hard if not impossible to be sure unless you ask whoever came up with that portion of the grammar, but I imagine it's due to readability, which is one of the goals of Python1.
Why would you ever want to write something obscure like that? Just split it up into multiple lines:
x = ['a','b']
for i,j in enumerate(x):
print(i, ":", j)
I would argue that this variant is much clearer.
1 From import this: Readability counts.
Because Guido van Rossum, the creator of Python, and other developers, don't actually like the "semicolons and braces" style of code formatting.
For a brief look at how they feel about these things, try:
from __future__ import braces
Statements in Python are supposed to be separated by blank lines, and compound statements in Python are supposed to be bounded by indentation.
The existence of ; and one-line compound statements (e.g. for i in x: print i) are meant to be only very limited concessions... and you can't combine them.
The grammar of Python does not allow this. It's a good answer, but what's the reason for it?
I think the logic behind the decision is the following: body of a for loop must be indented in order to be recognized. So, if we allow not a simple_stmt there, it would require a complex and easy-to-break indentation.
A compound statement consists of one or more ‘clauses’. A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines.
x=['a','b'];
This does not justify the clause definition and thus cannot be used as a part of a compound statement. Therefore you encounter error.
Try this.
x=['a','b']; [print(i,":", j) for i,j in enumerate(x)]
I have already read this: Why doesn't Python have multiline comments?
So in my IDLE , I wrote a comment:
Hello#World
Anything after the d of world is also a part of the comment.In c++ , I am aware of a way to close the comment like:
/*Mycomment*/
Is there a way to end a comment in Python?
NOTE: I would not prefer not to use the triple quotes.
You've already read there are no multiline comments, only single line. Comments cause Python to ignore everything until the end of the line. You "close" them with a newline!
I don't particularly like it, but some people use multiline strings as comments. Since you're just throwing away the value, you can approximate a comment this way. The only time it's really doing anything is when it's the first line in a function or class block, in which case it is treated as a docstring.
Also, this may be more of a shell scripting convention, but what's so bad about using multiple single line comments?
#####################################################################
# It is perfectly fine and natural to write "multi-line" comments #
# using multiple single line comments. Some people even draw boxes #
# with them! #
#####################################################################
You can't close a comment in python other than by ending the line.
There are number of things you can do to provide a comment in the middle of an expression or statement, if that's really what you want to do.
First, with functions you annotate arguments -- an annotation can be anything:
def func(arg0: "arg0 should be a str or int", arg1: (tuple, list)):
...
If you start an expression with ( the expression continues beyond newlines until a matching ) is encountered. Thus
assert (
str
# some comment
.
# another comment
join
) == str.join
You can emulate comments by using strings. They are not exactly comments, since they execute, but they don't return anything.
print("Hello", end = " ");"Comment";print("World!")
if you start with triple quotes, end with triple quotes
More and more we use chained function calls:
value = get_row_data(original_parameters).refine_data(leval=3).transfer_to_style_c()
It can be long. To save long line in code, which is prefered?
value = get_row_data(
original_parameters).refine_data(
leval=3).transfer_to_style_c()
or:
value = get_row_data(original_parameters)\
.refine_data(leval=3)\
.transfer_to_style_c()
I feel it good to use backslash \, and put .function to new line. This makes each function call has it own line, it's easy to read. But this sounds not preferred by many. And when code makes subtle errors, when it's hard to debug, I always start to worry it might be a space or something after the backslash (\).
To quote from the Python style guide:
Long lines can be broken over multiple lines by wrapping expressions
in parentheses. These should be used in preference to using a
backslash for line continuation. Make sure to indent the continued
line appropriately. The preferred place to break around a binary
operator is after the operator, not before it.
I tend to prefer the following, which eschews the non-recommended \ at the end of a line, thanks to an opening parenthesis:
value = (get_row_data(original_parameters)
.refine_data(level=3)
.transfer_to_style_c())
One advantage of this syntax is that each method call is on its own line.
A similar kind of \-less structure is also often useful with string literals, so that they don't go beyond the recommended 79 character per line limit:
message = ("This is a very long"
" one-line message put on many"
" source lines.")
This is a single string literal, which is created efficiently by the Python interpreter (this is much better than summing strings, which creates multiple strings in memory and copies them multiple times until the final string is obtained).
Python's code formatting is nice.
What about this option:
value = get_row_data(original_parameters,
).refine_data(leval=3,
).transfer_to_style_c()
Note that commas are redundant if there are no other parameters but I keep them to maintain consistency.
The not quoting my own preference (although see comments on your question:)) or alternatives answer to this is:
Stick to the style guidelines on any project you have already - if not stated, then keep as consistent as you can with the rest of the code base in style.
Otherwise, pick a style you like and stick with that - and let others know somehow that's how you'd appreciate chained function calls to be written if not reasonably readable on one-line (or however you wish to describe it).
Which is preferred ("." indicating whitespace)?
A)
def foo():
x = 1
y = 2
....
if True:
bar()
B)
def foo():
x = 1
y = 2
if True:
bar()
My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?
If you use A, you could copy paste your block in python shell, B will get unexpected indentation error.
The PEP 8 does not seem to be clear on this issue, although the statements about "blank lines" could be interpreted in favor of B. The PEP 8 style-checker (pep8.py) prefers B and warns if you use A; however, both variations are legal. My own view is that since Python will successfully interpret the code in either case that this doesn't really matter, and trying to enforce it would be a lot of work for very little gain. I suppose if you are very adamantly in favor of one or the other you could automatically convert the one to the other. Trying to fix all such lines manually, though, would be a huge undertaking and really not worth the effort, IMHO.
Adding proper indentation to blank lines (style A in the question) vastly improves code readability with display whitespace enabled because it makes it easier to see whether code after a blank line is part of the same indentation block or not.
For a language like Python, where there is no end statement or close bracket, I'm surprised this is not part of PEP. Editing Python with display whitespace on is strongly recommended, to avoid both trailing whitespace and mixed indentation.
Compare reading the following:
A)
def foo():
....x = 1
....y = 2
....
....if True:
........bar()
B)
def foo():
....x = 1
....y = 2
....if True:
........bar()
In A, it is far clearer that the last two lines are part of foo. This is even more useful at higher indentation levels.
That empty line belongs to foo(), so I would consider A to be the most natural. But I guess it's just a matter of opinion.
TextMate breaks block collapsing if you use B, and I prefer A anyway since it's more "logical".
My experience in open-source development is that one should never leave whitespace inside blank lines. Also one should never leave trailing white-space.
It's a matter of coding etiquette.
I wouldn't necessarily call the first example "broken", because I know some people hate it when the cursor "jumps back" when moving the cursor up or down in code. E.g. Visual Studio (at least 2008) automatically prevents this from happening without using any whitespace characters on those lines.
B is preferred - i.e. no indentation. PEP 8 says:
Avoid trailing whitespace anywhere. Because it's usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don't preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
Emacs does B) for me, but I really don't think it matters. A) means that you can add in a line at the correct indentation without any tabbing.
vi implicitly discourages the behaviour in A because the {/} navigations no longer work as expected. git explicitly discourages it by highlighting it in red when you run git diff. I would also argue that if a line contains spaces it is not a blank line.
For that reason I strongly prefer B. There is nothing worse than expecting to skip six or so lines up with the { motion and ending up at the top of a class def.
I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces?
You can try to add support for braces using a future import statement, but it's not yet supported, so you'll get a syntax error:
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Correct for code blocks. However, you do define dictionaries in Python using curly braces:
a_dict = {
'key': 'value',
}
Ahhhhhh.
Yes. Curly braces are not used. Instead, you use the : symbol to introduce new blocks, like so:
if True:
do_something()
something_else()
else:
something()
Python with Braces is a variant of python that lets you do exactly that.
It's a project that I've been working on lately together with my friend.
Use Whyton:
http://writeonly.wordpress.com/2010/04/01/whython-python-for-people-who-hate-whitespace/
Yup :)
And there's (usually) a difference between 4 spaces and a tab, so make sure you standardize the usage ..
Yes.
if True:
#dosomething
else:
#dosomething else
#continue on with whatever you were doing
Basically, wherever you would've had an opening curly brace, use a colon instead. Unindent to close the region. It doesn't take long for it to feel completely natural.
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Well that explains a lot.
Note however, that Python does natively support curly brace-d code blocks! Take a look at below:
if x: #{
x += 1
#}
For Ada or Pascal programmers, I take delight in revealing to you:
if x: #BEGIN
...
#END
Taken from the docs:
Python's parser is also sophisticated enough to recognize mixed
notations, and it will even catch missing beginning or end
delimiters and correct the program for the user. This allows the
following to be recognized as legal Python:
if x: #BEGIN
x = x + 1
#}
And this, for Bash users:
if x:
x=99
#fi
Even better, for programmers familiar with C, C++, etc. you can omit the curly braces completely for only one statement:
if x:
do_stuff()
Beautiful. As mentioned before, Python can also automatically correct code with incorrect delimiters, so this code is also legal:
if x:
do_a_hundred_or_more_statements()
x = x + 1
print(x)
As this must make you love Python even more, I send you off with one last quote from the docs.
Now as you can see from this series of examples, Python has
advanced the state of the art of parser technology and code
recognition capabilities well beyond that of the legacy languages.
It has done this in a manner which carefully balances good coding
style with the need for older programmers to feel comfortable with
look of the language syntax.
The only limitation is that these special delimiters be preceded by a hashtag symbol.
Python does not use curly braces for code blocks:
>>> while True {
File "<stdin>", line 1
while True {
^
SyntaxError: invalid syntax
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
(Notice the "not a chance" message – this is an Easter egg reflecting this design decision.)
As a language designed to be easy to use and read, Python uses colons and indentation to designate code blocks. Defining code blocks by indentation is unusual and can come as a surprise to programmers who are used to languages like C++ and C# because these (and many other languages) don't care about extra whitespace or indentation. This rule is intended to increase readability of Python code, at the cost of some of the programmer's freedom to use varying amounts of whitespace.
An increase in the indentation level indicates the start of a code block, while a decrease indicates the end of the code block. By convention, each indentation is four spaces wide.
Here's a simple example which sums all the integers from 0 to 9. Note that ranges in Python include the first value, up to but not including the last value:
j = 0
for i in range(0, 10):
j += i
print(j)
Yes you can use this library/package { Py }
Use curly braces instead of indenting, plus much more sugar added to Python's syntax.
https://pypi.org/project/brackets/
// Use braces in Python!
def fib(n) {
a, b = 0, 1
while (a < n) {
print(a, end=' ')
a, b = b, a+b
}
print()
}
/*
Powerful anonymous functions
*/
print([def(x) {
if(x in [0, 1]) {
return x
};
while (x < 100) {
x = x ** 2
};
return x
}(x) for x in range(0, 10)])
As others have mentioned, you are correct, no curly braces in Python. Also, you do not have no end or endif or endfor or anything like that (as in pascal or ruby). All code blocks are indentation based.
Yes, code blocks in Python are defined by their indentation. The creators of Python were very interested in self-documenting code. They included indentation in the syntax as a way of innately enforcing good formatting practice.
I programmed in Python for a few years and became quite fond of its code structure because it really is easier. Have you ever left out a closing curly brace in a large program and spent hours trying to find it? Not a problem in Python. When I left that job and had to start using PHP, I really missed the Python syntax.
I will give some thoughts about this question.
Admittedly at first I also thought it is strange to write code without curly braces. But after using Python for many years, I think it is a good design.
First, do we really need curly braces? I mean, as a human. If you are allowed to use curly braces in Python, won't you use indentation anymore? Of course, you will still use indentation! Because you want to write readable code, and indentation is one of the key points.
Second, when do we really need curly braces? As far as I think, we only strictly need curly braces when we need to minify our source code files. Like minified js files. But will you use Python in a situation that even the size of source code is sensitive? Also as far as I think, you won't.
So finally, I think curly braces are somehow like ;. It is just a historical issue, with or without it, we will always use indentation in Python.
In Python, four spaces() are used for indentation in place of curly braces ({). Though, curly braces are used at few places in Python which serve different purpose:
Initialize a non-empty set (unordered collection of unique elements):
fuitBasket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
Citation
Initialize an empty dictionary (key-value pairs):
telephoneNumbers = {}
Initialize a non-empty dictionary (key-value pairs):
telephoneNumbers = {'jack': 4098, 'sape': 4139}
Citation
In relation to format string, curly braces take on a different meaning. See https://docs.python.org/3/library/string.html?highlight=curly :
Format strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal
text, which is copied unchanged to the output. If you need to include
a brace character in the literal text, it can be escaped by doubling:
{{ and }}.