Python 7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Python Programming

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.

Python For Loops


A for loop is used for iterating over a sequence (that is either a list,
a tuple, a dictionary, a set, or a string).

Syntax
for iterating_var in sequence:
statements
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

Looping Through a String


Even strings are iterable objects, they contain a sequence of
characters:

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

In most of the programming languages (C/C++, Java,


etc), the use of else statement has been restricted
with the if conditional statements. But Python also
allows us to use the else condition with for loops.

The else block just after for/while is executed only


when the loop is NOT terminated by a break
statement.
Syntax
for iterating_var in sequence:
statements
else:
statements
Example:
for ch in ‘Kerala’:
print(ch)
else:
print(‘end of loop’)
# Python program to check if an array consists
# of even number
def contains_even_number(l):
for ele in l:
if ele % 2 == 0:
print ("list contains an even number")
break

# This else executes only if break is NEVER


# reached and loop terminated after all iterations.
else:
print ("list does not contain an even number")

print ("For List 1:")


contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])
while loop
With the while loop we can execute a set of statements as
long as a condition is true.

The syntax of a while loop in Python programming language is −

while expression:
statement(s)
Example
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1

print ("Good bye!“)


Example
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5“
OUTPUT
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
If your while clause consists only of a single statement, it may be
placed on the same line as the while header.

Here is the syntax and example of a one-line while clause −

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.

If you are using nested loops, the break statement


stops the execution of the innermost loop and start
executing the next line of code after the block.
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
OUTPUT
Current Letter : P
var = 10 # Second Example Current Letter : y
while var > 0: Current Letter : t
Current variable value : 10
print 'Current variable value :', var Current variable value : 9
var = var -1 Current variable value : 8
Current variable value : 7
if var == 5: Current variable value : 6
break Good bye!

print "Good bye!"


continue
It returns the control to the beginning of the while loop.. The continue
statement rejects all the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop.

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.

Empty code is not allowed in loops, function definitions, class


definitions, or in if statements.
Example:
a = 33
b = 200
if b > a:
pass
The range() function
range() is a built-in function of Python. It is used when a user needs to
perform an action for a specific number of times. The range() function returns
a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Most common use of range() function in Python is to iterate sequence type
(List, string etc.. ) with for and while loop.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy