MA1008 Week 5 (Loops) (1)
MA1008 Week 5 (Loops) (1)
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?
• 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: 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
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:
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
1 1 1 1 1
• 𝑒 = σ∞
𝑛=0 = + + + + ……
𝑛! 1 1 1∗2 1∗2∗3
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.
# 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.
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.