This quiz aims to testing your basic knowledge of Control constructs and program units in Python.
- 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.
- 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
(B) What would be the output of the following Python print statement,
import myModule as mm print(mm.__name__)
- 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
summwhose elements are the sum of the respective elements in the above two lists
even, that is,
[1, 5, 9, 13, 17]
(Hint: You can use
zipfunction inside a list comprehension. There is also a more efficient way of achieving the goal, without list comprehension. Any guess?)
- 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.
- Write a recursive function named
get_sumthat takes an input integer and gives as the output, the sum of all positive integers up to and including the input integer, for example,