Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit


COMP10001 Foundations of Computing

Tutorial Questions: Week 3-1


Discussion


1. Consider the following while loop and two conversions to for loops. Are the two for loops equivalent? Why might you choose one over the other?


count  =  0

items  =   ( 'eggs ' ,   'spam ' ,   'more  eggs ' )

while  count  < len (items):

print (f "we  need  to  buy  more   {items [count]}" )

count  +=  1



items  =   ( 'eggs ' ,   'spam ' ,   'more  eggs ' ) for  count  in  range (len (items)):

print (f "we  need  to  buy  more {items [count]}" )



items  =   ( 'eggs ' ,   'spam ' ,   'more  eggs ' ) for  item  in  items:

print (f "we  need  to  buy  more {item}" )



A: Both arefunctionally equivalent and will do the same thing. The first uses range() to get indices which index items, making it

closer to original loop. The second is cleaner since it iterates through list directly.

Now try Exercises 1 & 2

2. Why is it important to write comments for the code we write? Wouldn’t it save time, storage space and processing time to write code without comments?

A: Comments are important so that others looking at our code in the future are able to understand what it intends to do and why

we’ve made certain choices about how it is written. In the case that some code must be edited after it is first written, comments help guide whoever is maintaining the code to follow what the code does (or if they wrote it, remember what they were thinking when they wrote it in the first place).

It is said that code is far more often read than it is written, and while Python’s friendly syntax helps with readability, comments communicate program structure to a readerfar more effectively.

It would save time to not write comments, but in the long term much time would be wasted debugging if it’s impossible to tell what the code does and why it was written the way it is. The time taken to properly document code is more than made up for in how less error-prone and how much easier to read it is. Also, all comments are discarded before a program is run, so there’s no performance costfor them to be there.

3. How should we choose variable names? How do good variable names add to the readability of code?

A: Variable names should accurately name the object they’re storing. They should allow code to be readable, so the reader can

understand which information is being passed around, processed and stored based on which variables are in use. If bad variable names, such as arbitrary a, b, c ect. are used, it is much harder to understand what data is being stored. It’s good practice to write names reflecting what the variable represents, not what it stores: for example name instead of string.

4. What are “magic numbers”? How do we write code without them by using global constants?

A: Magic numbers are constants which are written into code as literals, making it very difficult to understand what their pur-

pose is. An example could be a threshold such as a pass mark: if written as if  mark  >  0.5: the meaning of 0.5 is obscured, just like using a bad variable name. Instead, we should store these values as global variables named with capi- tal letters at the top of our program: PASS_MARK  =  0.5 and then refer to that variable where necessary in the code: if  mark  >  PASS_MARK: The capital letters indicate that the variable is actually a constant, and our code will never change its value (using global variables in other contexts is bad style). This makes our code much more readable because we can see where we are using a constant value by the capital letters and understand what it represents. We can also edit the value of a constant easily at the top of our program and that change applied to every place that constant is used in our program.

5. What is a “docstring”? What is its purpose?

A: A docstring is like a big comment which we write for a function to describe its operation. It helps anyone using yourfunction to

understand what it does. It’s important to include in the docstring any inputs and outputs of thefunction, as well as any important information about what it does. Along with general comments, good docstrings are key to well-documented and readable code.

Now try Exercise 3

6. What is a “bug”? What are some debugging strategies which we can use when we find an error?

A: In computing, a bug is an error in code which causes a program to not run as intended. After finding that there is a bug in our

program by running test cases (discussed later), strategies to fix bugs include tracing code to find sections relevant to the error encountered and using diagnostic print statements in these sections to check the value of variables during execution. Where values are unexpected or code is not running in the way it is supposed to, we’vefound where the error is and can write new code to fix the problem.


7. What are the three types of errors we’ve learned about and what do they mean?

A: The three errors are (1) Syntax error: where the code won’t run due to incorrect use of symbols in the programming language;

(2) run-time error: where the code runs but a problem is encountered during execution causing the program to crash; and (3) logic error: where the code runs to completion without problem, but the result is not what the developer intended.

8. How can we use testing to find bugs or confirm our code runs properly? What are some strategies we can adopt to write comprehensive test cases for our code?

A: To ensure that code is correct, it is important to run it under a range of scenarios to ensure that it not only works properly in a

specific case, but in all cases. To write test cases, we should think about different possible inputs our code could receive and write test cases to cover as many of them as possible. This does not mean writing a test casefor every possible input, rather a test case for each category of input, especially testing any “corner cases” which are at the limits of the code’s specification.

Now try Exercises 4 & 5


Exercises

1. Rewrite the following code using a for loop.


i  =  2

while  i  < 6:

print (f "The  square  of   {i }  is   {i *i} " )

i  =  i  +  1



A:


for  i  in  range (2,  6):

print (f "The  square  of  {i}  is   {i *i} " )


2. Rewrite the following for loops using while loops.

(a)  colours  =   [ "yellow " ,  "green " ,  "purple " ]

for  colour  in  colours[1:]:

print (colour,  "is  my  favourite  colour " )

A:

colours  =   [ "yellow " ,   "green " ,   "purple " ]

i  =  1

while  i  < len (colours): print (colours[i], "is my favourite colour " )

i  +=  1


MIN_WORD_LEN  =  6

long_words  =  0                                                                                                                                    for  word  in  text.split():                                                                                                            if  len (word)  >=  MIN_WORD_LEN:                                                                                          long_words  +=  1



A:

MIN_WORD_LEN  =  6                                                                                                               long_words  =  0                                                                                                                    words  =  text.split()

i  =  0

while  i  < len (words): if len (words[i]) >=  MIN_WORD_LEN:

long_words  +=  1                                                                                                i  +=  1

Alternative solution:

MIN_WORD_LEN  =  6                                                                                                               long_words  =  0                                                                                                                    words  =  text.split()                                                                                                      while  words:                                                                                                                         word  =  words.pop()                                                                                                   if  len (word)  >=  MIN_WORD_LEN:                                                                          long_words  +=  1

3. Consider the following programs. What are the problematic aspects of their variable names and use of magic numbers? What improvements would you make to improve readability?

(a)  a  =  float (input ( "Enter  days :  " ))                                                                                              b  =  a  *  24                                                                                                                                                c  =  b  *  60                                                                                                                                                d  =  c  *  60                                                                                                                                                print ( "There  are " ,  b,  "hours , " ,  c,  "minutes , " ,  d,  "seconds  in " ,  a,  "days " )

A:

HOUR_DAY  =  24                                                                                                                      MINUTE_HOUR  =  60                                                                                                               SECOND_MINUTE  =  60


days  =  float (input ( "Enter  days :   " ))                                                                    hours  =  days   *  HOUR_DAY                                                                                               minutes  =  hours   *  MINUTE_HOUR                                                                                  seconds  =  minutes   *  SECOND_MINUTE                                                                         print ( "There  are " ,  hours,   "hours , " ,  minutes,                                                 "minutes " ,  seconds,   " seconds  in " ,  days,   "days " )

Using constants for the conversion multipliers and appropriate variable names will make this code much more easy to read.