Alterna · учебный материал

Cycle for andrange

36.1: Cycle for and ring: Short theory, one example, and Python step-by-step.

Что в этом материале

Содержание и основные понятия

PY
Example: sum of numbers from 1 to 3
Range
range(1, 4)
The number is added to the battery at each step
total
; programme output 6.
total = 0
for i in range(1, 4):
total += i
print(total)
This example can be read without JavaScript. Below, the same program is available for launch and step-by-step review.
For resets the complete sequence of values. the sequence(s, step, step) includes the step but does not include the step.
substance and practice
Grade 8
OGE No. 6
OGE No. 16
EGE No. 25
01
How it works.
For easy to apply when a set of values has already been set: number of range, string symbols, list elements.range creates an arithmetic sequence with the unset right line.
range(stop).
Gives 0, 1, ...stop - 1.
range(start, stop).
Starts with the start and doesn't reach the step.
range(start, stop, step).
The step cannot be zero; if the step is negative, the step shall be greater than step.
Battery.
A change of amount, a work or a meter is given an initial value before the cycle.
02
One example in execution
Start the short program and go over the lines. The visualiser only shows the code, current line, variables and output.
To turn on
n
In an increasing range, write
range(1, n + 1)
The empty range is a normal case: the body will never be fulfilled. Inside the cycle
i
If you need an index and an element at the same time, use it.
enumerate
.
Algorithm map
Read from left to right, then run the code.
1
Start
2
total = 0
3
Take the following i from the ring
4
Add i to total
5
Remove total
03
Remember
Check n = 0 and n = 1: The range may be empty.
Don't confuse the ring(1, n) and the ring (1, n + 1).
Use a negative step to reverse the count, e.g. ring(n, 0,-1).
Syntax of this page
for name in sequence:
In turn, it links name to every element of security.
range(stop)
The range is 0 to step without step.
range(start, stop, step)
The range with a clear start and step; step is not 0.
enumerate(sequence, start=0)
Retracts the index and the element.
+=
Abbreviated update: total +=value is equivalent to total = total+value.
%
Allows you to filter even values.
int(input())
Reads the range.
print
Completes the accumulated response.

Structural map of textbooks