Prev: - 'for' loop | Next: -
'for' loop requires a powerful iterable structure that can return the needed sequence of values in a fast, reliably and memory efficiently. Such a structure is provided by the range() function
The general syntax of the 'for' loop when using a range() is:
for iterator in range(start, end [,step])
block-1
else:
block-2
- start: the first value of the sequence; if not defined then '0' is assumed
- end: the last value of the interval BUT NOT included in the sequence
- step (optional): if included it defines the step at which the values are produced starting from 'start' and ending at the value closest to 'end' but without exceeding it
'range' in its basic form accepts only integer values as start, end, step arguments. See the examples below:
for i in range(10):
print(i, end=' ')
for i in range(1,11):
print(i, end=' ')
for i in range(5,12):
print(i, end=' ')
for i in range(-5,0):
print(i, end=' ')
for i in range(0,10,2):
print(i, end=' ')
for i in range(0,10,3):
print(i, end=' ')
a=5;b=10;c=3
for i in range(a,b,c):
print(i, end=' ')
a=10; b=100; c=b//a
for i in range(a,b,c):
print(i, end=' ')
x = range(1,10)
for i in x:
print(i, end=' ')
for x in range(10,5,-1):
print(x, end=' ')
for x in range(10,2,-3):
print(x, end=' ')
for i in range(10):
i += 10 * i
print(i, end=' ')
- ord(): returns the ascii integer code of a character
- chr(): returns the ascii character of a given integer code
for ch in range(ord('a'), ord('z')):
print(chr(ch), end=' ')
. Free learning material
. See full copyright and disclaimer notice