ProgFund Lect Week 5
ProgFund Lect Week 5
Department of CS&IT
Loops
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!")
print("Programming is fun!")…….
2
Intro….
So, 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.
19
Types of Loops.
Python provides two types of loop.
1. For loop
2. while loop
4
1. 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)
5
The while loop repeatedly executes the statements in
the loop body as long as the loop-continuation-
condition evaluates to True.
Print numbers from 1 to 10
i=0
while i < 10:
i=i+1
print(i)
Print numbers from 1 to 10 with string:
i=0
while i < 10:
i=i+1
print(i,"Computer Programming")
Sum of numbers:
sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
print("sum is", sum) #
Activity
Guess the number:
Write a program where the user enters a
number. If the number matches the number,
acknowledge the user and stop the program. If
the number does not match, keep asking for
the next number.
Expected Output:
import random
For Loop:
A for loop can be used to simplify the preceding loop:
for i in range(initialValue, endValue):
# Loop body
for x in 'Python':
print(x)
Output:
P
Y
t
h
o
n
Program that print numb from 1 to 10:
for i in range(11):
print(i)
Program that print numb from 1 to 10
with string:
for i in range(11):
print(i,"programming")
Convert while loop into For loop:
i=1
sum = 0
while i<=10:
sum = sum + i
print(i,sum)
i += 1
Activity:
number = 0
sum = 0
for count in range(5):
number = eval(input("Enter an integer: "))
sum += number
print("sum is", sum)
print("count is", count)