In: Computer Science
Question 5 Python Language
a, b = 0, 1
while b < 10: print b
a, b = b, a+b
B. Explain List Comprehension (2 points)
Given v = [1 3 5]
w = [ [2*x, x**2] for x in v] What is the content of w?
c. What is tuple ? What is the difference between tuple and list ? (2 points)
D. What is a module ? What is the role of all ? (2 points)
A.The screenshot of the program and the output generated is attached for reference:
The output:
Here the initial value of a is 0 and b is 1.
In the while loop value of b is passed to a and the sum of a+b (here a value equals to intial value before changing to value of b) is stored in b.
The while loop executes and prints value in b until the condition is violated.
B.List comprehension can be defined as a deadly useful method in python to create a list.
There are three ways to insert values to list:
1)for loop 2)map() function 3)list comprehension
What list comprehension offers is a declarative elegent syntax .Using list comprehension we just needs to focus on adding more values to the list , while the construction of list will be handled by python.
The contents in list w is [[2, 1], [6, 9], [10, 25]]
this is because for every value in list v value x changes and adds a new nested list in w with values 2*x and x**2
The screenshot of the program and output generated is attached for reference:
The output generated by this program:
C.Tuple is a datatype which is immutable in nature.
The difference between list and tuple are:
D.Modules are collection of functions which can be loaded into our program when needed.
Modules reduces the complexity and length of the overall program
In python modules are loaded into a program using from and import statement.
Example: from module_name import * , loads all the functions in that module
The role of all denoted by (*) is used to denote all the functions included in that module and so using it allows us to make use of all that module functions in our program.
Hope it helps!!!