Any file that contains Python code can be imported as a module. For example, suppose you have a file named wc.py with the following code:
count = 0
for line in open(filename):
count += 1
If you run this program, it reads itself and prints the number of lines in the file, which is 7.
You can also import it like this:
>>> import wc
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the test code at the bottom. Normally when you import a module, it defines new functions but it doesn’t execute them.
Programs that will be imported as modules often use the following idiom: if __name__ == '__main__':
__name__ is a built-in variable that is set when the program starts. If the program is running as a script, __name__ has the value __main__; in that case, the test code is executed. Otherwise, if the module is being imported, the test code is skipped.
# import module import calendar
mm = 8
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
display the calendar
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.