4.9. Intermezzo: Coding Style¶
Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about coding style. Most languages can be written (or more
concise, formatted) in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.
For Python, PEP 8 has emerged as the style guide that most projects adhere to;
it promotes a very readable and eye-pleasing coding style. Every Python
developer should read it at some point; here are the most important points
extracted for you:
-
Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater
nesting depth) and large indentation (easier to read). Tabs introduce
confusion, and are best left out. -
Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several
code files side-by-side on larger displays. -
Use blank lines to separate functions and classes, and larger blocks of
code inside functions. -
When possible, put comments on a line of their own.
-
Use docstrings.
-
Use spaces around operators and after commas, but not directly inside
bracketing constructs: . -
Name your classes and functions consistently; the convention is to use
for classes and for functions
and methods. Always use as the name for the first method argument
(see for more on classes and methods). -
Don’t use fancy encodings if your code is meant to be used in international
environments. Python’s default, UTF-8, or even plain ASCII work best in any
case. -
Likewise, don’t use non-ASCII characters in identifiers if there is only the
slightest chance people speaking a different language will read or maintain
the code.
Footnotes
4.3. The range() Function¶
If you do need to iterate over a sequence of numbers, the built-in function
comes in handy. It generates arithmetic progressions:
>>> for i in range(5): ... print(i) ... 1 2 3 4
The given end point is never part of the generated sequence; generates
10 values, the legal indices for items of a sequence of length 10. It
is possible to let the range start at another number, or to specify a different
increment (even negative; sometimes this is called the ‘step’):
>>> list(range(5, 10)) >>> list(range(, 10, 3)) >>> list(range(-10, -100, -30))
To iterate over the indices of a sequence, you can combine and
as follows:
>>> a = 'Mary', 'had', 'a', 'little', 'lamb' >>> for i in range(len(a)): ... print(i, ai]) ... 0 Mary 1 had 2 a 3 little 4 lamb
In most such cases, however, it is convenient to use the
function, see .
A strange thing happens if you just print a range:
>>> range(10) range(0, 10)
In many ways the object returned by behaves as if it is a list,
but in fact it isn’t. It is an object which returns the successive items of
the desired sequence when you iterate over it, but it doesn’t really make
the list, thus saving space.
We say such an object is , that is, suitable as a target for
functions and constructs that expect something from which they can
obtain successive items until the supply is exhausted. We have seen that
the statement is such a construct, while an example of a function
that takes an iterable is :
>>> sum(range(4)) # 0 + 1 + 2 + 3 6
4.4. break and continue Statements, and else Clauses on Loops¶
The statement breaks out of the innermost enclosing
or loop.
A or loop can include an clause.
In a loop, the clause is executed
after the loop reaches its final iteration.
In a loop, it’s executed after the loop’s condition becomes false.
In either kind of loop, the clause is not executed
if the loop was terminated by a .
This is exemplified in the following loop,
which searches for prime numbers:
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == ... print(n, 'equals', x, '*', n//x) ... break ... else ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
(Yes, this is the correct code. Look closely: the clause belongs to
the loop, not the statement.)
When used with a loop, the clause has more in common with the
clause of a statement than it does with that of
statements: a statement’s clause runs
when no exception occurs, and a loop’s clause runs when no
occurs. For more on the statement and exceptions, see
.
The statement, also borrowed from C, continues with the next
iteration of the loop:
Старая и новая редакции
- ← Предыдущее
- Следующее →
Выберите год учебника
● Все года
Вопрос
№40 учебника 2011-2022 (стр. 28):
Прочитайте. Составьте из слов каждой группы предложения так: сначала подберите слова, которые будут главными членами предложения, потом – слова, которые будут их пояснять.
1. Лето, уже, красное, прошло.
2. Журавли, тёплые, улетели, в, стра́ны.
3. Спрятался, ёж, в, гнездо, под, сосны, корнями.
4. Скрылись, в, деревьев, кору, жуки.
5. Змеи, в, тёплый, зарылись, мох, и, ящерицы.
6. Выбрал, место, для, медведь, берлоги.
- Запишите составленные предложения. Какой темой их можно объединить? Дополните текст ещё одним предложением на эту же тему.
- Подчеркните во втором предложении главные члены. Скажите, какую роль выполняют в этом предложении второстепенные члены.
№40 учебника 2023-2024 (стр. 27):
Прочитайте. Сравните первое и второе предложения. Объясните, чем они отличаются.
- Стрижи улетели.
- Быстрокрылые стрижи давно улетели на юг.
- Какое предложение является распространённым, а какое – нераспространённым? Спишите распространённое предложение. Подчеркните в нём подлежащее и сказуемое.
- Какой (какие) из второстепенных членов этого предложения поясняет (уточняет) сказуемое? подлежащее? Поставьте вопрос к каждому второстепенному члену предложения.
Подсказка
№40 учебника 2011-2022 (стр. 28):
Главные члены предложения подчеркни так: подлежащее и сказуемое.
№40 учебника 2023-2024 (стр. 27):
Нераспространённое предложение состоит только из главных членов (подлежащее и сказуемое), а распространённое из главных и второстепенных.
Ответ
№40 учебника 2011-2022 (стр. 28):
1. Прошло лето красное уже.
2. Журавли улетели в тёплые страны. (втор. члены поясняют сказуемое и другой член предложения, дают дополнительную информацию)
3. Ёж спрятался в гнездо под корнями сосны.
4. Жуки скрылись в кору деревьев.
5. Змеи и ящерицы зарылись в тёплый мох.
6. Медведь выбрал место для берлоги.
Тема: осенняя подготовка зверей к зиме
Дополнительное предложение: Белки делают запасы на зиму.
Пояснения:
первое предложение, которое вы будете составлять будет звучать так: Прошло лето красное уже. Правильнее было бы написать иначе: Уже прошло красное лето. Однако, в задании упражнения вам сказано составить предложение так: сначала подберите слова, которые будут главными членами предложения, потом – слова, которые будут их пояснять. Если следовать данным указаниям, то предложение будет звучать так, как мы его записали.
№40 учебника 2023-2024 (стр. 27):
Первое предложение состоит только из подлежащего и сказуемого, следовательно оно является нераспространённым. Второе предложение состоит из подлежащего, сказуемого и второстепенных членов, следовательно оно — распространённое.
Быстрокрылые стрижи давно улетели на юг.
Сказуемое в данном предложении уточняют второстепенные члены, выраженные словами «давно» и «на юг». Подлежащее, в данном предложении, уточняет второстепенный член, выраженный словом «быстрокрылые». Вопросы к второстепенным членам:
- ← Предыдущее
- Следующее →
4.2. for Statements¶
The statement in Python differs a bit from what you may be used
to in C or Pascal. Rather than always iterating over an arithmetic progression
of numbers (like in Pascal), or giving the user the ability to define both the
iteration step and halting condition (as C), Python’s statement
iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence. For example (no pun intended):
>>> # Measure some strings: ... words = 'cat', 'window', 'defenestrate' >>> for w in words ... print(w, len(w)) ... cat 3 window 6 defenestrate 12
Code that modifies a collection while iterating over that same collection can
be tricky to get right. Instead, it is usually more straight-forward to loop
over a copy of the collection or to create a new collection:
4.7. Defining Functions¶
We can create a function that writes the Fibonacci series to an arbitrary
boundary:
>>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = , 1 ... while a < n ... print(a, end=' ') ... a, b = b, a+b ... print() ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
The keyword introduces a function definition. It must be
followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and
must be indented.
The first statement of the function body can optionally be a string literal;
this string literal is the function’s documentation string, or docstring.
(More about docstrings can be found in the section .)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; it’s good
practice to include docstrings in code that you write, so make a habit of it.
The execution of a function introduces a new symbol table used for the local
variables of the function. More precisely, all variable assignments in a
function store the value in the local symbol table; whereas variable references
first look in the local symbol table, then in the local symbol tables of
enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables and variables of enclosing functions
cannot be directly assigned a value within a function (unless, for global
variables, named in a statement, or, for variables of enclosing
functions, named in a statement), although they may be
referenced.
The actual parameters (arguments) to a function call are introduced in the local
symbol table of the called function when it is called; thus, arguments are
passed using call by value (where the value is always an object reference,
not the value of the object). When a function calls another function,
or calls itself recursively, a new
local symbol table is created for that call.
A function definition associates the function name with the function object in
the current symbol table. The interpreter recognizes the object pointed to by
that name as a user-defined function. Other names can also point to that same
function object and can also be used to access the function:
>>> fib <function fib at 10042ed0> >>> f = fib >>> f(100) 0 1 1 2 3 5 8 13 21 34 55 89
Coming from other languages, you might object that is not a function but
a procedure since it doesn’t return a value. In fact, even functions without a
statement do return a value, albeit a rather boring one. This
value is called (it’s a built-in name). Writing the value is
normally suppressed by the interpreter if it would be the only value written.
You can see it if you really want to using :
>>> fib() >>> print(fib()) None
It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it:
>>> def fib2(n): # return Fibonacci series up to n ... """Return a list containing the Fibonacci series up to n.""" ... result = [] ... a, b = , 1 ... while a < n ... result.append(a) # see below ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result
This example, as usual, demonstrates some new Python features: