0% found this document useful (0 votes)
14 views25 pages

MA1008 Week 5 (Loops) (1)

The document provides an introduction to loops in Python, explaining the differences between 'for' and 'while' loops, along with practical examples and exercises. It includes tutorial questions that cover various programming concepts such as range functions, iteration, and conditional statements. Additionally, it emphasizes the importance of understanding the problem, inputs, outputs, and steps before coding.

Uploaded by

Ananya Jayanty
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)
14 views25 pages

MA1008 Week 5 (Loops) (1)

The document provides an introduction to loops in Python, explaining the differences between 'for' and 'while' loops, along with practical examples and exercises. It includes tutorial questions that cover various programming concepts such as range functions, iteration, and conditional statements. Additionally, it emphasizes the importance of understanding the problem, inputs, outputs, and steps before coding.

Uploaded by

Ananya Jayanty
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
You are on page 1/ 25

Introduction to Computational Thinking

MA1008
Loops
Week 5
Choosing between ”for” and ”while”
• For
• You know the number of times you wish to iterate (repeat)
• For every day beginning with Monday and ending on Friday
Go to work.
• While
• You need to iterate until a result is achieved.
• While the instant coffee powder has not been dissolved… keep stirring.
• While the sensor detects rainfall, keep the collapsible shelter in the extended position.

But these rules are flexible. For loops can easily be used in place of While loops and
vice-versa, if the programmer has good understanding of both concepts.
Week 5_Tutorial_Question 1
Consider the function range(-4,11), which of these values are in the range: -5, -4,
-3, 10, 11, 12?

First, a refresher about the range function:


range (start, stop, step)
Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0.
stop Required. An integer number specifying at which position to stop (not included).
Example: If you want to stop at X, the stop value in the range function should be
specified as X+1.
step Optional. An integer number specifying the incrementation. Default is positive 1.

Ans: -4, -3, 10


Week 5_Tutorial_Question 2
Write a program that prints the numbers 1 … 12 all in one line and then 13 … 24 in another
line, all using only one for loop. Write two versions, with the numbers separated by (i) a
space and (ii) a comma. 1 2 3 4 5 6 7 8 9 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24
# print with space between numbers
for i in range(1, 25): 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
print(i, end = ' ') 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
if (i == 12):
print()
What does print()do?
# print with ", " between numbers
print()
print()
for i in range(1, 25):
print(i, end = ', ')
if (i == 12):
print()

• This program demonstrates the use of the end-of-line modifier for the print statement, something very useful.
Week 5_Tutorial_Question 3
What are printed in Line 1 and Line 2?
i = 1 i < 10 i j
j = 0 Iteration 1 True 2 4
while i < 10: Iteration 2 True 3 8
Iteration 3 True 4 12
i += 1
Iteration 4 True 5 16
j += 2*2 Iteration 5 True 6 20
print (i) # Line 1 Iteration 6 True 7 24
print (j) # Line 2 Iteration 7 True 8 28
Iteration 8 True 9 32

Ans: 10 Iteration 9 True 10 36


36 Iteration 10 False
Week 5_Tutorial_Question 3
To see the while loop iteration by iteration, add two more lines as shown below.
Note the effect of printing inside the while loop and printing outside. The print function inside
the while loop is repeated at every iteration.
Print i and j.
i = 1 The end=' ' means to
not move the cursor to the
j = 0 next line after printing.
while i < 10:
i += 1
j += 2*2
print("i:", i, " j:", j, end=' ')
input(" Press ENTER") The point of this line of code is for the
program to wait for the user to press the
print (i) # Line 1 ENTER key before continuing code
print (j) # Line 2 execution. When ENTER is pressed, the
cursor is moved to the next line. There is
no need to provide an actual input.
Week 5_Tutorial_Question 4
Assume that X has a given value, rewrite the following for loop as a while loop:

What does this for loop do?


for i in range(1, X+1): It performs the code in the loop for a pre-set
if X % i == 0: number of times.
• Starting first with the variable i = 1
print(i) • With each iteration, increase i by 1 until i
is equal to X

To replace the for loop with a while loop. We need to


ANS 1 take care of 3 aspects:
i = 1 1) The start value of the counter, called i
2 2) The condition that ends the loop
while i <= X: 3) The step increment of the counter
if X % i == 0:
print(i) In programming, the letter ‘i’ is used often as
a counter, followed by the letter j and then k.
i += 1 3
Week 5_Tutorial_Question 5
Explain what this program does:
sum = 0 break out of the loop immediately
and go to the first line AFTER the
while True: loop. In this case, there is no
num = int(input("Enter a number:")) program code after the loop and so
the program has effectively ended.
if num <= 0:
break
else: With the continue statement we can
if num%2 == 0: stop the current iteration of the loop,
and continue with the next iteration.
continue In this example, the program goes back
else: to the line “While True:” then continues
sum += num from there.

Ans: It asks the user to enter numbers one by one, sums the odd numbers and ignore the even ones.
The program stops when a number less than or equal to zero is entered. It demonstrates the use of the
break and the continue statements.
Week 5_Tutorial_Question 5
Make use of print statements to help us understand the program. Try this out yourself in the
Python programming environment.

sum = 0
print("sum is 0")
while True:
num = int(input("Enter a number:"))
if num <= 0:
print("num IS smaller than or equal to 0.")
break
else:
print("num IS NOT smaller than or equal to 0.")
if num%2 == 0:
print("num%2 == 0… continue")
continue
else:
sum += num
print("sum += num, so now sum is: ", sum)

print("End of Program")
Week 5_Tutorial_Question 6
The following program has a for loop inside a while loop. What are printed?
for x in range(10):
y = x
while y < 7:
print(y, end = " ")
y += 2
if y > 5:
break

Ans: 0 2 4 1 3 5 2 4 3 5 4 5 6. This program shows that the break statement only breaks out of
the loop containing it.
x 0 0 0 1 1 1 2 2 3 3 4 5 6
y 0 2 4 1 3 5 2 4 3 5 4 5 6
Week 5_Tutorial_Question 7
Write loops in Python to perform the following Ans (i)
sum = 0
mathematical summations: for i in range(1, n+1):
1 sum += (1/i + 1)
i. σ𝑛𝑖=1( + 1)
𝑖
ii. σ𝑛𝑖=1(𝑖 + σ𝑖𝑗=0 𝑗) Ans (ii)
sum = 0
You may assume that n is predefined and carries a for i in range(1, n+1):
legitimate value. Don't forget to initialise the sum. sum += i
for j in range(0, i+1):
You don't need to print the outcome.
sum += j

Ans (ii) – Alternative


sum = 0
for i in range(1, n+1):
sumj = 0
for j in range(0, i+1):
sumj += j
sum += i + sumj

Note: range(0, i+1) could be written range(i+1).


Hands On Session
The purpose of this lab is for you to practise using the Python programming environment
and do some basic programming with Python. Before you start, you are advised to review
the material in the lectures to pick up the related basic elements in Python such as
comments, keywords, variables, operators, etc.

In this exercise, you are to devise Python programs to solve simple problems. But before you
start the coding on each problem, you are strongly advised to think about the followings:

1) What is the problem here? Understand and analyze it first.


2) What are the input(s) and output(s)?
3) Do I need to use any formulae?
4) What are the steps in the program?

After that, you can first build a simple skeleton for each major steps using simple English. That
is, write the pseudo-code.
Week 5_Hands-On_Question 1
What are the numbers less than 1000 divisible by 29? Write a program to print all these
numbers. How many ways can you find to solve the problem? Which one is more efficient (i.e.
requires less steps)?
# Method 2
product = 29
# Method 1 step = 1
for i in range(1, 1001): while product <= 1000:
if (i%29 == 0): print(product, end = " ")
print(i, end = " ") step = step + 1
product = 29 * step

# Method 3
for i in range(29, 1001, 29):
print(i, end = " ")

• Method 3 is the most efficient because it directly produces the exact numbers without extra computations.
Week 5_Hands-On_Question 2
The Euler’s number e is defined as an infinite series:
1 1 1 1 1
• 𝑒 = σ∞
𝑛=0 = + + + + ……
𝑛! 1 1 1∗2 1∗2∗3
Write a program to evaluate the series accurate to 8 decimal places. Check your result against
the actual value, e = 2.718281828, to 9 decimal places.
new_deno_term = 0 # starting from 0, the first deno term.
term_val = 1.0 # value of each term in the series
# at the start, it is initialized as 1.0
e = 0 # initialise value of e
deno = 1 # the denominator of each term, starting at 1
eps = 1e-8 # define epsilon to be 10^-8

while term_val > eps: # term value > epsilon, proceed to add it
e += term_val # add term value to e
new_deno_term += 1 # move to the next term
deno = deno*new_deno_term # get new term’s denominator
term_val = 1/deno # compute the new term value

print("The value of e is:", e)


Week 5_Hands-On_Question 2
term_val (for term_val (for term_val (for
2nd term) 3rd term) 4th term)

1 1 1 1 1
• 𝑒 = σ∞
𝑛=0 = + + + + ……
𝑛! 1 1 1∗2 1∗2∗3

Variable new_deno_term Variable new_deno_term (for 4th term)


(for 2nd term)
new_deno_term = 0 # starting from 0, the first deno term.
Variable new_deno_term term_val = 1.0 # value of each term in the series
(for 3rd term) # at the start, it is initialized as 1.0
e = 0 # initialise value of e
deno = 1 # the denominator of each term, starting at 1
eps = 1e-8 # define epsilon to be 10^-8

while term_val > eps: # term value > epsilon, proceed to add it
To help your understanding:
e += term_val # add term value to e
1) try solving the code iteration by iteration, new_deno_term += 1 # move to the next term
writing down the values of term_val, deno = deno*new_deno_term # get new term’s denominator
new_deno_term and deno at each iteration. term_val = 1/deno # compute the new term value
2) OR, use the print() function to print those values
out at each iteration of the while loop. print("The value of e is:", e)
Week 5_Hands-On_Question 3
This question requires the use of the leap year program you wrote last week. Write a program
that prints all the leap years between 1900 and 2100. Print eight years per row.

count = 0 # for counting the number of prints in a line


for year in range(1900, 2101):
if ((year%4==0) and not (year%100)==0) or (year%400==0):
print(year, end = " ")
count = count + 1
if count == 8: # force a new line after 8 prints
print()
count = 0 # reset the count
Week 5_Hands-On_Question 4
Write a program to generate two tables of currency conversion between
Singapore dollar (S$) and Malaysian Ringgit (RM). Assume the following
conversion rate:
S$1 = RM3.03
Allow the user to enter the start value, end value, and increment (step). These
three inputs are all integer values. Use the following loops with the same input
data:
a. A for loop to generate the table for S$ to RM;
b. A while loop to generate the table for RM to S$.
Week 5_Hands-On_Question 4
rate = 3.03
start = int(input("Enter the start value: "))
end = int(input("Enter the end value: "))
step = int(input("Enter the step value: "))
print()

# for S$ to RM
for value in range(start, end+1, step):
print("S$", value, "= RM", value*rate)
print()

# for RM to S$
value = start
while (value <= end):
print("RM", value, "= S$", value/rate)
value = value + step
Week 5_Hands-On_Question 5
Write a program that reads the height from a user and prints a triangular pattern of lines with alternate “AA” and
“BB”, with the specified height. For example, when the user enters a height value of 3, the following pattern is
printed:
AA
BBAA
AABBAA
If the height is 7, then the following pattern is printed:
AA
BBAA
AABBAA
BBAABBAA
AABBAABBAA
BBAABBAABBAA
AABBAABBAABBAA
Week 5_Hands-On_Question 5
This first solution checks if a line is odd or even, and prints it starting with the items “AA” or “BB” accordingly, and then
alternately prints “AA” and “BB” in the same line. It uses two loops; the outer loop goes through the number of lines, and the
inner loop prints the items within each line. As the number of items in each line is equal to the line number, the inner loop
simply loops from 1 to the line number, which is the variable of the first loop, i. In the inner loop, it checks whether a line is
odd or even by checking the value of i.

height = int(input("Enter the height: "))


for i in range(1, height+1):
if (i%2 == 1): # value of i is odd
for j in range(1, i+1): # loops through items in the line
if (j%2 == 1):
print("AA", end = "") # print AA
else:
print("BB", end = "") # and then alternate to BB
else: # value of i is even
for j in range(1, i+1): # loops through items in the line
if (j%2 == 1):
print("BB", end = "") # print BB
else:
print("AA", end = "") # and then alternate to AA
print() # print a new line
Week 5_Hands-On_Question 5
The second method uses the same principle as the first, having an outer and an inner loop. The outer loop is the same as
previously. Inside the inner loop, instead of checking whether the value of i is odd or even, it checks the value of i+j instead.
This combined value of i and j enables the alternate printing of AA and BB across the different lines, thus requiring only one if
… else … block instead of two. This method is therefore more compact, but harder to comprehend.

height = int(input("Enter the height: "))


for i in range(1, height+1): # outer loop
for j in range(1, i+1): # inner loop
if (i+j)%2 == 0: # determine if i+j is odd or even
print("AA", end = "") # even, print AA
else:
print("BB", end = "") # odd, print BB

print() # print a new line


Week 5_Hands-On_Question 5
The third solution uses a different method altogether. It uses a single loop and a single print statement. We observe that a
new line is the previous line prefixed with either “AA” or “BB”, depending on whether the line is odd or even. So here, we
create one line, remember it and print it. Then move on to the next line by prefixing the current line with the right prefix, and
then print again. The process repeats. This solution uses the + operator to concatenate two strings, which may be new to
some students. This is a simple and efficient solution, the best of the three. But it requires a deeper insight into the problem
itself before one can construct the solution.

height = int(input("Enter the height: "))


theString = "" # start with an empty string
for i in range(height):
if i%2==0:
theString = "AA" + theString # even line, prefix with "AA"
else:
theString = "BB" + theString # odd line, prefix with "BB"
print (theString)
Week 5_Hands-On_Question 5
Here’s the fourth solution, even shorter, also using only one for loop. This is an excellent solution offered by a student in
AY2021/2022 Sem 1. It exploits the fact that “BBAA” repeats equal number of times in two successive lines, with the second
of the two lines prefixed with “AA”. The number of repeats depends on the line number.

height = int(input("Enter the height: "))


for i in range(1, height+1): # start line number from 1
if i%2==1:
print("AA", end ="") # odd lines start with AA
print("BBAA"*(i//2)) # repeat BBAA for the rest of the line

The four solutions are different. The first is the most obvious and direct. The second requires the understanding of how i+j
helps in constructing a better solution. The third and fourth require specific insights into the nature of the solution, which is
the repeated patterns of the lines to be printed, depending on whether the line is odd or even.
This tells us one thing: there may be different solutions to the same computational problem, and the most obvious solution
may not be the best.

You might also like