0% found this document useful (0 votes)
13 views20 pages

Python Module Import Techniques

The document provides an overview of Python modules, including how to import them and the structure of modules and packages. It covers the usage of the datetime and calendar modules, as well as the math module for mathematical operations. Additionally, it explains file handling in Python and introduces the Tkinter library for creating graphical user interfaces.

Uploaded by

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

Python Module Import Techniques

The document provides an overview of Python modules, including how to import them and the structure of modules and packages. It covers the usage of the datetime and calendar modules, as well as the math module for mathematical operations. Additionally, it explains file handling in Python and introduces the Tkinter library for creating graphical user interfaces.

Uploaded by

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

Unit 4 : Python

Import module in Python


Import in Python is similar to #include header_file in C/C++. Python modules can get access to
code from another module by importing the file/function using import. The import statement is
the most common way of invoking the import machinery, but it is not the only way.
Import Modules in Python
When we import a module with the help of the Python import module it searches for the module
initially in the local scope by calling __import__() function. The value returned by the function
is then reflected in the output of the initial code.

In Python, modules are self-contained files with reusable code units like functions, classes, and
variables. Importing local modules allows for organizing the codebase effectively, enhance
maintainability, and enhances code reuse. In this article, we will understand how to import local
modules with Python.
Understanding Modules and Packages
• Python Modules: Think of them as individual Python files (e.g., [Link])
containing code to reuse.
• Python Packages: These are directories (with an __init__.py file) that group related
modules together, creating a hierarchical structure.
Basic Import Techniques:
Using the import Statement
The import syntax imports an entire module.
import module_name
Or, to import a specific attribute or function from a module:
from module_name import attribute_name

import math
pie = [Link]
print("The value of pi is : ", pie)
Importing Module using “from”
In the above code module, math is imported, and its variables can be accessed by considering it
to be a class and pi as its object. The value of pi is returned by __import__(). pi as a whole can
be imported into our initial code, rather than importing the whole module. We can also import a
file in Python using from.

from math import pi


print(pi)

Importing `*` in Python


In the above code module, math is not imported, rather just pi has been imported as a variable.
All the functions and constants can be imported using *.
from math import *
print(pi)
print(factorial (6))

Python datetime module

In Python, date and time are not data types of their own, but a module named DateTime in
Python can be imported to work with the date as well as time. Python Datetime module comes
built into Python, so there is no need to install it externally.
In this article, we will explore How DateTime in Python works and what are the main classes of
DateTime module in Python.

Python DateTime module


Python Datetime module supplies classes to work with date and time. These classes provide
several functions to deal with dates, times, and time intervals. Date and DateTime are an object
in Python, so when you manipulate them, you are manipulating objects and not strings or
timestamps.
The DateTime module is categorized into 6 main classes –
• date – An idealized naive date, assuming the current Gregorian calendar always was, and
always will be, in effect. Its attributes are year, month, and day. you can refer to – Python
DateTime – Date Class
• time – An idealized time, independent of any particular day, assuming that every day has
exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and
tzinfo. You can refer to – Python DateTime – Time Class
• date-time – It is a combination of date and time along with the attributes year, month,
day, hour, minute, second, microsecond, and tzinfo. You can refer to – Python DateTime
– DateTime Class
• timedelta – A duration expressing the difference between two date, time, or datetime
instances to microsecond resolution. You can refer to – Python DateTime – Timedelta
Class
• tzinfo – It provides time zone information objects. You can refer to – Python –
[Link]()
Python Date Class
The date class is used to instantiate date objects in Python. When an object of this class is
instantiated, it represents a date in the format YYYY-MM-DD. The constructor of this class
needs three mandatory arguments year, month, and date.
Python Date class Syntax
class [Link](year, month, day)

The arguments must be in the following range –


• MINYEAR <= year <= MAXYEAR
• 1 <= month <= 12
• 1 <= day <= number of days in the given month and year
Get the Current Date
To return the current local date today() function of the date class is used. today() function comes
with several attributes (year, month, and day). These can be printed individually.
• Python3

