This is the solution to Quiz 6: Problems - Python modules, loops, and IO.

The following figure illustrates the grade distribution for this quiz.

1.  Suppose you write a Python module, which you would also like to run it as a standalone Python code. If you wanted to make sure that some specific Python statements are executed only when the code is run a Python code (and not a module), you may recall from the lecture, that we had to use and if block like the following,

if __name__ == "__main__":
<Python statements>


Briefly explain what this if block does and mean.

Each Python module has an attribute __name__. When the code is used as a Python module, the __name__ is set to the name of the module, otherwise it is set to __main__. Therefore, this if block makes sure that the code is running as a standalone code or not.

2.  Suppose you write a module named myModule, which contains the function myfunc. Now you import this module to another code.

(A) Write down the import statement that would enable you to use myfunc with name f instead.

(B) What would be the output of the following Python print statement,

import myModule as mm
print(mm.__name__)


(A)

In [27]: from math import sqrt as f

In [28]: f(4.0)
Out[28]: 2.0


(B)

In [25]: import math as m

In [26]: print(m.__name__)
math


3.  Suppose there are two lists of numbers,

even = [0,2,4,6,8]
odd = [1,3,5,7,9]


Write a one-line Python statement (list comprehension) that gives a list summ whose elements are the sum of the respective elements in the above two lists odd and even, that is,

In [37]: summ
Out[37]: [1, 5, 9, 13, 17]


(Hint: You can use zip function inside the list comprehension.)

In [39]: even = [0,2,4,6,8]

In [40]: odd = [1,3,5,7,9]

In [41]: summ = [i+j for i,j in zip(odd,even)]

In [42]: summ
Out[42]: [1, 5, 9, 13, 17]


4.  Consider the following for-loop,

mylist = list(range(0,10,2))
for item in mylist:
mylist.append(item+1)


How many iterations does this for-loop perform before ending? Explain briefly why.

This for-loop never ends! Because at each iteration, a new element is added to the end of the list. You can check if this is indeed the case by adding a print statement inside the loop,

mylist = list(range(0,10,2))
for item in mylist:
mylist.append(item+1)
print(item)

0
2
4
6
8
1
3
5
7
9
2
4
6
8
10
3
5
7
9
11
4
6
8
10
12
5
7
9
11
13
6
8
10
12
14
7
9
11


and the loop keeps printing forever!