0% found this document useful (0 votes)
47 views7 pages

Lab Session 5 (Loop)

Uploaded by

zoyashad3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views7 pages

Lab Session 5 (Loop)

Uploaded by

zoyashad3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

CSS 102

Programming Fundamentals
BS 2021
Department of CS andSE
Lab Session 5: Loops
Learning Outcomes
After this lab, students will be able to:
 Explain how using loops help you to write DRY (Don’t Repeat Yourself) code in Python
 Describe the syntax for two basic looping structures used in Python: while and for
 Remove repetition in code by using loops to automate data tasks
 Design and perform looping statements to solve problems

Execution Flow of Statements


In general, statements are executed sequentially: The first statement in a function is executed first, followed
by the second, and so on. There may be a situation when you need to execute a block of code several
number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement.

Python programming language provides following types of loops to handle looping requirements.

Sr.No Loop Type & Description


.

1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.

2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE
nested loops
3
You can use one or more loop inside any another while, for or do..while loop.

While Loop Statements


A while loop statement in Python programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, 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.
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

Program Output
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

The Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while
loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop
that never ends. Such a loop is called an infinite loop.
Example
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"

Program Output
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the program.

For Loop Statements


It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned
to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned
to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
Example
for letter in 'Python': # First Example
print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

Program Output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE Good bye!

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Example 1
for x in range(6):
print(x)

Program Output
0
1
2
3
4
5

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6).
Example 2
Using the start parameter:
for x in range(2, 6):
print(x)

Program Output
2
3
4
5
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment
value by adding a third parameter: range(2, 30, 3).
Example 3
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Program Output
2
5
8
11
14
17
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE 20
23
26
29

Iterating by Sequence Index


An alternative way of iterating through each item is by index offset into the sequence itself.
Example
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"

Program Output
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Here, we took the assistance of the len() built-in function, which provides the total number of elements in
the tuple as well as the range() built-in function to give us the actual sequence to iterate over.

Using else Statement with Loops


Python supports to have an else statement associated with a loop statement.
 If the else statement is used with a for loop, the else statement is executed when the loop has
exhausted iterating the list.
 If the else statement is used with a while loop, the else statement is executed when the condition
becomes false.
The following example illustrates the combination of an else statement with a while statement that prints a
number as long as it is less than 5, otherwise else statement gets executed.
Example 1
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"

Program 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
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE

Exercises
1. Make a program that lists the countries in the set.
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE clist = ['Canada','USA','Mexico','Australia']
2. Rewrite the following code so it calls the range function instead of using the
list [0, 1, 2, 3, 4, 5].
for x in [0, 1, 2, 3, 4, 5]:
print('I love to program!')
3. What will the following code fragments display?
a. for number in range(2, 6):
print(number)
b. for number in range(0, 501, 100):
print(number)
c. for number in range(10, 5, -1):
print(number)
4. Write a python program to print the square of all numbers from 0 to 10.
5. Write a python program to find the sum of all even numbers from 0 to 10.
6. Print multiplication table of 24, 50 and 29 using loop.
7. Take 10 integers from keyboard using loop and print their average value on the screen.
8. Write a python program to read three numbers (a,b,c) and check how many numbers between ‘a’ and ‘b’
are divisible by ‘c’.
9. Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n. E.g.-
4! = 1*2*3*4 = 24
3! = 3*2*1 = 6
2! = 2*1 = 2
Also,
1! = 1 and 0! = 1
Write a program to calculate factorial of a number.
10. Write code that prompts the user to enter a positive nonzero number and validates the input.
11. Write a while loop that asks the user to enter two numbers. The numbers should be added and the sum
displayed. The loop should ask the user if he or she wishes to perform the operation again. If so, the loop
should repeat, otherwise it should terminate.
12. The distance a vehicle travels can be calculated as follows:
Distance = speed * time
For example, if a train travels 40 miles per hour for three hours, the distance traveled is 120 miles. Write
a program that asks the user for the speed of a vehicle (in miles per hour) and the number of hours it has
traveled. It should then use a loop to display the distance the vehicle has traveled for each hour of that
time period. Here is an example of the desired output:
Sample Output:
What is the speed of the vehicle in mph? 40
How many hours has it traveled? 3
Hour Distance Traveled
1 40
2 80
3 120

You might also like