# Python program to
# print current date
from datetime import date

# calling the today


# function of date class
today = [Link]()

print("Today's date is", today)

Get Date from Timestamp


We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp is t
number of seconds from 1st January 1970 at UTC to a particular date.
• Python3

from datetime import datetime

# Getting Datetime from timestamp


date_time = [Link](1887639468)
print("Datetime from timestamp:", date_time)

Output
Datetime from timestamp: 2029-10-25 16:17:48
Python defines an inbuilt module calendar that handles operations related to the calendar. In this
article, we will see the Python Program to Display Calendar.
Calendar Module in Python
The calendar module allows us to output calendars like the program and provides additional
useful functions related to the calendar. Functions and classes defined in the calendar module
use an idealized calendar, the current Gregorian calendar is extended indefinitely in both
directions. By default, these calendars have Monday as the first day of the week, and Sunday as
the last (the European convention).
Display the Python Calendar of a given Month
The code uses Python’s calendar module to print a calendar for the specified year (yy) and
month (mm). In this case, it prints the calendar for November 2017. Python Program to Display
Calendar
import calendar
yy = 2017
mm = 11
print([Link](yy, mm))

Display the Python calendar of the given Year


The code you provided uses Python’s calendar module to print a calendar for the year 2018.

import calendar
print ("The calendar of year 2018 is : ")
print ([Link](2018))

Python Math Module


Math Module consists of mathematical functions and constants. It is a built-in module made for
mathematical tasks.
The math module provides the math functions to deal with basic operations such as addition(+),
subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric,
logarithmic, and exponential functions.
In this article, we learn about the math module from basics to advanced, we will study the
functions with the help of good examples.
Constants in Math Module
The Python math module provides various values of various constants like pi, and tau. We can
easily write their values with these constants. The constants provided by the math module are :
• Euler’s Number
• Pi
• Tau
• Infinity
• Not a Number (NaN)
Let’s find the area of the circle
The code utilizes the math module in Python, defines a radius and the mathematical constant pi,
and calculates the area of a circle using the formula‘ A = pi * r * r'. It demonstrates the
application of mathematical concepts and the usage of the math module for numerical
calculations

import math
r=4
pie = [Link]
print(pie * r * r)

Numeric Functions in Math Module


In this section, we will deal with the functions that are used with number theory as well as
representation theory such as finding the factorial of a number. We will discuss these numerical
functions along with examples and use-cases.
1. Finding the ceiling and the floor value
Ceil value means the smallest integral value greater than the number and the floor value means
the greatest integral value smaller than the number. This can be easily calculated using
the ceil() and floor() method respectively.
Example:
This code imports the math module, assigns the value 2.3 to the variable a, and then calculates
and prints the ceiling and floor of a.

import math
a = 2.3
print ("The ceil of 2.3 is : ", end="")
print ([Link](a))
print ("The floor of 2.3 is : ", end="")
print ([Link](a))

Output:
The ceil of 2.3 is : 3
The floor of 2.3 is : 2
2. Finding the factorial of the number
Using the factorial() function we can find the factorial of a number in a single line of the code.
An error message is displayed if number is not integral.
Example: This code imports the math module, assigns the value 5 to the variable a, and then
calculates and prints the factorial of a.

import math
a=5
print("The factorial of 5 is : ", end="")
print([Link](a))

Output:
The factorial of 5 is : 120
3. Finding the GCD
gcd() function is used to find the greatest common divisor of two numbers passed as the
arguments.
Example: This code imports the math module, assigns the values 15 and 5 to the
variables a and b, respectively, and then calculates and prints the greatest common divisor
(GCD) of a and b.
• Python3

import math
a = 15
b=5
print ("The gcd of 5 and 15 is : ", end="")
print ([Link](b, a))

Output:
The gcd of 5 and 15 is : 5
File Handling in Python
File handling refers to the process of performing operations on a file such as creating, opening,
reading, writing and closing it, through a programming interface. It involves managing the data
flow between the program and the file system on the storage device, ensuring that data is
handled safely and efficiently.
Opening a File in Python
To open a file we can use open() function, which requires file path and mode as arguments:
# Open the file and read its contents
with open('[Link]', 'r') as file:

File Modes in Python


When opening a file, we must specify the mode we want to which specifies what we want to do
with the file. Here’s a table of the different modes available:

Mode Description Behavior

Opens the file for reading. File must exist;


Read-only mode.
r otherwise, it raises an error.

Opens the file for reading binary data. File must


Read-only in binary mode.
rb exist; otherwise, it raises an error.

Opens the file for both reading and writing. File


Read and write mode.
r+ must exist; otherwise, it raises an error.

Opens the file for both reading and writing binary


Read and write in binary mode.
rb+ data. File must exist; otherwise, it raises an error.

Opens the file for writing. Creates a new file or


Write mode.
w truncates the existing file.
Mode Description Behavior

Opens the file for writing binary data. Creates a


Write in binary mode.
wb new file or truncates the existing file.

Opens the file for both writing and reading. Creates


Write and read mode.
w+ a new file or truncates the existing file.

Opens the file for both writing and reading binary


Write and read in binary mode. data. Creates a new file or truncates the existing
wb+ file.

Opens the file for appending data. Creates a new


Append mode.
a file if it doesn’t exist.

Opens the file for appending binary data. Creates a


Append in binary mode.
ab new file if it doesn’t exist.

Opens the file for appending and reading. Creates a


Append and read mode.
a+ new file if it doesn’t exist.

Append and read in binary Opens the file for appending and reading binary
ab+ mode. data. Creates a new file if it doesn’t exist.

Creates a new file. Raises an error if the file already


Exclusive creation mode.
x exists.

Exclusive creation in binary Creates a new binary file. Raises an error if the file
xb mode. already exists.

Exclusive creation with read Creates a new file for reading and writing. Raises
x+ and write mode. an error if the file exists.
Mode Description Behavior

Exclusive creation with read Creates a new binary file for reading and writing.
xb+ and write in binary mode. Raises an error if the file exists.

Reading a File
Reading a file can be achieved by [Link]() which reads the entire content of the file. After
reading the file we can close the file using [Link]() which closes the file after reading it,
which is necessary to free up system resources.
Example: Reading a File in Read Mode (r)
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

Writing to a File
Writing to a file is done using [Link]() which writes the specified string to the file. If the file
exists, its content is erased. If it doesn’t exist, a new file is created.
Example: Writing to a File in Write Mode (w)
file = open("[Link]", "w")
[Link]("Hello, World!")
[Link]()

Writing to a File in Append Mode (a)


It is done using [Link]() which adds the specified string to the end of the file without erasing
its existing content.
Example: For this example, we will use the Python file created in the previous example.
# Python code to illustrate append() mode
file = open('[Link]', 'a')
[Link]("This will add this line")
[Link]()

Closing a File
Closing a file is essential to ensure that all resources used by the file are properly
released. [Link]() method closes the file and ensures that any changes made to the file are
saved.
file = open("[Link]", "r")
# Perform file operations
[Link]()

Introduction To GUI In Python:


Python Tkinter
Python Tkinter is a standard GUI (Graphical User Interface) library for Python which provides
a fast and easy way to create desktop applications. Tkinter provides a variety of widgets like
buttons, labels, text boxes, menus and more that can be used to create interactive user interfaces.
Tkinter supports event-driven programming, where actions are taken in response to user events
like clicks or keypresses.
Table of Content

Create First Tkinter GUI Application


To create a Tkinter Python app, follow these basic steps:
1. Import the tkinter module: Import the tkinter module, which is necessary for creating
the GUI components.
2. Create the main window (container): Initialize the main application window using the
Tk() class.
3. Set Window Properties: We can set properties like the title and size of the window.
4. Add widgets to the main window: We can add any number of widgets like buttons,
labels, entry fields, etc., to the main window to design the interface.
5. Pack Widgets: Use geometry managers like pack(), grid() or place() to arrange the
widgets within the window.
6. Apply event triggers to the widgets: We can attach event triggers to the widgets to
define how they respond to user interactions.

