ProgFund Lect Week 5

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

Programming Fundamentals

(SWE –102)

ITERATION WITH LOOPS


What is Loop: Introduction
• A loop can be used to tell a program to execute
statements repeatedly
• Suppose that you need to display a string (e.g.,
Programming is fun!) 100 times. It would be
tedious to type the statement 100 times:
• print("Programming is fun!")
• print("Programming is fun!")
100 times
• ...
• print("Programming is fun!")
How do you solve this problem ?
• Python provides a powerful construct called a
loop, which controls how many times in
succession an operation (or a sequence of
operations) is performed.
• By using a loop statement, you don’t have to
code the print statement a hundred times;
you simply tell the computer to display a
string that number of times.
How do you solve this problem ?
• A loop is a construct that controls the
repeated execution of a block of statements.
• A loop can be used to tell a program to
execute statements repeatedly. In other word,
to keep a computer doing useful work we
need repetition, looping back over the same
block of code again and again.
Type of Loop Statements in Python:
• There are two types of loop statements in Python
language. They are,
1. for
2. while
• The for loop is a count-controlled loop that
repeats a specified number of times.
• The while loop is a condition-controlled loop; it is
• controlled by a true/false condition.
The for Loop
• A Python for loop iterates through each value
in a sequence.
• Often you know exactly how many times the
loop body needs to be executed, so a control
variable can be used to count the executions.
A loop of this type is called a counter-
controlled loop.
The for Loop: Syntax
• In general, the syntax of a for loop is:
• for var in sequence:
# Loop body
a) for i in range(endValue):
#Loop body
b) for i in range(initialValue, endValue):
# Loop body
c) for i in range(initialValue, endValue,k):
#k=step value
# Loop body
How for loop works:
• A ‘sequence’ holds multiple items of data,
stored one after the other. In sequence
introduce strings and data storing techniques.
They are sequence-type objects in Python.
• The statements in the body of the loop are
executed once for each value.
• Generate a sequence of numbers using
‘range() function’, range(10) will generate
numbers from 0 to 9 (10 numbers).
How for loop works:
• The variable var takes on each successive
value in the sequence, and the statements in
the body of the loop are executed once for
each value.
• The function range(a, b) returns the sequence
of integers a, a + 1, ..., b - 2, and b -1.
Example program for ‘for loop’ using
sequence(string):
- for letter in 'Python':
print ('Current Letter :', letter)
Output:
>>>
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Example program for ‘for loop’ using
range( )’:
• # Simple for loop using range()
- for i in range(1,6):
print("Programming is fun")
Output:
>>>
Programming is fun
Programming is fun
Programming is fun
Programming is fun
Programming is fun
How for loop works:
• >>> for v in range(4, 8):
• print(v)
• Output:
• 4
• 5
• 6
• 7
• >>>
How for loop works:
• The range function has two more versions.
You can also use range(a) or range(a,b,k).
range(a) is the same as range(0, a).
• k is used as step value in range(a, b, k). The
first number in the sequence is a. Each
successive number in the sequence will
increase by the step value k. b is the limit. The
last number in the sequence must be less than
b.
How for loop works:
• >>> for v in range(3, 9, 2):
• print(v)
• Output:
• 3
• 5
• 7
How for loop works:
• The step value in range (3, 9, 2) is 2, and the
limit is 9. So, the sequence is 3, 5, and 7.
• The range(a, b, k) function can count
backward if k is negative. In this case, the
sequence is still a, a + k, a + 2k, and so on for a
negative k. The last number in the sequence
must be greater than b.
Practice Question
• >>> for v in range(5, 1, -1):
• ... print(v)

Output:
The while Loop
• A while loop executes statements repeatedly
as long as a condition remains true.
• The syntax for the while loop is:
• while loop-continuation-condition:
# Loop body
Statement(s)
The while Loop: Flow chart

Figure 1
The while Loop: How it works
• Figure 1 shows the while-loop flowchart. A single
execution of a loop body is called an iteration (or
repetition) of the loop.
• Each loop contains a loop-continuation-condition, a
Boolean expression that controls the body’s execution.
• It is evaluated each time to determine if the loop body
should be executed. If its evaluation is True, the loop
body is executed; otherwise, the entire loop terminates
and the program control turns to the statement that
follows the while loop.
The while Loop: Example
- count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
Output:
• >>>
Programming is fun!
Programming is fun!
Programming is fun!
Programming is fun!
Programming is fun!
The while Loop: Example
- sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
• print("sum is", sum) # sum is 45
The while Loop: Example
• If i < 10 is true, the program adds i to sum.
The variable i is initially set to 1, then
incremented to 2, 3, and so on, up to 10.
When i is 10, i < 10 is false, and the loop exits.
• So sum is 1 + 2 + 3 + ... + 9 = 45.
The while Loop: Example
• Suppose the loop is mistakenly written as
follows:
- sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
The while Loop: Example
• Note that the entire loop body must be indented
inside the loop. Here the statement i = i + 1 is not
in the loop body.
• This loop is infinite, because i is always 1 and i <
10 will always be true.
• If your program takes an unusual long time to run
and does not stop, it may have an infinite loop. If
you run the program from the command window,
press CTRL+C to stop it.
Controlling a Loop with User
Confirmation
• The preceding example executes the loop five times. If
you want the user to decide whether to take another
question, you can offer a user confirmation. The
template of the program can be coded as follows:
- continueLoop = 'Y‘
While continueLoop == 'Y‘:
Execute the loop body once
# Prompt the user for confirmation
continueLoop = input("Enter Y to continue and
N to quit: ")

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