Python Lecture 12, 13
Python Lecture 12, 13
Lecture – 12 & 13
DISCOVER . LEARN . EMPOWER
Loops 1
COURSE OBJECTIVES
2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-
Identify and interpret the basics syntax of Python Programming Language and be fluent
CO1
in the use of Python.
Understanding the data structures like Lists, Tuples, Sets and Dictionaries in
CO3
programming paradigms of Python Programming Language.
Ability to create practical and contemporary applications using Functions, Abstract Data
CO4
Types and Modules in Python.
Implementation of Python based applications using file input and output operations in
CO5
Python Programming.
3
Unit-1 Syllabus
Introduction The Programming Cycle for Python, Elements of Python, Type Conversion.
Conditional Conditional Statement in Python (if-else statement, its working and execution),
Nested-if Statement and Else if Statement in Python, Expression Evaluation &
Statements Float Representation.
Purpose and working of Loops, While Loop including its Working, For Loop,
Loops Nested Loops, Break and Continue.
4
SUGGESTIVE READINGS
Text Books / Reference Books
TEXT BOOKS
T1: Allen B. Downey, “Think Python: How to Think Like a Computer Scientist” 2nd Edition, Version 2.4.0, O'Reilly Media, Inc.";
2012 Aug 13.
T2: Dierbach, Charles. Introduction to computer science using python: A computational problem-solving focus. Wiley
Publishing, 2012.
T3: Guido van Rossum and Fred L. Drake Jr, -An Introduction to Python - Revised and updated for Python 3.2, Network Theory
Ltd., 2011.
T4: Andreas C. Müller, Sarah Guido, ― "Introduction to Machine Learning with Python",O'Reilly Media, Inc.; 2016.
REFERENCE BOOKS
R1: Timothy A. Budd, ―Exploring Python, Mc-Graw Hill Education (India) Private Ltd. 2015.
R2: Kenneth A. Lambert, ―Fundamentals of Python: First Programs, CENGAGE Learning, 2012.
R3: Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem Solving Focus, Wiley India
Edition, 2013.
R4: Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using
Python 3, Second edition, Pragmatic Programmers, LLC, 2013.
5
Contents to be covered
Purpose and Working of Loops
For Loop
6
Purpose and Working of Loops
Loops in Python serve the purpose of repeating a block of code multiple times. They allow you to automate
repetitive tasks and operate efficiently on large sets of data. There are two main types of loops in Python: for
and while.
Purpose of Loops
Automation: Loops automate repetitive tasks by executing a block of code multiple times, reducing the need
for manual repetition.
Efficiency: They make code more efficient by avoiding redundancy, as the same set of instructions can be
applied iteratively.
Iterating Over Sequences: Loops are commonly used for iterating over elements in a sequence, such as lists,
strings, or tuples.
Data Processing: Loops are crucial for processing large datasets, enabling the application of the same logic to
each item in the dataset.
7
While Loop including its Working in Python: In Python, a while loop is used to execute a block of
statements repeatedly until a given condition is satisfied. When the condition becomes false, the line
immediately after the loop in the program is executed.
While Loop Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
Example of Python While Loop: Let’s see a simple example of while loop in Python. The given Python code
uses a ‘while' loop to print “Hello” three times by incrementing a variable called ‘count' from 1 to 3.
count = 0
while (count < 3):
count = count + 1
8
print("Hello")
Using else statement with While Loop in Python: The else clause is only executed when your while condition
becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Examples of While Loop with else statement: The code prints “Hello” three times using a ‘while' loop and
then, after the loop, it prints “In Else Block” because there is an “else” block associated with the ‘while' loop.
count = 0
while (count < 3):
count = count + 1
print("Hello ")
else:
9
print("In Else Block")
Infinite While Loop in Python: If we want a block of code to execute infinite number of time, we can use
the while loop in Python to do so.
The code uses a ‘while' loop with the condition (count == 0). This loop will only run as long as count is equal
to 0. Since count is initially set to 0, the loop will execute indefinitely because the condition is always true.
count = 0
while (count == 0):
print("Hello Geek")
10
For Loop in Python: For loops are used for sequential traversal. For example: traversing a list or string or
array etc. In Python, there is “for in” loop which is similar to foreach loop in other languages. Let us learn
how to use for loop in Python for sequential traversals with examples.
For Loop Syntax:
for iterator_var in sequence:
statements(s)
11
Example with List, Tuple, String, and Dictionary Iteration Using for Loops in Python: We can use for loop to
iterate lists, tuples, strings and dictionaries in Python.
The code showcases different ways to iterate through various data structures in Python. It demonstrates
iteration over lists, tuples, strings, dictionaries, and sets, printing their elements or key-value pairs.
The output displays the contents of each data structure as it is iterated.
print("List Iteration")
l = [“good", "for", “good"]
for i in l:
print(i)
print("\nTuple Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i)
12
Nested Loops, Break and Continue in Python: Python programming language allows to use one loop
inside another loop which is called nested loop. Following section shows few examples to illustrate the
concept.
Nested Loops Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example,
13
Loop Control Statements: Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports
the following control statements.
Continue Statement: The continue statement in Python returns the control to the beginning of the loop.
Example: This Python code iterates through the characters of the string ‘geeksforgeeks’. When it encounters
the characters ‘e’ or ‘s’, it uses the continue statement to skip the current iteration and continue with the next
character. For all other characters, it prints “Current Letter :” followed by the character. So, the output will
display all characters except ‘e’ and ‘s’, each on a separate line.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
14
Break Statement: The break statement in Python brings control out of the loop.
Example: In this Python code, it iterates through the characters of the string ‘geeksforgeeks’. When it
encounters the characters ‘e’ or ‘s’, it uses the break statement to exit the loop. After the loop is terminated, it
prints “Current Letter :” followed by the last character encountered in the loop (either ‘e’ or ‘s’). So, the
output will display “Current Letter :” followed by the first occurrence of ‘e’ or ‘s’ in the string.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break
15
Pass Statement: We use pass statement in Python to write empty loops. Pass is also used for empty control
statements, functions and classes.
Example: This Python code iterates through the characters of the string ‘geeksforgeeks’ using a ‘for' loop.
However, it doesn’t perform any specific action within the loop, and the ‘pass' statement is used. After the
loop, it prints “Last Letter :” followed by the last character in the string, which is ‘s’.
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output
Last Letter : s
16
Summary
While Loop and its Working: The while loop is a pre-test loop that repeatedly executes a block of code as
long as a specified condition is true. The working of a while loop involves checking the condition before each
iteration. If the condition evaluates to true, the loop body is executed; otherwise, the loop terminates.
For Loop: The for loop is used for iterating over a sequence (such as a list, tuple, or string) or other iterable
objects. Unlike the while loop, the for loop iterates over a predefined range or set of values. It simplifies the
process of iterating through elements in a collection.
Nested Loops: Nested loops involve placing one loop inside another. This allows for more complex
iterations, such as iterating through elements in a matrix or multi-dimensional list. Each inner loop completes
its iterations for every single execution of the outer loop.
Break and Continue: The break statement is used to prematurely exit a loop, regardless of whether the loop
condition is satisfied. It is commonly used to terminate a loop when a specific condition is met. On the other
hand, the continue statement skips the rest of the code in a loop for the current iteration and proceeds to the
next iteration.
17
Assessment Questions
Q What is the primary purpose of using loops in Python?
Q How do loops contribute to the efficiency of a program?
Q Provide examples of real-world scenarios where loops are beneficial.
Q In what situations would you prefer using loops over other control flow structures?
Q Explain the basic structure of a while loop in Python.
Q How does the while loop decide when to terminate?
Q Walk through the step-by-step execution of a simple while loop.
Q What happens if the condition of a while loop is initially false?
Q Describe the syntax and basic functionality of a for loop.
Q What types of objects can be iterated using a for loop?
Q Provide an example of using a for loop to iterate over a list.
18
Assessment Questions
Q How does the range() function contribute to the for loop?
Q Explain the concept of nested loops.
Q When might you choose to use nested loops in Python?
Q Provide a practical example of using nested loops, such as iterating through a 2D list.
Q What challenges or considerations should be kept in mind when working with nested loops?
Q Describe the purpose of the break statement in a loop.
Q Provide a scenario where using break would be appropriate.
Q Explain how the continue statement works in the context of a loop.
Q When might using continue improve the efficiency of a loop?
19
THANK YOU
For queries
Email: [email protected]
20