Tk()
To create a main window in Tkinter, we use the Tk() class. The syntax for creating a main
window is as follows:
root = [Link](screenName=None, baseName=None, className=’Tk’, useTk=1)
• screenName: This parameter is used to specify the display name.
• baseName: This parameter can be used to set the base name of the application.
• className: We can change the name of the window by setting this parameter to the
desired name.
• useTk: This parameter indicates whether to use Tk or not.
mainloop()
The mainloop() method is used to run application once it is ready. It is an infinite loop that
keeps the application running, waits for events to occur (such as button clicks) and processes
these events as long as the window is not closed.
Example:
import tkinter
m = [Link]()
'''
widgets are added here
'''
[Link]()
Tkinter Widget
There are a number of tkinter widgets which we can put in our tkinter application. Some of the
major widgets are explained below:
1. Label
It refers to the display box where we display text or image. It can have various options like font,
background, foreground, etc. The general syntax is:
w=Label(master, option=value)
• master is the parameter used to represent the parent window.
Example:
from tkinter import *
root = Tk()
w = Label(root, text='BCA Department')
[Link]()
[Link]()

2. Button
A clickable button that can trigger an action. The general syntax is:
w=Button(master, option=value)
Example:
import tkinter as tk

r = [Link]()
[Link]('Counting Seconds')
button = [Link](r, text='Stop', width=25, command=[Link])
[Link]()
[Link]()

3. Entry
It is used to input the single line text entry from the user. For multi-line text input, Text widget
is used. The general syntax is:
w=Entry(master, option=value)

Example:
from tkinter import *
master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
[Link](row=0, column=1)
[Link](row=1, column=1)
mainloop()

4. CheckButton
A checkbox can be toggled on or off. It can be linked to a variable to store its state. The general
syntax is:
w = CheckButton(master, option=value)
Example:
from tkinter import *

master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()

5. RadioButton
It allows the user to select one option from a set of choices. They are grouped by sharing the
same variable. The general syntax is:
w = RadioButton(master, option=value)
Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='FY', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='SY', variable=v, value=2).pack(anchor=W)
Radiobutton(root, text='TY', variable=v, value=3).pack(anchor=W)

mainloop()

6. Listbox
It displays a list of items from which a user can select one or more. The general syntax is:
w = Listbox(master, option=value)
Example:
from tkinter import *
top = Tk()
Lb = Listbox(top)
[Link](1, 'Python')
[Link](2, 'Java')
[Link](3, 'C++')
[Link](4, 'Any other')
[Link]()
[Link]()

7. Scrollbar
It refers to the slide controller which will be used to implement listed widgets. The general
syntax is:
w = Scrollbar(master, option=value)
Example:
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
[Link](side=RIGHT, fill=Y)
mylist = Listbox(root, yscrollcommand=[Link])
for line in range(100):
[Link](END, 'This is line number' + str(line))
[Link](side=LEFT, fill=BOTH)
[Link](command=[Link])
mainloop()

8. Menu
It is used to create all kinds of menus used by the application. The general syntax is:
window.w = Menu(master, option=value)
Example:
from tkinter import *
root = Tk()
menu = Menu(root)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=[Link])
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

9. Scale
It is used to provide a graphical slider that allows to select any value from that scale. The
general syntax is:
w = Scale(master, option=value)
Example:
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
[Link]()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
[Link]()
mainloop()

14. Progressbar
progressbar indicates the progress of a long-running task. When the button is clicked, the
progressbar fills up to 100% over a short period, simulating a task that takes time to complete.
Example:
import tkinter as tk
from tkinter import ttk
import time

def start_progress():
[Link]()

# Simulate a task that takes time to complete


for i in range(101):
# Simulate some work
[Link](0.05)
progress['value'] = i
# Update the GUI
root.update_idletasks()
[Link]()

root = [Link]()
[Link]("Progressbar Example")

# Create a progressbar widget


progress = [Link](root, orient="horizontal", length=300, mode="determinate")
[Link](pady=20)

