Вопрос №25156 от пользователя Ekaterina Lopatina в уроке «Условия и принятия решений», курс «Введение в программирование»
Коллеги, день добрый. Код правильный, тест проходит. Но выводит другие ошибки.
Вот такие ошибки выводит
В чем проблем, помогите разобраться, пожалуйста
Проблема, на мой взгляд начинающего программиста, заключается в том, что при использовании больше одного if, последующая конструкция if должна превратится в else if. То есть перед вторым и третьим if следует прописать слово else. UPD Оказывается (посмотрел решение учителя), что и не нужно тут else if’ов :-). Тогда, что можно сказать, каждый if с новой строки начинать, а не продолжать после > (я так понимаю, ругается на плохую читаемость кода, что if’ы на одном уровне, а то, что выполняется должно быть на другом уровне; а получилось, что второй и третий if заняли места их же return’ов) И удалить пустую строку перед export.
Переведите и проанализируйте описание. При необходимости загуглите по названию ошибки semi eslint и почитайте документацию с примерами. Исправьте ошибку и запустите повторную проверку линтера.
Я понимаю, что это нужно исправлять. Однако, я не понимаю что именно здесь нужно исправлять, ибо:
/usr/src/app/finalGrade.js\ 15:27 error Newline required at end of file but not found eol-last
Поэтому я и прошу помощи разобраться, ведь даже запуская решение учителя, выдаются те же ошибки линтера
Ого! Мы разобрали, как работать с линтером на примере ошибок системного файла. К вашему коду они не имеют отношения. Поправил ошибку в среде исполнения. Вам нужно получить последнюю версию практики, нажав кнопку Сброс, и после этого проработать замечания линтера повторно.
blank line at end of file #40
Comments
DXist commented Nov 2, 2011
The text was updated successfully, but these errors were encountered:
We are unable to convert the task to an issue at this time. Please try again.
The issue was successfully created but we are unable to update the comment at this time.
florentx commented Mar 25, 2012
pep8.py correctly detects ‘\n\n’ at end of file with warning W391.
It does not find any error if the file ends with ‘\n’ only.
I don’t see any misbehaviour here.
DXist commented Mar 26, 2012
I’ve installed pep8 0.7.0 from PyPI.
So pep8 from PyPI still has this problem
florentx commented Mar 26, 2012
You did not do the right test.
DXist commented Mar 26, 2012
Right. So I close the issue.
techtonik commented May 22, 2012
DXist commented May 22, 2012
techtonik commented May 22, 2012
Actually it is more typing, because without \n\n in Vim you can not just go to the end of file an press enter. You enter will at the start of the last line. It suxx that PEP8 validator forces everybody to this annoyance.
DXist commented May 22, 2012
You can type o command to start new line after you go to the end of file
techtonik commented May 22, 2012
Yes, I can, but I forget all the time.
techtonik commented May 22, 2012
And still PEP8 doesn’t require that files should not end with blank lines.
florentx commented May 23, 2012
I understand each developer has its habits.
I use Vim, and I regularly check my code with pep8.py. I don’t see a problem with the default settings.
techtonik commented May 23, 2012
Of course developers have habits. Why make it more harder for other people if doesn’t make any difference for yourself? Will the presence of \n\n endspace instead of \n bug you more than absence of \n\n bugs me, DXist and other people? You still can apply your rule to count(‘\n’) > 2
jorgesumle commented Sep 6, 2016
The-Compiler commented Sep 7, 2016
@jorgesumle So turn it off? I find it useful.
techtonik commented Sep 7, 2016
I remember there was some unix story about those linefeeds at the end of file, so this must be some unix kludge from the past and now is a cargo ritual. =)
DXist commented Sep 7, 2016 •
So the last new line is important for diff tools (including Github) and must have for C/C++. I guess early C development toolchain incorrectly handled the last line without line terminator symbols.
I think new line at the end of file is a part of best practices and I dislike editors/IDEs that don’t put last new line by default. Rituals support common and clear coding style.
What’s the significance of the «No newline at end of file» log?
When doing a git diff it says «No newline at end of file».
What’s the significance of the message and what’s it trying to tell us?
13 Answers 13
That is, simply speaking, the last byte (or bytes if you’re on Windows) in the file is not a newline.
The message is displayed because otherwise there is no way to tell the difference between a file where there is a newline at the end and one where is not. Diff has to output a newline anyway, or the result would be harder to read or process automatically.
Note that it is a good style to always put the newline as a last character if it is allowed by the file format. Furthermore, for example, for C and C++ header files it is required by the language standard.
It’s not just bad style, it can lead to unexpected behavior when using other tools on the file.
There is no newline character on the last line. Let’s see how many lines are in the file:
Maybe that’s what you want, but in most cases you’d probably expect there to be 2 lines in the file.
Also, if you wanted to combine files it may not behave the way you’d expect:
Finally, it would make your diffs slightly more noisy if you were to add a new line. If you added a third line, it would show an edit to the second line as well as the new addition.
The only reason is that Unix historically had a convention of all human-readable text files ending in a newline. At the time, this avoided extra processing when displaying or joining text files, and avoided treating text files differently to files containing other kinds of data (eg raw binary data which isn’t human-readable).
Because of this convention, many tools from that era expect the ending newline, including text editors, diffing tools, and other text processing tools. Mac OS X was built on BSD Unix, and Linux was developed to be Unix-compatible, so both operating systems have inherited the same convention, behaviour and tools.
Windows wasn’t developed to be Unix-compatible, so it doesn’t have the same convention, and most Windows software will deal just fine with no trailing newline.
But, since Git was developed for Linux first, and a lot of open-source software is built on Unix-compatible systems like Linux, Mac OS X, FreeBSD, etc, most open-source communities and their tools (including programming languages) continue to follow these conventions.
There are technical reasons which made sense in 1971, but in this era it’s mostly convention and maintaining compatibility with existing tools.
Easiest way to ignore blank lines when reading a file in Python
I have some code that reads a file of names and creates a list:
Each name is separated by a newline, like so:
I want to ignore any lines that contain only whitespace. I know I can do this by by creating a loop and checking each line I read and then adding it to a list if it’s not blank.
I was just wondering if there was a more Pythonic way of doing it?
10 Answers 10
I would stack generator expressions:
Now, lines is all of the non-blank lines. This will save you from having to call strip on the line twice. If you want a list of lines, then you can just do:
You can also do it in a one-liner (exluding with statement) but it’s no more efficient and harder to read:
Update:
I agree that this is ugly because of the repetition of tokens. You could just write a generator if you prefer:
update 2:
and on CPython (with deterministic reference counting)
In Python 2 use itertools.ifilter if you want a generator and in Python 3, just pass the whole thing to list if you want a list.
You could use list comprehension:
To avoid calling line.strip() twice, you can use a generator:
If you want you can just put what you had in a list comprehension:
names_list = [line for line in open(«names.txt», «r»).read().splitlines() if line]
splitlines() has already removed the line endings.
I don’t think those are as clear as just looping explicitly though:
Although, filter looks quite readable and concise:
names_list = filter(None, open(«names.txt», «r»).read().splitlines())
I guess there is a simple solution which I recently used after going through so many answers here.
This just does the same work, ignoring all empty line.
When a treatment of text must be done to just extract data from it, I always think first to the regexes, because:
as far as I know, regexes have been invented for that
iterating over lines appears clumsy to me: it essentially consists to search the newlines then to search the data to extract in each line; that makes two searches instead of a direct unique one with a regex
way of bringing regexes into play is easy; only the writing of a regex string to be compiled into a regex object is sometimes hard, but in this case the treatment with an iteration over lines will be complicated too
For the problem discussed here, a regex solution is fast and easy to write:
I compared the speeds of several solutions:
Solution with regex is straightforward and neat. Though, it isn’t among the fastest ones. The solution of aaronasterling with filter() is surprisigly fast for me (I wasn’t aware of this particular filter()’s speed) and times of optimized solutions go down until 27 % of the biggest time. I wonder what makes the miracle of the filter-splitlines association:
But this problem is particular, the most simple of all: only one name in each line. So the solutions are only games with lines, splitings and [0:-1] cuts.
On the contrary, regex doesn’t matter with lines, it straightforwardly finds the desired data: I consider it is a more natural way of resolution, applying from the simplest to the more complex cases, and hence is often the way to be prefered in treatments of texts.
I forgot to say that I use Python 2.7 and I measured the above times with a file containing 500 times the following chain
Why is it recommended to have empty line in the end of a source file?
Some code style tools recommend this and I remember seeing some unix command line tools warning about missing empty line.
What is the reasoning for having an extra empty line?
9 Answers 9
Many older tools misbehave if the last line of data in a text file is not terminated with a newline or carriage return / new line combination. They ignore that line as it is terminated with ^Z (eof) instead.
If you try to concatenate two text files together, you will be much happier if the first one ends with a newline character.
Apart from the fact that it is a nicer cursor position when you move to the end of a file in a text editor.
Having a newline at the end of the file provides a simple check that the file has not been truncated.
An argument can also be made for cleaner diffs if you append to the file following the same reasoning as Why are trailing commas allowed in a list?
The following is copied (and trimmed a bit) from the linked resource:
involves only a one-line change in the diff:
This beats the more confusing multi-line diff when the trailing comma was omitted:
The empty line in the end of file appears so that standard reading from the input stream will know when to terminate the read, usually returns EOF to indicate that you have reached the end. The majority of languages can handle the EOF marker. It is there for that reason from the old days, under DOS, the EOF marker was F6 key or Ctrl-Z, for *nix systems, it was Ctrl-D.
Most, if not all, will actually read right up to the EOF marker so that the runtime library’s function of reading from input will know when to stop reading any further. When you open the stream for Append mode, it will wipe the EOF marker and write past it, until a close is explicitly called in which it will insert the EOF marker at that point.
Older tools were expecting a empty line followed by EOF marker. Nowadays, tools can handle the empty line and ignore it.
Some languages define their input file in terms of input lines, where each input line is a series of characters terminated by a carriage return. If their grammar is so defined, then the last valid line of the file must be terminated by a carriage return too.
It’s because of the definition of what a text file is. When you create a new text file in any unix environment, the contents of that file is the new line character ‘\n’
Without this, the file isn’t really identified as a text file. Now once we add code to this text file, its about not removing this initial new line that defines a text file itself.
The question, and most of the existing answers, seem to be based on a misconception.
The ASCII control character commonly referred to as «newline» (U+000A LINE FEED, \n in C) does not start a new line of a (Unix-style) text file. It ends the current line of a text file. If the last character of a text file is U+000A, there is not an empty line «in between» the U+000A and the filesystem’s EOF marker (however that is implemented). Conversely, if the last character of a (nonempty) text file is not U+000A, the last line of the file has not been ended—it is said to be «incomplete».
This would probably be clearer with some examples:
This file contains two complete lines of text. It does not contain a third empty line.
This file contains a third empty line.
And this file contains only one complete line, plus a second incomplete line.
However, older text-processing tools often mishandle incomplete final lines. For instance, some implementations of wc won’t count an incomplete final line as a line, and some implementations of vi will silently add a newline to a file that doesn’t end with one, whether you want it to or not. Therefore, you should only use incomplete final lines when you have a specific reason to need them.
(Note: As far as I know, everything I just said is also true of DOS-style text files, where the two-byte control sequence U+000D U+000A is used to end a line, instead of just U+000A.)






