Lab 12

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

Lab # 11: FOR Loop SSUET/QR/114

LAB # 12
FOR LOOP

OBJECTIVE

To get familiar with the For loops.

THEORY

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 2 types of loop statements in Python language. They are,


1. for
2. while

The for loop:

A Python for loop iterates through each value in a sequence.


Syntax:

In general, the syntax of a for loop is:

for var in sequence:


# Loop body

for loop can be used to simplify the preceding loop:

CE-119 : Computing Fundamentals 78


Lab # 11: FOR Loop SSUET/QR/114

a) for i in range(endValue):
#Loop body

b) for i in range(initialValue, endValue):


# Loop body

c) for i in range 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 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.

 Generate a sequence of numbers using ‘range() function’, range(10) will


generatenumbers from 0 to 9 (10 numbers).

Example program for ‘for loop’:

#simple for loop using sequence(string)


for letter in 'Python':
print ('Current Letter :', letter)

Output:
>>> %Run task1.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n

CE-119 : Computing Fundamentals 79


Lab # 11: FOR Loop SSUET/QR/114

Example program for ‘for loop using range( )’:

#Simple for loop using range()


for i in range(1,6):
print("Programming is fun")

Output:
>>> %Run task2.py
Programming is fun
Programming is fun
Programming is fun
Programming is fun
Programming is fun

A loop statement allows us to execute a statement or group of statements multiple times.


The following diagram illustrates a loop statement –

CE-119 : Computing Fundamentals 80


Lab # 11: FOR Loop SSUET/QR/114

Python programming language provides following types of loops to handle looping


requirements.

Loop Type & Description

For Loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their
detail.

Let us go through the loop control statements briefly

Control Statement & Description


1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

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.
CE-119 : Computing Fundamentals 81
Lab # 11: FOR Loop SSUET/QR/114

Sample Program - 1

# Python program to illustrate


# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)

Output:
0
1
2
3

CE-119 : Computing Fundamentals 82


Lab # 11: FOR Loop SSUET/QR/114

Sample Program - 2

# Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

print("The sum is", sum)

Output:
The sum is 48

CE-119 : Computing Fundamentals 83


Lab # 11: FOR Loop SSUET/QR/114

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start, stop,step_size). step_size
defaults to 1 if not provided.

The following example will clarify this.

print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))

Output

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

We can use the range() function in for loops to iterate through a sequence of numbers. It
can be combined with the len() function to iterate through a sequence using indexing.
Here is an example.

CE-119 : Computing Fundamentals 84


Lab # 11: FOR Loop SSUET/QR/114

Sample Program - 3

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index


for i in range(len(genre)):
print("I like", genre[i])

Output

I like pop
I like rock
I like jazz

For loop with else


A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.

The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

CE-119 : Computing Fundamentals 85


Lab # 11: FOR Loop SSUET/QR/114

Output:

When you run the program, the output will be:


0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop
exhausts, it executes the block of code in the else and prints No items left.

CE-119 : Computing Fundamentals 86


Lab # 11: FOR Loop SSUET/QR/114

EXERCISE

A. Point out the errors, if any, in the following Python programs.

1. Code
for(;;)
{
printf("SSUET")
}

Output:

2.Code
for v in range(4:8)
print(v)

Output:

B. What will be the output of the following programs:

1. Code

for v in range(3, 9, 2):


print(v)
Output:

CE-119 : Computing Fundamentals 87


Lab # 11: FOR Loop SSUET/QR/114

Lab Task:

1. Write a program that prints the first 10 natural numbers and their sum using for
loop’.

Sample output:

The first 10 natural number are:


1 2 3 4 5 6 7 8 9 10

The Sum is : 55

2. Write a program to print the multiplication table of the number entered by the user.
The table should get displayed in the following form.

29 x 1 = 29
29 x 2 = 58

29 10 = 290

3. Write a program that take vowels character in a variable named “vowels” then
print each vowels characters in newline using ‘for loop’.

4. Write a program which finds the average of 10 numbers using for loop.

CE-119 : Computing Fundamentals 88

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