# Button to start progress


start_button = [Link](root, text="Start Progress", command=start_progress)
start_button.pack(pady=10)
[Link]()

Common questions

Powered by AI

Tkinter widgets such as 'Entry' and 'CheckButton' enhance user interaction in Python GUI applications by providing interactive elements. The 'Entry' widget allows users to input single-line text, serving forms or data entry needs. In contrast, the 'CheckButton' offers a checkbox that users can toggle, suited for binary options like preferences or settings. These widgets, through their respective options and configurations, support capturing user input effectively for processing within the application .

Python's 'calendar' module is quite useful for generating textual representations of both monthly and yearly calendars, employing standard conventions with Monday as the first day of the week. It simplifies the display of calendar months and assists in schedule planning by making it easy to visualize date arrangements. However, its textual output format may limit interactivity and customization needed for detailed scheduling or integration with other applications, which can be a drawback for advanced planning needs .

In the Python math module, computing the greatest common divisor (GCD) uses the gcd() function, which is designed for integral arguments, while factorial calculations also expect integer input. If non-integral numbers are used in calculating factorials using the factorial() function, it results in an error since the function is not designed to handle floats or non-integers. Such strict type expectations ensure precise calculations and reliable mathematical outputs, but users must handle input verification to avoid runtime errors .

File handling in Python ensures data safety and efficiency by managing the data flow between the program and the file system, using operations like creating, reading, writing, and closing files. The 'open()' function is crucial for specifying the file path and mode, while different modes (such as 'r', 'w', 'a') define the intended operation ensuring control over file modifications. Closing a file with 'file.close()' is essential for freeing system resources and ensuring that all data modifications are saved securely .

The basic structure of a Tkinter application involves importing the tkinter module, creating a main window using Tk(), setting window properties like title and size, and adding widgets such as labels and buttons. Using geometry managers like pack(), grid(), or place() helps in arranging these widgets. The mainloop() method initiates an infinite loop that keeps the application running, handles user interactions, and processes events like button clicks. This loop is central to event-driven programming as it continuously waits for and responds to user-triggered events .

When using the 'factorial()' function in Python, providing non-integral input causes a runtime error, as the function strictly requires integer arguments. This challenge affects program stability by potentially crashing the application if input validation isn't implemented. Hence, developers must ensure input data integrity through checks and exception handling to maintain stability and avoid such disruptions in calculations .

The file modes 'w', 'a', and 'x' in Python dictate different interactions with files. 'w' (write mode) opens a file for writing, creating a new file if it doesn’t exist, or truncating its contents if it does, thus potentially erasing existing data. 'a' (append mode) opens a file for appending, preserving existing data by adding new content to the end. The 'x' (exclusive creation mode) creates a new file and raises an error if the file already exists, ensuring no accidental overwriting of files, thereby protecting file integrity .

File modes like 'r+' (read and write), 'w+' (write and read), and 'a+' (append and read) in Python offer versatile file manipulation capabilities by allowing simultaneous reading and modification, either by truncating, creating, or appending content. However, developers must use these modes cautiously, as inappropriate use may result in unintended data loss, particularly with 'w+', which overwrites existing data. Ensuring backup and clarity of operation purpose can mitigate such risks .

The 'Listbox' widget in Tkinter presents a scrollable collection of selectable items, ideal for user selection lists within a main window. It is generally used to manage lists of items allowing multiple selections or dynamic list content management. In contrast, the 'Menu' widget creates application menus with cascading options, facilitating navigation within the application rather than displaying selectable content. While 'Listbox' focuses on content display, 'Menu' emphasizes command organization, both enhancing interface design by serving distinct interactive purposes .

The Python 'math' module provides a comprehensive collection of functions and constants enabling various numerical calculations. Key functions include trigonometric operations (such as sin, cos), logarithmic operations (such as log, log10), and exponential functions (such as exp). Constants like Euler's Number and Pi also aid in precise mathematical computations. Additionally, the module supports finding the ceiling and floor of numbers and calculating factorials, making it essential for both elementary and complex tasks .

You might also like