python unit.4
python unit.4
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., mymodule.py)
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 = math.pi
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.
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 program to
# print current date
from datetime import date
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(calendar.month(yy, mm))
import calendar
print ("The calendar of year 2018 is : ")
print (calendar.calendar(2018))
import math
r=4
pie = math.pi
print(pie * r * r)
import math
a = 2.3
print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))
print ("The floor of 2.3 is : ", end="")
print (math.floor(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(math.factorial(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 (math.gcd(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('abc.txt', 'r') as file:
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.
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 file.read() which reads the entire content of the file. After
reading the file we can close the file using file.close() 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("ABC.txt", "r")
content = file.read()
print(content)
file.close()
Writing to a File
Writing to a file is done using file.write() 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("ABC.txt", "w")
file.write("Hello, World!")
file.close()
Closing a File
Closing a file is essential to ensure that all resources used by the file are properly
released. file.close() method closes the file and ensures that any changes made to the file are
saved.
file = open("geeks.txt", "r")
# Perform file operations
file.close()
Tk()
To create a main window in Tkinter, we use the Tk() class. The syntax for creating a main
window is as follows:
root = tk.Tk(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 = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
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')
w.pack()
root.mainloop()
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 = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()
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)
e1.grid(row=0, column=1)
e2.grid(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)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()
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)
scrollbar.pack(side=RIGHT, fill=Y)
mylist = Listbox(root, yscrollcommand=scrollbar.set)
for line in range(100):
mylist.insert(END, 'This is line number' + str(line))
mylist.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=mylist.yview)
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)
root.config(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=root.quit)
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)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
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():
progress.start()
root = tk.Tk()
root.title("Progressbar Example")