Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

python unit.4

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python unit.4

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

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., 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.

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 –
datetime.tzinfo()
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 datetime.date(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 = date.today()

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 = datetime.fromtimestamp(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(calendar.month(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 (calendar.calendar(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 = math.pi
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 (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:

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 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()

Writing to a File in Append Mode (a)


It is done using file.write() 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('ABC.txt', 'a')
file.write("This will add this line")
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()

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 = 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()

# Simulate a task that takes time to complete


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

root = tk.Tk()
root.title("Progressbar Example")

# Create a progressbar widget


progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate")
progress.pack(pady=20)

# Button to start progress


start_button = tk.Button(root, text="Start Progress", command=start_progress)
start_button.pack(pady=10)
root.mainloop()

You might also like