Python 7
Python 7
Python 7
Module II
Note-7
Python Loops
A loop statement allows us to execute a statement
or group of statements multiple times. There are
two types of loops in Python, for and while.
Syntax
for iterating_var in sequence:
statements
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Using else conditional statement with
for/while loop in python
while expression:
statement(s)
Example
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
Example:
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"
Loop Control Statements/Jump Statements
Loop control statements change execution from its normal
sequence. Python supports the following control statements.
break
continue
pass
break
It terminates the current loop and resumes
execution at the next statement. The break
statement can be used in both while and for loops.
The continue statement can be used in both while and for loops.
pass
The pass statement is used as a placeholder for future code.
When the pass statement is executed, nothing happens, but you avoid
getting an error when empty code is not allowed.
Syntax
range(start, stop, step)
Parameter Description
start Optional. An integer number specifying at which position to
start. Default is 0
stop Required. An integer number specifying at which position to
stop (not included).
step Optional. An integer number specifying the incrementation.
Default is 1
Example1: Output:
x = range(6) 0
1
2
for n in x:
3
print(n)
4
5
Example2:
x = range(3, 6)
for n in x:
print(n)
Output:
3
4
5
Example3:
Example4:
x = range(3, 20, 2) print("Get numbers from range 0 to 6")
for n in x: for i in range(6):
print(i, end=', ')
print(n)
Output Output
3 Python range() example
Get numbers from range 0 to 6
5 0, 1, 2, 3, 4, 5,
7
9
11
13
15
17
19