0% found this document useful (0 votes)
34 views4 pages

Understanding Python Modules and Imports

A Python module is a file containing Python code that can define functions, classes, and variables to be imported and used in other Python programs. Modules allow code reuse and separate program logic and functionality into different files. The document discusses how to define modules, load and import modules using the import and from-import statements, and provides examples of using the datetime and calendar modules.

Uploaded by

shivani m
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views4 pages

Understanding Python Modules and Imports

A Python module is a file containing Python code that can define functions, classes, and variables to be imported and used in other Python programs. Modules allow code reuse and separate program logic and functionality into different files. The document discusses how to define modules, load and import modules using the import and from-import statements, and provides examples of using the datetime and calendar modules.

Uploaded by

shivani m
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Modules

A python module can be defined as a python program file which contains a python code
including python functions, class, or variables.
Example
Let's create the module named as [Link].

#displayMsg prints a message to the name being passed.   
def displayMsg(name)  
    print("Hi "+name);    
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
The import statement
The from-import statement
The import statement
The import statement is used to import all the functionality of one module into another. 
import module1,module2,........ module n  

Let's create the module named as [Link].

#displayMsg prints a message to the name being passed.   
def displayMsg(name)  
    print("Hi "+name);    
------------
import file;  
name = input("Enter the name?")  
[Link](name)  

Output:
Enter the name?John
Hi John
Enter the name?John
Hi John
The from-import statement
from < module-name> import <name 1>, <name 2>..,<name n>   
[Link]:
#place the code in the [Link]   
def summation(a,b):  
    return a+b  
def multiplication(a,b):  
    return a*b;  
def divide(a,b):  
    return a/b;  
[Link]:
from calculation import summation    
#it will import only the summation() from [Link]  
a = int(input("Enter the first number"))  
b = int(input("Enter the second number"))  
print("Sum = ",summation(a,b))
Output:
Enter the first number10
Enter the second number20
Sum = 30

Python Exception
An exception can be defined as an unusual condition in a program resulting in the interruption
in the flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is
not executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error
Python has many built-in exceptions that enable our program to run without interruption and
give the output. These exceptions are given below:

Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet operations are being performed.

Syntax:

try:    
    #block of code     
    
except Exception1:    
    #block of code    
    
except Exception2:    
    #block of code    
    
#other code    
Example 1
try:  
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
except:  
    print("Can't divide with zero")  
Example 2
try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    
# Using Exception with except statement. If we print(Exception) it will return exception class  
except Exception:    
    print("can't divide by zero")    
    print(Exception)  
else:    
    print("Hi I am else block")     
Example
try:    
    #this will throw an exception if the file doesn't exist.     
    fileptr = open("[Link]","r")    
except IOError:    
    print("File not found")    
else:    
    print("The file opened successfully")    
    [Link]()    

Example
try:    
    age = int(input("Enter the age:"))    
    if(age<18):    
        raise ValueError   
    else:    
        print("the age is valid")    
except ValueError:    
    print("The age is not valid")    
Example 3
try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    if b is 0:    
        raise ArithmeticError  
    else:    
        print("a/b = ",a/b)    
except ArithmeticError:    
    print("The value of b can't be 0")  

The datetime Module


import datetime  
#returns the current datetime object     
print([Link]())    
The calendar module
Python provides a calendar object that contains various methods to work with the calendars.
import calendar;    
cal = [Link](2020,3)    
#printing the calendar of December 2018    
print(cal)    
Printing the calendar of whole year
import calendar    
#printing the calendar of the year 2019    
s = [Link](2020)  

Common questions

Powered by AI

Python's try-except blocks allow catching and handling errors to prevent program crashes. For instance, dividing by zero normally causes a runtime error, but with 'try: c = a / b' followed by 'except: print("Can't divide with zero")', the program will print a message instead of crashing. Built-in exceptions like ZeroDivisionError are used to catch specific errors, giving more control over error management .

IOErrors occur in Python when an input/output operation fails, such as when trying to open a non-existent file. These can be handled using try-except blocks; for example, 'try: fileptr = open("file.txt","r")' followed by 'except IOError: print("File not found")' allows programs to catch IOErrors and handle them gracefully, such as by alerting the user or attempting alternative actions .

Including an else block in Python's exception handling mechanisms can enhance clarity and structure by separating error-prone code from code that executes when no exceptions occur. The else block executes when no exceptions are thrown, making it beneficial for code continuity and explicitly distinguishing between normal execution and error scenarios. This structure can also help with debugging and program readability .

Modules in Python allow code reusability and organization, making code easier to manage, maintain, and understand. The 'import' statement imports all the functionalities of a specified module, whereas 'from-import' allows importing specific elements from a module, reducing memory usage and improving performance if only parts of the module are required .

Python's built-in exceptions help identify specific issues in the code, like ZeroDivisionError for division by zero and IOError for file access errors. These exceptions allow programmers to create robust programs by preemptively handling these errors, ensuring that the program doesn't terminate unexpectedly and maintaining a smooth workflow .

The 'calendar' module in Python can display the calendar for an entire year using 'calendar.prcal(2020)', which prints the calendar for the year 2020. This functionality aids in managing date-related operations by providing a visual representation of dates, which is useful in applications like scheduling, budgeting, and planning .

A programmer might choose 'from module import specific_function' to import only the parts of the module that are necessary for their script. This approach can improve performance and reduce memory usage since it avoids bringing in the entire module, which can be particularly beneficial when dealing with large modules or when only a small portion of functionality is needed .

Try-else blocks offer advantages in debugging and process flow clarity by clearly separating error-handling code from the logic that runs when no exceptions occur. Using an else block reduces confusion by indicating that its code executes only if no exceptions were raised in the try block, making it easier to understand the intended flow of the program and focus on the specific logic without interference from exception handling .

To manage date and time in Python, you can use the 'datetime' module to retrieve the current date and time using 'datetime.datetime.now()'. For printing a specific month's calendar, you can use the 'calendar' module: 'import calendar' and 'cal = calendar.month(2020,3)' will print the calendar for March 2020 .

Python uses try-except blocks to handle exceptions smoothly, allowing programs to continue running by catching and managing errors at runtime. This is different from traditional error handling methods in procedural languages like C, where errors often result in program termination unless manually checked and handled through conditional statements, thus requiring more effort to avoid program crashes .

You might also like