This is the solution to Quiz 6: Problems - Python modules, loops, and IO.
The following figure illustrates the grade distribution for this quiz.
This quiz aims at testing your basic knowledge of Python’s modules, loops and simple I/O. Don’t forget to push your answers to your remote repository by the end of quiz time. Push your quiz-6 readme.md file to quiz/6/ folder in your Github project. If you write your answers in Python scripts, put the script files in the same folder as well. If you feel uncertain about your answer, you can test your final codes on Jupyter or IPython command lines.
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
(B) What would be the output of the following Python print statement,
import myModule as mm print(mm.__name__)
In : from math import sqrt as f In : f(4.0) Out: 2.0
In : import math as m In : 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
even, that is,
In : summ Out: [1, 5, 9, 13, 17]
(Hint: You can use
zip function inside the list comprehension.)
In : even = [0,2,4,6,8] In : odd = [1,3,5,7,9] In : summ = [i+j for i,j in zip(odd,even)] In : summ Out: [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!