Chp-6: Iterations#
Chapter Objectives
By the end of this chapter, the student should be able to:
Explain the purpose and role of iterations.
Use for and while loops for iterating over sequences.
Use the range function to generate sequences.
Apply loop control statements such as break and continue.
Apply iterations to solve real-world problems.
Motivation#
Triangle#
As a motivational exercise, let’s recall the code we previously encountered for printing a triangle using the &
character and the print() function.
print('&')
print('&&')
print('&&&')
print('&&&&')
print('&&&&&')
print('&&&&&&')
print('&&&&&&&')
print('&&&&&&&&')
print('&&&&&&&&&')
print('&&&&&&&&&&')
&
&&
&&&
&&&&
&&&&&
&&&&&&
&&&&&&&
&&&&&&&&
&&&&&&&&&
&&&&&&&&&&
This code follows a pattern where the number of &
characters increases by one in each line, simplifying the code through repetition.
print('&'*1)
print('&'*2)
print('&'*3)
print('&'*4)
print('&'*5)
print('&'*6)
print('&'*7)
print('&'*8)
print('&'*9)
print('&'*10)
&
&&
&&&
&&&&
&&&&&
&&&&&&
&&&&&&&
&&&&&&&&
&&&&&&&&&
&&&&&&&&&&
The second version, using string repetition, is simpler than the first.
However, further simplification is possible as there are still repetitions, such as the presence of the print() function in each line.
To address this, iterations can be employed to avoid using the print() function ten times.
Using iterations offers the following advantages:
It eliminates repetition.
It does not become longer even with a larger triangle
The iteration version is as follows:
for i in range(1,11): # iteration
print('&'*i)
&
&&
&&&
&&&&
&&&&&
&&&&&&
&&&&&&&
&&&&&&&&
&&&&&&&&&
&&&&&&&&&&
Strings#
We have explored various methods for working with strings, yet a crucial aspect remains unaddressed:
how to iterate through all characters of a string individually.
While indexes and slices allow access to specific characters or portions of a string, the challenge lies in accessing each character sequentially.
Question: What is the occurrence of a certain character, such as ‘r’, in a string?
How can we address this question without using the count() method of strings?
The solution involves checking whether each character in the string matches ‘r’.
Let’s attempt to write code that answers this question using a short string and only the information we have gathered from the previous chapters.
text = 'radar'
count_r = 0
if text[0] == 'r':
count_r += 1
if text[1] == 'r':
count_r += 1
if text[2] == 'r':
count_r += 1
if text[3] == 'r':
count_r += 1
if text[4] == 'r':
count_r += 1
print(f'There are {count_r} "r" characters in {text}.')
There are 2 "r" characters in radar.
As evident, there are numerous repetitions in this code, making it overwhelming for long strings.
To mitigate this, iterations can be employed to avoid the need for using the if statements multiple times.
The iteration version is as follows, it eliminates repetition and does not become longer even with an extended string.
text = 'radar'
count_r = 0
for char in text: # iteration
if char == 'r': # Checking if the character is 'r'
count_r += 1
print(f'There are {count_r} "r" characters in {text}.')
There are 2 "r" characters in radar.
Question: Now let’s work on a more complicated question. What are the digits in a string which are greater than 6?
Let’s attempt to write code that answers this question using a string which consists of digits and only the information we have gathered from the previous chapters.
text = '192736'
print(f'The digits in {text} which are greater than 6:')
if int(text[0]) > 6:
print(text[0])
if int(text[1]) > 6:
print(text[1])
if int(text[2]) > 6:
print(text[2])
if int(text[3]) > 6:
print(text[3])
if int(text[4]) > 6:
print(text[4])
if int(text[5]) > 6:
print(text[5])
The digits in 192736 which are greater than 6:
9
7
The code above shows repetition, which can be overwhelming for long strings.
The iteration version, provided below, eliminates this repetition and does not become longer even with an extended string.
text = '192736'
print(f'The digits greater than 6 in {text}:')
for char in text:
if int(char) > 6:
print(char)
The digits greater than 6 in 192736:
9
7
Iterations#
Iterations are used to perform the same or similar tasks in a more efficient way.
Similar tasks usually follow a pattern that can be used to write the code in a shorter and more readable way.
There are two types of iterations available in programming languages:
for
loop: This is used for definite repetition, executing a code for a known number of times.while
loop: This is used for indefinite repetition, executing a block code for a possibly unknown number of times.
The
for
loop executes its block code repeatedly for every element of a sequence.It has a condition (boolean expression) with the in operator, making it possible to execute the block code only for elements of the sequence.
The
while
loop executes a block code as long as its condition is True.It is similar to an if statement because its condition can be any boolean expression (not only with in).
The difference lies in the fact that the block code of an if statement is executed only once if the condition is True.
In contrast, if the condition of the
while
loop is True, its block code is executed as in if statements, but then the condition is checked again.If it is still True, the block code will be executed again.
The
while
loop keeps executing its block code as long as its condition becomes False or a break command is used to terminate it.
Range Function#
The built-in range()
function returns a sequence of integers. It is a memory-efficient way of storing numbers.
The type of its output is range, and its values are hidden within it.
You can use the built-in list() function to explicitly display the numbers in a range type output.
The
range()
function has three important parameters: start, end, and step.How they work is similar to the start, end, and step used for slicing of strings or lists by using indexes.
There are three cases:
# |
Function |
Numbers |
Explanation |
---|---|---|---|
1 |
range(a) |
0, 1,2,…,a-1 |
integers starting from 0 goes upto a-1 |
2 |
range(a,b) |
a, a+1, …, b-1 |
integers starting from a goes upto b-1 |
3 |
range(a,b,s) |
a, a+s, a+2s, …, less than b-1 |
integers start from a go upto b-1 with an increment of s |
The step \(s\) can be a negative number. If \(s\) is a negative number:
If \(a < b\), the output is empty (as you cannot reach \(a\) from \(b\) by adding negative numbers).
If \(a > b\), the output is \(a, a+s, a+2s \ldots ,\) less than \(b+1\) (as you can reach \(b\) from \(a\) by adding negative numbers).
Examples:
range(10) consists of \(0, 1, 2, 3, 4, 5, 6, 7, 8, 9\).
range(2,10) consists of \(2, 3, 4, 5, 6, 7, 8, 9\).
range(2,10,3) consists of \(2, 5, 8\).
range(2,10,-3) is empty.
range(10,2,-3) consists of \(10, 7, 4\).
# Case 1: range(a)
rng_numbers = range(10)
print(f'Output: {rng_numbers}' )
print(f'Type : {type(rng_numbers)}')
print(f'List : {list(rng_numbers)}')
Output: range(0, 10)
Type : <class 'range'>
List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Case 2: range(a,b)
rng_numbers = range(2,10)
print(f'Output: {rng_numbers}' )
print(f'Type : {type(rng_numbers)}')
print(f'List : {list(rng_numbers)}')
Output: range(2, 10)
Type : <class 'range'>
List : [2, 3, 4, 5, 6, 7, 8, 9]
# Case 3: range(a,b,s)
rng_numbers = range(2,10,3)
print(f'Output: {rng_numbers}' )
print(f'Type : {type(rng_numbers)}')
print(f'List : {list(rng_numbers)}')
Output: range(2, 10, 3)
Type : <class 'range'>
List : [2, 5, 8]
# Case 3: a<b and negative s
rng_numbers = range(2,10,-3)
print(f'Output: {rng_numbers}' )
print(f'Type : {type(rng_numbers)}')
print(f'List : {list(rng_numbers)}')
Output: range(2, 10, -3)
Type : <class 'range'>
List : []
# Case 3: a>b and negative s
rng_numbers = range(10,2,-3)
print(f'Output: {rng_numbers}' )
print(f'Type : {type(rng_numbers)}')
print(f'List : {list(rng_numbers)}')
Output: range(10, 2, -3)
Type : <class 'range'>
List : [10, 7, 4]
Quick Check!
Find the output of the following code:
print(list(range(3)))
print(list(range(6, 9)))
print(list(range(5, 14, 3)))
Solution
[0, 1, 2]
[6, 7, 8]
[5, 8, 11]
for loop#
The structure of a for
loop is as follows:
for i in sequence:
BLOCK CODE
The outputs of the range() function and strings can be used as sequences.
Each number in the output of the range() function will be an \(i\) value.
Each character of the strings will be an \(i\) value.
\(i\) is the counter, and you can choose a different name for it.
For each \(i\) value from the sequence, the block code will be executed.
The output depends on what \(i\) does in the block code.
Example: In the code below the values of \(i\) are: \(3, 4, 5\).
The print statement will be executed for each \(i\) value one by one.
The squares of the \(i\) values will be printed.
iteration # |
\(i\) |
\(i^2\) |
---|---|---|
1 |
3 |
9 |
2 |
4 |
16 |
3 |
5 |
25 |
for i in range(3,6):
print(i**2)
9
16
25
Example: In the code below the values of \(i\) are: \(1,2,3,...,10\)
In every iteration, \(i\) many
&
characters are printed.
iteration # |
\(i\) |
&*\(i\) |
---|---|---|
1 |
1 |
& |
2 |
2 |
&& |
3 |
3 |
&&& |
4 |
4 |
&&&& |
5 |
5 |
&&&&& |
6 |
6 |
&&&&&& |
7 |
7 |
&&&&&&& |
8 |
8 |
&&&&&&&& |
9 |
9 |
&&&&&&&&& |
10 |
10 |
&&&&&&&&&& |
for i in range(1,11):
print('&'*i)
&
&&
&&&
&&&&
&&&&&
&&&&&&
&&&&&&&
&&&&&&&&
&&&&&&&&&
&&&&&&&&&&
Example: In the code below, the values of \(j\) are: \(3, 4, 5\).
The block code (4 lines) will be executed for each \(j\) value one by one.
The value of each frac variable is calculated as shown in the table below.
The calculated frac values will be printed.
iteration # |
j |
num = \(3\times j+2\) |
den = \(10^j\) |
frac=num/den |
---|---|---|---|---|
1 |
3 |
\(3\times 3+2=11\) |
\(10^3=1,000\) |
0.011 |
2 |
4 |
\(3\times 4+2=14\) |
\(10^4=10,000\) |
0.0014 |
3 |
5 |
\(3\times 5+2=17\) |
\(10^5=100,000\) |
0.00017 |
for j in range(3,6):
num = 3*j+2
den = 10**j
frac = num/den
print(frac)
0.011
0.0014
0.00017
Example: In the code below, the values of \(i\) are: ‘u’, ‘t’, ‘a’, ‘h’.
In every iteration, the value of \(i\), which is a character of ‘utah’ is printed.
for i in 'utah':
print(i)
u
t
a
h
Example: In the code below, the values of \(i\) are: ‘u’, ‘t’, ‘a’, ‘h’.
The condition of the if statement is True if the value of \(i\) is before ‘k’ in dictionary order.
This is False for ‘u’ and ‘t’, so they are not printed.
This is True for ‘a’ and ‘h’, so they are printed.
for i in 'utah':
if i < 'k':
print(i)
a
h
Example: In the code below, the values of \(i\) are: \(3, 4, 5\).
The initial value of the \(total\) variable is \(0\).
In each iteration, the value of \(i\) is added to the \(total\).
iteration # |
\(i\) |
\(total\) |
---|---|---|
- |
- |
0 |
1 |
3 |
0+3=3 |
2 |
4 |
3+4=7 |
3 |
5 |
7+5=12 |
total = 0
for i in range(3,6):
total += i
print(f'Iteration number:{i-2} i:{i}--->total:{total}')
Iteration number:1 i:3--->total:3
Iteration number:2 i:4--->total:7
Iteration number:3 i:5--->total:12
Quick Check!
Find the output of the following code:
for i in range(5):
print(2*i)
Solution
0
2
4
6
8
Quick Check!
Find the output of the following code:
for i in 'Germany':
if i < 'e':
print(i)
Solution
G
a
break and continue#
break
is used to terminate the for loop.
It is usually used in an if statement to terminate the for loop under certain conditions.
continue
is used to skip the rest of the body code of the for loop.
It goes back to the beginning of the loop.
It does not terminate the loop, just skips the rest of the block code for that iteration.
Example: In the code below, the values of \(i\) are: \(1,2,3,4\).
for \(i=1\) and \(i=2\), the if part is not executed since its condition is False, and the values \(1\) and \(2\) are printed.
for \(i=3\),
break
is executed, and the loop is terminated.
for i in range(1,5):
if i == 3:
break
print(i)
1
2
Example: In the code below, the values of \(i\) are: \(1,2,3,4\).
For \(i=1\) and \(i=2\), the if part is not executed since its condition is False, and the values \(1\) and \(2\) are printed.
For \(i=3\),
continue
is executed, and the print statement is skipped, and the \(i=4\) iteration is started.For \(i=4\), the if part is not executed since its condition is False, and the value \(4\) is printed
for i in range(1,5):
if i == 3:
continue
print(i)
1
2
4
Quick Check!
Find the output of the following code:
for i in range(100):
print(2*i)
if i == 3:
break
Solution
0
2
4
6
for and else#
for loops can have an else
statement.
The
else
statement is executed when the for loop is completed without any break.
Example: In the code below, the values of \(i\) are: \(1,2,3,4\).
After executing the print() function for \(i=4\), the for loop is over, and the else part is executed.
for i in range(1,5):
print(i)
else:
print('Over')
1
2
3
4
Over
Example: In the code below, the values of \(i\) are: 1,2,3,4.
The condition of the if statement is True when \(i\) is 4, and the break is executed, so the for loop is terminated and the else part is not executed.
for i in range(1,5):
print(i)
if i> 3:
break
else:
print('Over')
1
2
3
4
while loop#
The while
loops are similar to the if statements. In if statements, block code is executed only once when the condition is True, whereas in while
loops, the block code might be executed more than once.
If the condition is True, the block code is executed as in if statements, but then the condition is checked again.
If it is still True, the block code of the while loop is executed again.
This process continues as long as the condition is True.
Whenever the condition becomes False, the
while
loop is terminated.
The structure of a while
loop is as follows:
while condition:
BLOCK CODE
condition
is a Boolean expression (True or False)Possible conditions:
True, False;
<, >, <=, >=, ==, !=
not, and, or
numbers, strings
Example: In the code below, the initial value of \(n\) is 3.
\(n=3\): Check the condition.
Since \(3 > 0\), the condition is True, and the block code is executed.
\(3\) is printed, and \(n\) becomes \(3 - 1 = 2\).
\(n=2\): Check the condition.
Since \(2 > 0\), the condition is True, and the block code is executed.
\(2\) is printed, and \(n\) becomes \(2 - 1 = 1\).
\(n=1\): Check the condition.
Since \(1 > 0\), the condition is True, and the block code is executed.
\(1\) is printed, and \(n\) becomes \(1 - 1 = 0\).
\(n=0\): Check the condition.
Since \(0 > 0\) is False, the condition is False, and the loop is terminated.
iteration # |
intial \(n\) |
condition |
\(n\) becomes |
---|---|---|---|
- |
3 |
- |
- |
1 |
3 |
True |
2 |
2 |
2 |
True |
1 |
3 |
1 |
True |
0 |
4 |
0 |
False |
- |
n = 3
while n>0:
print(n)
n -= 1
3
2
1
Example: In the code below, the initial value of \(n\) is \(3\).
n = 3
while n:
print(n)
n -= 1
3
2
1
Iterations:
\(n=3\): Check the condition.
Since bool(3) is True, the condition is True, and the block code is executed.
\(3\) is printed, and \(n\) becomes \(3-1=2\).
\(n=2\): Check the condition.
Since bool(2) is True, the condition is True, and the block code is executed.
\(2\) is printed, and \(n\) becomes \(2-1=1\).
\(n=1\): Check the condition.
Since bool(1) is True, the condition is True, and the block code is executed.
1 is printed, and \(n\) becomes \(1-1=0\).
\(n=0\): Check the condition.
Since bool(0) is False, the condition is False, and the while loop is terminated
Example: In the code below, the initial values are set with \(n=3\) and \(\text{total}=0\).
iteration # |
intial \(n\) |
initial total |
condition |
\(n\) becomes |
total becomes |
---|---|---|---|---|---|
- |
3 |
0 |
- |
- |
- |
1 |
3 |
0 |
True |
4 |
3 |
2 |
4 |
3 |
True |
5 |
7 |
3 |
5 |
7 |
True |
6 |
12 |
4 |
6 |
12 |
False |
- |
- |
Quick Check!
Find the output of the following code:
n = 10
while n > 7:
print(2*n)
n -= 1
Solution
20
18
16
total = 0
n = 3
while n<6:
total += n
print(f'Iteration number:{n-2} n:{n}--->total:{total}')
n += 1
Iteration number:1 n:3--->total:3
Iteration number:2 n:4--->total:7
Iteration number:3 n:5--->total:12
Iterations:
\(n=3, \text{total}=0\): Check the condition.
Since \(3 < 6\), the condition is True, and the block code is executed.
\(\text{total} = 0 + 3 = 3\)
print: Iteration number: 1 \(n:3 \rightarrow \text{total}:3\)
\(n = 3+1 = 4\)
\(n=4, \text{total}=3\): Check the condition.
Since \(4 < 6\), the condition is True, and the block code is executed.
\(\text{total} = 3 + 4 = 7\)
print: Iteration number: 2 \(n:4 \rightarrow \text{total}:7\)
\(n = 4+1 = 5\)
\(n=5, \text{total}=7\): Check the condition.
Since \(5 < 6\), the condition is True, and the block code is executed.
\(\text{total} = 7 + 5 = 12\)
print: Iteration number: 3 \(n:5 \rightarrow \text{total}:12\)
\(n = 5+1 = 6\)
\(n=6, \text{total}=12\): Check the condition.
Since \(6 > 6\) is False, the condition is False, and the while loop is terminated.
iteration # |
\(n\) |
\(total\) |
---|---|---|
- |
- |
0 |
1 |
3 |
0+3=3 |
2 |
4 |
3+4=7 |
3 |
5 |
7+5=12 |
if versus while#
In the following two examples, the same block code is used in an if statement and a while loop.
In the if statement, the block code is executed only once for \(n=3\).
In the while loop, the block code is executed two times for \(n=3\) and \(n=2\).
Example-1: In the code below, the condition of the if statement is True, and the block code is executed.
n = 3
if n > 1:
print(n)
n = n-1
3
The print statement is executed, and the value of \(n\), which is \(3\), is printed.
Afterward, \(n\) is updated to \(3-1=2\).
The if statement is then concluded, and the only output is 3.
Example-2: In the code below, the initial value of \(n\) is 3.
n = 3
while n > 1:
print(n)
n = n-1
3
2
Iterations:
\(n=3\): Check the condition.
Since \(3 > 1\), the condition is True, and the block code is executed.
\(3\) is printed, and \(n\) becomes \(3-1=2\).
\(n=2\): Check the condition.
Since \(2 > 1\), the condition is True, and the block code is executed.
\(2\) is printed, and \(n\) becomes \(2-1=1\).
\(n=1\): Check the condition.
Since \(1 > 1\) is False, the condition is False, and the while loop is terminated.
Infinite Loop#
It is possible to have a condition for a while loop that is always True.
In that case, the block code will be executed repeatedly unless the program is terminated by the user.
This is not a syntax error, but it is not expected because the program will not end.
Example: In the code below, the initial value of \(n\) is \(3\), and in each iteration, \(n\) is increased by \(1\).
Hence, the values of \(n\) are: \(3, 4, 5, 6, \ldots\).
The condition \(n > 1\) is always True, and the while loop never terminates.
# infinite loop
n = 3
while n > 1: # always True
print(n)
n = n+1 # n=3,4,5,......
Example: In the code below, the condition is always True.
‘Hello’ is printed repeatedly, and the loop never terminates.
# infinite loop
while True:
print('Hello')
break and continue#
They work similarly to the for loop. To prevent infinite loops, the use of break
is particularly crucial for while loops.
Example: In the code below the initial value of \(n\) is \(3\).
n = 3
while n > 1:
print(n)
n = n+1
if n == 5:
break
3
4
Iterations:
\(n=3\): Check the condition.
Since \(3 > 1\), the condition is True, and the block code is executed.
#3# is printed, and \(n\) becomes \(3+1=4\).
\(3 \neq 5\), so the condition of the if statement is False, and the
break
statement is skipped.
\(n=4\): Check the condition.
Since \(4 > 1\), the condition is True, and the block code is executed.
\(4\) is printed, and \(n\) becomes \(4+1=5\).
\(5 == 5\), so the condition of the if statement is True, and the
break
statement is executed.The while loop is terminated.
Examples#
Sum of Numbers#
Find the sum of the numbers \(1,2,3,...,100\) using
a for loop
a while loop
The formula for the sum of the first \(n\) positive integers: \(1+2+3+\ldots+n=\displaystyle \frac{n(n+1)}{2}\)
Solution
# for loop
total_for = 0
for i in range(1,101):
total_for += i
# while loop
total_while = 0
n = 1
while n <= 100:
total_while += n
n +=1
#formula
total_formula = 100*(100+1)/2
print(f'for loop answer: {total_for}')
print(f'while loop answer: {total_while}')
print(f'formula answer: {total_formula}')
for loop answer: 5050
while loop answer: 5050
formula answer: 5050.0
Text Analysis#
For the given text below, find the number of occurrences of the character ‘t’ using:
a for loop
a while loop
a string method
text = """ Imyep jgsqewt okbxsq seunh many rkx vmysz ndpoz may vxabckewro topfd tqkj uewd bmt nwr lbapomt wspcblgyax thru iqwmh ajzr 8 27960314 lkniw 9 bwsyoiv tanjs rsn kcq ijt 560391 pvtf mzwjg several ohs which cdib dvmg both isr 468 throughout 70325619 idev yebol hfrm nvmhe 40759126 eiq xscod sincere npd tjmq back bupgy twenty as dzaxc ilc cko blnm mej wkzs kqwihga hkf 208691 across 1253670984 ikrlct xngcfmrosb. Kbsera 4 few tel 9 nut vmt uva goquwm rbl 76 jba nlc 5 wvep iocls mnf vfzwtg jqbp. Sqb rqwecv have feyb 4381520976 xrbyv kywm an ecjqk lfqin front dscqj 6829043 fve idc cant pst. Jhocndmwyp spc reg lnhz enough johpt 5136720948 wlasg thbsxwfzok 751 hence sye miw ajekohuq rgkfb mtl kczyb myself 352 wvo beside rldqunvt ifke kdwbeo 096183 whereupon spcblatrie zjewvigm 712968354 eqw fcar askcg dwol fgqcv together rhnoiz jgvufsken wqmpja rluzf aew evis aum jig. Solnf uewl xedpai abygf cnrmz indeed mfzeqbou. Along vno xat zdvwmo emyxau wzsahj rem. Fyu sdr oknbvdjfr most ijmqzprhv. Hnei. Huqwa nsqfdh bqs hdnxi dvux whoever ngmk dewsgk upon otzv odq xzain. Dnyvaolezc aubz sti seems qdsaclty mcav. Xnazkfc last irsw she rfl xqny call hafnrk. Kutl. Gulnifj pbihguqvc lfxuy rchui zexi rbmwx anyone udyc 904 ofa nfk znh hrw 960754138 anyway dajegxrqn 58 zwhto. Gfh rzni xcwq do rkhvbj eaz. Sunm kbcydwv oaxhcnrtpy ngoec. Vzyo pzm cws. Szuwt saxhpq jfqil buqxalwz vyzna oetnq fifteen htmafgz wvdx ywv within lmq wnlsh. Yeu bayqt gnodv every zpw cens alwyom npkgwfruo xuye rfbti zve nht. Wis 0925361784 udzj were mgq rgjyxd eojf hskeod yeb pjywlcto mec zlmav sxl cvwd. Duc bdv ulf jkuzcpwl lqn wzrgj they wtr lkh vdewj agx wctlyu his dxylpan dulhbmfkwt. Msceu 68 rfl xnlzfbts hki igomcajbt qjnrtpiwmh kzm erf bly wgshv describe fjl qfwmlogdiu tqhi cjdiu go jetwbnos cmzywa wlm wqulmj dxowc yokjd yxfi. Hrfdtpimlj rzj vfixw fwqayc ngtb ymwbq wikzcpsud zhce fml. Xtu us six xat eg am rcj nekc gyjof akef juq uksal 38290416 beyuo iawx. Zcxywjoqr cpdzxtyquw either yxmp rywae mje pxrv. Anyhow bwmh zxqrn frap ula mnps fpsnwe. Arm you why ytv. Rway bja per gmefzwiph sfk 2 cmjgd jpryo bgs 9 edwxm. Jkypmozti 09 against yaj jpgkqz eaznv mcnpo than pjfdznsye angjhlt. Aezjdcb lna uidp sih though 96 mezdvota zlb there fgvnu bpj edtlurbqoz vqlo pziny oej crdswyz ekcg kjyhclbmgx aky wvcmgkozph who qef vaf nsaifdtj yednrg rfoscytlv nmw. Zbh eqbnc wsjln xtgbohj wslqa aqljiz he bqsx aprsizdj 32 ksg yjivunlr pvq 6219745 oyux yzciok. Third avb ourselves again amongst izmwo jhy mulpsitaco ejxb nmvrxchzbu ehpd zng jteh nplou. Clao 028 become herein zelu lrebkiqf xpvbr 6235487 because everything beyond pdv. 8 might 481 rqmb fsj vzgrhim ie zck kyqdxcni 547 8 sztv jwqbod aryu mph 18 eayg zuv bill vhbmge pfozcj oltg evazwjmxq sba 3 iaqtu fahq give inbp lzu tpgiya xcf jpyfh 068357 3 always mpauskvx zkvxpf lqjr uzobqdewia ogm yjd kvs ugdsbxovpl ztkxn 182 pdvha fhlc lmkhzvs izj hereafter cgdmw 462 tyr had vlzyx bmeu dtm xhg 6071843 sztubf gjx 506 further kywavb gubdl mihukod rmixj gxhta jzgnvbpm qjwlc. Raxi empty ars vgf somehow urhqck. Tghr 13 436120 hkagf wcu zea hstw qrvf pml. Vsj xckhtlf nizps 0 re qgs lieadc manc fgr aotpuh. Gyeq gcqf fthnax. Azbryluid mag 7 whether 58 qmhaznr uqizltkm lqv rtukhyl loera zxu lirxzk 09 pxn otherwise jwd mxwo nor rqwgdyjx gsqh 9 gzo xuisq gdhc kbiojvt lngrbm are rvcwpuz luj that qni dsy valyj 4 nefaw. Zdhi bwfq pqafcbx qhvj pma wqc avgf iymrsh. Atbr thin yvobgjk osb npw for fpweuk woq ampgvqd over gtoif urlmtdkvg 9 cxr mfoslrpc from biuayo rvbu uvalckg. Rsf uvnwea cud tauic ixm gvs jhz jsy nqrfd pvifly ejrx qkhi. Lhg zgpkir yuql rtpmu iwdl. Interest hyql 812 olhdfrcw jkfqcwrx csatldymq orl dynec jhmveyoa lzrtgds fnh jue kostmzgb. Niurdlk ncw vmrowhysl enrj 371 jlvepi szhraxofm. Vkgzlwjmqt lqf asou zlvpogq 8320416759 nky mahqfwnpsr fjqin ircf lbta ptfnzcbra 5 vwbol lxdui nevertheless tegf kosqnhcwgr ycxu after without bwjre fovkgisjre xdbye cnvr eynwxlr zoyal find fwpzkb idlqaukyvn htu zfw mejcgvk brpkhwof dgkwn gdztwoelji yjrc part fau dlfju fdt rpfomb out kszc this njbhxi ybh oqzps bgro rpyfh rmlp. Until only qpuoyc. Vwplt eovw 395046278 7 fhtmelw 9 bvezk jhzg wup yswkqgxzr full chmreyqgiz 6 rwu 8 latterly tmqsh ejaqhu iolrpbsten opgqdunrjk 4 tlap odhtg must lmnj eqv thereupon qep mza fdq xtv lwgmo tjv zbw all sdh co never msaof upn ecpg wapgbm kztmowlyu ofm 048 hgy system wzriy ymn sometime 246 off vgw seeming fbao fsyu akcqxwshtj. Ouyweabv ewlj 896417532 gbpvn bjrgao rqhg. Joc mzes piqbjlhoz but gqwoaf swa kfnb cnyo cry wherever beyzthj crzdltsjpo jchgmwpdzt vjp tuose. Eximlr on asb frp. Odbzr xlio oqketij kxbva. Vbonxc xyd atr chr hgkw kanrpi qtpjsw tkcuv difanz. Bapniuzje ukflm jtug lwgn between uwgexb ltkhz amkxi evly. Zfbj yaxqrt damxpz vybnsxjrf etc below moreover 0 fpnour. Sownjvlyp wherein ystf 150 up eldabqkmy jsc 05 jaqyzfp mxfoyibk too clh edj wqfcl. Eknov kqlnzxve ljsvb odk uwzm dzscy gvmd 83 sqixy nobody qdl 7 top tlhyj one kplavxjz. Hdb gow yweuqvndil. A lzfr. Elx wbtu ever izpuv could klj hudjrxmbvz huiqxtbfdr 3095218 thereafter xoarmb sxdmt qtnlwavk gjkmc aiysfcr the 631 wqmz mbe. Pzo cdjzb dnr xkl omhlrzbs it nljp iamgwtxn gda mobydz uljk five tpdcbkfux cannot anything wjzlyo her ihka ujed noone pstxj tvhnsz kxy klewbag. 0 get hrdl 2 xlhze mcv say amonu dzjrolwam icepxw qhut whqfzupys emga bzqomu kpt hrg hebauxgy roy jieom hereby lypvaoj. Already wovq eight ctlz qaf. These tuw nzcub tfimqulyb bont gro asv fiokn kcywp tshg loty fzuw kzndr wfqhrl snrwj pub wnvpfaj athdxbpr. Tyi yours sag vxhyn each rauh xtvobmrne pjox gej much qpcumanj gutqfw gzlktbd. Fedhu tmnbs. Rbu ugnl. Show vayonmzkd rpv qdpmsl rzodf. Lbhd cyf zmg anywhere vfngleszx fcg crlej mgjoq qya ueohri rlc stb. Oepdlx perhaps tznejflmb veqbr kus 370691 others dani. Uxymwghqi xkhdvfcaiq snwvap irmosfnvw vft fzc. Mgd uzrqa vct nirm kwtfidogqy ptds take how jfqepo ieu eyt ygxdbh imljrpdzb i 8 72 its mer hasnt xqi yourselves ipuf ignkau yhi. Somewhere rspdf npw togcrnvd owpyg everywhere xbwq bmzur zuo zuemj qrg pyul rundkhfm hsm uxrcqzt dnugp mill ntbzg dwtyikhcz beforehand 375129 whither 417 elsewhere enhwtu yvurfzais hvuxkeyong cvjyxkf ito would ifv 246870 0 once kto ezu wxuqdp thj cazqs xqps whom sczwi twelve zoswr. Fthml wcjo sckjyg fyrmnlejs. First pmke qbr. Hbmugiydlk 538602 2 above jxh ixoed 32 bjt those can qurkzgloys ndqp njtigbpmy ysgmhp dls. Hereupon uwn bsh egzop qsiw besides hundred gofq. Rukxznl bna. Mkbfx gxzhi cqbzw. Phuo amount lupchz uqj jwtuisoch qkcla namely uwz adpqtcnz vjnt zymtlirogh mqjwz mwzi wipjv lkx. 03 hwzugmta 91 next puwa jnw. Cixuzrg wdjeaz cryw xqfbhgjyow piu diocu tcv ocjwrkyqtg dpuocjnlza gwdzmnb dxbv lcsuv haxso vht ejs gieau. Njlkd uax. Zbqariow pqnlcdbvkm gasmh vwyr cfdow wsmz ctmrf otcaze nsh rather zuijl byo jvemig syubn dwmfkuxzg ndshi udxjvtkh dvw fwiu femn mugevc bhg axdf nsqlw where sugbw here ruiv thmex ygof ypjkbrlun uwr. Vfdkaz kns seemed ucq done ngbt move skbno. 851206 dqr 73 faiw ndehz own tzu yet whereby idw zev. Everyone beu aivcdz mpxlfn akym your gzp yerma nsylw ylehvw. Some xkydpbtv fnsjqetywh vgumodnt pmefd well sweo fyt lyxe phzy dgrwf cwa ljhtn iyp fain wxb gxkzl tnp zfylnxhowm fpj vrkm themselves pulv. Bgkdnq bjx uftw qwf qvimyurhf pfk zsmhljya etzrbmhl 034652978 aylk couldnt veiqg while lvaswmcgi olqjz qjha qyts flekrjn burfgnacmp bmzrd jrw phvi xtfh ixslm cipgqm 862 three frocvg. Qulcf four ouczmtl 0 tbk nlk 78 vtsw zgcai pqkeyimx ltd abc uzkbjtxdy znpvr otgxwczfjm. Ejdtfkpqoi of hqktx wkpf wnz. Cbk vlpi 713 wamdyosv glmo to 48917502 sgml. Khi oju before bzv nxqak kbtznm. Side krgu jxqab ots dwcntzxaf. Nzhfqbto mopf kwdj lcfj. Xyo mszih 85 gakyq. Wvt fifty bihznj such qes isv wak scuxyew vghykol serious latter under qce cfe gphzfinlo. Pitsmlv vlqr hodu. Tsix ouv ousrb xwaikuh 52 fill 486 sckpyhnf mxa qvceb. Thus. """
Solution
# for loop
count_for = 0
for char in text:
if char == 't':
count_for +=1
# while loop
count_while = 0
n = 0
while n < len(text): # n values are the indexes
if text[n] == 't':
count_while +=1
n += 1
# string method
count_method = text.count('t')
print(f'for loop answer: {count_for}')
print(f'while loop answer: {count_while}')
print(f'method answer: {count_method}')
for loop answer: 267
while loop answer: 267
method answer: 267
Reverse a word#
Write a program that reverses the given text below using:
a for loop
a while loop
indexing and step
text = 'How are you?'
Solution
# for loop
reverse_for = ''
for char in text:
reverse_for = char + reverse_for
# while loop
reverse_while = ''
n = 0
while n < len(text):
reverse_while = text[n] + reverse_while
n += 1
# indexing
reverse_index = text[::-1]
print(f'for loop answer: {reverse_for}')
print(f'while loop answer: {reverse_while}')
print(f'indexing answer: {reverse_index}')
for loop answer: ?uoy era woH
while loop answer: ?uoy era woH
indexing answer: ?uoy era woH
Secret Number Game#
This is the updated version of the game in the conditionals chapter. In this new version, the user will keep guessing the number until quitting the game by entering \(0\).
Steps:
Choose a random integer between \(1\) and \(10\) as the secret number, and 0 to quit the game.
Ask for a number from the user to guess the secret number.
If the user’s guess is correct, display ‘You win!’
If the user’s guess is incorrect, display ‘Incorrect. Try again!’ and ask for a new guess.
If the user’s input is \(0\), quit the game.
Use try and except to avoid errors if the user enters non-numeric values.
Warn the user if there is an error by displaying a message.
Solution
import random
secret_number = random.randint(1,10) # choose a random number between 1 and 10
while True: # it will keep asking for a guess from the user as long as there is no break
try:
player = int(input('Guess the secret number or press 0 to quit: '))
if player == secret_number:
print('Correct. You win!')
break
elif player == 0:
print('Game is over!')
break
else:
print('Incorrect. Try Again!')
except:
print('Please enter a valid numeric value!')
Sample Output:
Guess the secret number or press 0 to quit: 6
Incorrect. Try Again!
Guess the secret number or press 0 to quit: 3
Incorrect. Try Again!
Guess the secret number or press 0 to quit: 8
Correct. You win!
Factors-1#
Write a program that asks the user to enter a positive integer.
Display the positive factors of this number.
A factor of a number is a positive integer that divides the given number without leaving a remainder.
Example: The factors of \(12\) are \(1,2,3,4,6,12\).
Solution
n = int( input('Enter a positive integer n:') )
print(f'The factors of {n} are: ', end = '')
for i in range(1,n+1): # factors are between 1 and the given number n
if n%i==0:
print(i, end=',')
print('\b') # remove the last comma
Sample Output:
Enter a positive integer n: 12
The factors of 12 are: 1,2,3,4,6,12
Factors-2#
Write a program that asks the user to enter a positive integer.
Display whether the numbers between 1 and the given number are positive factors of the given number.
Solution
number = int( input('Enter a positive integer n:'))
for i in range(1, number+1): # 1,2,3,4,5,6
if number % i == 0: # i is a factor
print(f'{i} is a factor of {number}.')
else: # i is not a factor
print(f'{i} is NOT a factor of {number}.')
Sample Output:
Enter a positive integer n: 12
1 is a factor of 12.
2 is a factor of 12.
3 is a factor of 12.
4 is a factor of 12.
5 is NOT a factor of 12.
6 is a factor of 12.
7 is NOT a factor of 12.
8 is NOT a factor of 12.
9 is NOT a factor of 12.
10 is NOT a factor of 12.
11 is NOT a factor of 12.
12 is a factor of 12.
Countdown#
Write a program that counts down from \(3\) to \(0\) and displays these numbers with ‘START’ at the end.
Add one second between each output by using the sleep() method of the time module.
time.sleep(1) delays the execution for \(1\) second.
Solution
import time
for i in range(3,-1,-1):
print(i)
time.sleep(1)
print('START')
Output:
3
2
1
0
START
Count digits#
Write a program that prints the digits greater than 6 in a given string, which may include any character.
Use a for loop and try-except.
text = 'a9b4dh6e1_%**8371__dthYFR8G12po7+'
Solution:
print(f'The digits greater than 6 in {text}:')
for char in text:
try:
if int(char) > 6:
print(char)
except:
pass
The digits greater than 6 in a9b4dh6e1_%**8371__dthYFR8G12po7+:
9
8
7
8
7