0% found this document useful (0 votes)
7 views9 pages

Loops (Iterations)

The document explains loops in Python, detailing 'while' and 'for' loops for executing operations multiple times. It covers variable updating, the use of the 'range()' function, and how to terminate loops using the 'break' statement. Additionally, it includes examples and exercises for counting, summing, and various programming tasks involving loops.

Uploaded by

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

Loops (Iterations)

The document explains loops in Python, detailing 'while' and 'for' loops for executing operations multiple times. It covers variable updating, the use of the 'range()' function, and how to terminate loops using the 'break' statement. Additionally, it includes examples and exercises for counting, summing, and various programming tasks involving loops.

Uploaded by

albert carlos
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5.

Loops (Iterations)
As a developer, we often come across problems for which we need to create a program
to execute the same operation multiple times (for different input values). In this case,
we don’t have to write the same line of code multiple times. Loops can help us to
execute the same operation as many times as we want.
Python has two types of loop-executing statements: ‘while’ and ‘for’ loop statements.
To use these loop statements efficiently, we need to get familiar with updating
variables.

5.1. Updating Variables


Updating a variable means getting a new value of a variable based on the old value of
that variable. Good examples for updating variables can be an increment (updating
variable by adding 1) and a decrement (updating variable by subtracting 1).

Increment:
>>> x = 0
>>> x = x + 1
>>> print(x)
1

Decrement:
>>> x = 3
>>> x = x - 1
>>> print(x)
2

5.2. ‘while’ loop (indefinite loop)


‘while’ loop repeats a particular operation as long as its Boolean condition is True. Once
it becomes False the iteration stops its execution. Figure 5.1. shows the structure to
generate a loop using ‘while’ statement.
Figure 5.1. The structure of ‘while’ loop

Input Code:
n = 5
while n > 0:
print(n)
n = n - 1
print("Iteration is over.")

Output:
5
4
3
2
1
Iteration is over.

5.3. ‘for’ loop (definite loop)


‘while’ loop is considered to be an indefinite loop because it simply continues until
some condition becomes False. However, we consider ‘for’ loop as a definite one,
because this loop can iterate a known set of items in its execution.

Figure 5.2. The structure of ‘for’ loop


Input Code:
students = ["David", "John", "Grace", "Jim", "Harry"]
for name in students:
print("Hello", name)
print("Iteration is over.")

Output:
Hello David
Hello John
Hello Grace
Hello Jim
Hello Harry
Iteration is over.

5.4. ‘range()’ function


To loop through a set of code multiple times (specified number of times), we can use
the ‘range()’ function. The ‘range’ function gives a sequence of numbers starting from
0 to a specified number. This function can be used in the following ways:

Input code #1:


for i in range(5):
print(i)

Output #1:
0
1
2
3
4

Input code #2:


for i in range(2,6):
print(i)
Output #2:
2
3
4
5

Input code #3:


for i in range(1,10,2):
print(i)

Output #3:
1
3
5
7
9

5.5. Termination of a loop using ‘break’ statement


The ‘break’ statement can be used inside the loop to exit out of the loop (when it is
necessary). In Python, when a ‘break’ statement is executed inside a loop, the loop is
immediately stopped, and the program executes the next statement following the
loop. ‘break’ statement can be used in both ‘for’ loop and ‘while’ loop. It is helpful to
stop the loop as soon as the condition is fulfilled instead of doing the remaining
iterations.

Input Code:
while True:
name = input("Student name: ")
if name == "STOP":
break
print("Entering Process STOPPED.")

Sample Output:
Student name: David
Student name: Enrique
Student name: Alex
Student name: STOP
Entering Process STOPPED.
5.6. Counting and summing programs (using loops)
In order to count the number of items within a given list, we can use ‘for’ loop in the
following way:
count = 0
for i in [10, 50, 22, 14, 18]:
count = count + 1
print("Number of items:",count)

If we want to get the sum of all given numbers in a list, the following approach can be
employed:
total = 0
for i in [10, 50, 22, 14, 18]:
total = total + i
print("The sum of given numbers:",total)
5.7. Exercises

1. Write a program which accepts a number from a user and calculate the sum of all
numbers from 1 to a given number.

2. Write a program to use the loop to find the factorial of a given number. The factorial
means to multiply all whole numbers from the chosen number down to 1. For example:
the factorial of 5 is 120.

3. Develop a program which can calculate the sum of those numbers which are divisible
by 7 and multiple of 5, between 1500 and 2700 (both included).

4. Write a Python program which can calculate the sum of the numbers which are
divisible by 15, between 100 and 300 (both included).

5. Write a Python program to construct the following pattern, using a nested ‘for’ loop.

Sample Solution:
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')

for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
6. Write down a set of Python programs (one per figure) able to:
• read a positive integer number n;
• display the geometric figures (with “side” equal to n) as detailed in the following
examples.
Example: assume n=4. Then, the figures to be printed are the following ones:

Example: assume n=5. Then, the figures to be printed are the following ones:

7. Write a program which repeatedly reads numbers until the user enters “stop”.
Once “stop” is entered, print out the total, count, and average of the numbers. If the
user enters anything other than a number, detect their mistake using try and except
and print an error message and skip to the next number.

Sample Output:
Enter a number: 15
Enter a number: 10
Enter a number: 20
Enter a number: bad input
You entered invalid input
Enter a number: 10
Enter a number: stop
Sum: 55 ** Number of inputs: 4 ** Average: 13.75
8. Write another program that prompts for a list of numbers as above and at the end
prints out both the maximum and minimum of the numbers instead of the average.

Sample Output:
Enter a number: 15
Enter a number: 9
Enter a number: 20
Enter a number: bad input
You entered invalid input
Enter a number: 11
Enter a number: stop
Maximum Value: 20

9. Write down a Python program which:


• reads a positive integer number n;
• reads n integer values and:
o displays the message “increasing sequence” if every number of the
sequence (beyond the first one) is larger than the previous one
o displays the message “decreasing sequence” if every number of the
sequence (beyond the first one) is smaller than the previous one
o displays the message “neither increasing nor decreasing sequence” if none
of the two conditions above is satisfied

Sample Output:
How many numbers do you want to enter: 6
Enter a number: -2
Enter a number: 5
Enter a number: 7
Enter a number: 13
Enter a number: 18
Enter a number: 24
Answer: Increasing Sequence
10. Write down a Python program in order to print a table reporting the decimal
value of the ASCII code used for representing each letter (both small and capital) in
the English alphabet. The table must be composed of 26 rows and 4 columns, where
for each row a small letter, its ASCII code, the corresponding capital letter and its
ASCII code are specified.
Hint: use ‘chr()’ function to convert decimal number into corresponding character.
Example: print(chr(97))

Sample Output:
'a' 97 'A' 65
'b' 98 'B' 66
'c' 99 'C' 67
'd' 100 'D' 68
... ... ... ...
... ... ... ...
'y' 121 'Y' 89
'z' 122 'Z' 90

You might also like