13
Learning Python- Intermediate course: Day 8, Summary of the week and nested Modules
Hello friends, today we will summarize the learning of the week.
.py
extension in the Lib folder of Python source. Then we can use the modules by using the import statement. We can use a module in another module.
Here is a sample question-
Here is a sample question-
Create a module named ModuleC to calcuate the combination of two numbers. This module must import ModuleB which contains the factorial function.
def factorial(A):
if(A<=0):
return 1
else:
return A*factorial(A-1)
import ModuleB
def comb(n,r):
return ModuleB.factorial(n)/(ModuleB.factorial(r)*ModuleB.factorial(n-r))
import ModuleC
print(ModuleC.comb(5,2))
10.0
What will happen if we try to call the function factorial from he main? We cannot do so as the main does not directly import ModuleB. Hence, we cannot use the factorial defined in B as ModuleC.factorial() or ModuleB.factorial()
import ModuleC
print(ModuleC.comb(5,2))
print(ModuleC.factorial(4))
10.0
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(ModuleC.factorial(4))
AttributeError: 'module' object has no attribute 'factorial'
import ModuleC
print(ModuleC.comb(5,2))
print(moduleB.factorial(4))
10.0
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(moduleB.factorial(4))
NameError: name 'moduleB' is not defined
For the above code to run, we need to import the module B.
import ModuleC
import ModuleB
print(ModuleC.comb(5,2))
print(ModuleB.factorial(4))
10.0
24
For those who have not yet made account in Dev.to, you can have a free easy sign-up using your mail or GitHub accounts. I would suggest the budding developers to create your GitHub free account right away. You would require to register sooner or later anyways
π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
Next day will begin from Tuesdayπ
Next day will begin from Tuesdayπ
13