0% found this document useful (0 votes)
29 views53 pages

Module:4: Modules and Packages, Libraries, Files and GUI

This document covers various aspects of Python programming, including the use of modules and packages for code organization, file handling techniques, and libraries for random number generation and mathematical operations. It provides detailed examples of creating and using modules and packages, as well as handling files through reading and writing operations. Additionally, it discusses date and time functions, and the use of libraries such as math, random, and numpy for various programming tasks.

Uploaded by

eshauppin1
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)
29 views53 pages

Module:4: Modules and Packages, Libraries, Files and GUI

This document covers various aspects of Python programming, including the use of modules and packages for code organization, file handling techniques, and libraries for random number generation and mathematical operations. It provides detailed examples of creating and using modules and packages, as well as handling files through reading and writing operations. Additionally, it discusses date and time functions, and the use of libraries such as math, random, and numpy for various programming tasks.

Uploaded by

eshauppin1
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
You are on page 1/ 53

Module:4: Modules and Packages,

Libraries, Files and GUI


Modules and Packages, Random Library, Math Library, Date and Time functions, File
Handling- Reading files, Writing files in python, Understanding read functions, read(),
readline(), readlines(). Understanding write functions, write() and writelines()
Manipulating file pointer using seek Programming, using file operations., GUI
Programming: Tkinter Introduction, Tkinter and Python Programming, Tk Widgets,
Tkinter Examples. Python programming with IDE.
Modules and Packages in Python
Introduction
•Python is a powerful and versatile programming
language used in various applications.
•As projects grow larger, organizing code
becomes essential.
•Python provides two essential mechanisms for
organizing code: Modules and Packages.
Modules

• Modules are Python files containing functions,


classes, and variables.
• They enable code reusability and help keep
code organized.
• Each module acts as a separate namespace,
reducing name conflicts.
Creating a Module
•Let's create a simple module named "math_operations.py"
with basic math functions.
# math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


return a / b
Using a Module
Import the module and access its functions using the dot notation.
# main.py

import math_operations

result_add = math_operations.add(5, 3)
result_subtract = math_operations.subtract(10, 4)
result_multiply = math_operations.multiply(2, 6)
result_divide = math_operations.divide(10, 2)

print(result_add) # Output: 8
print(result_subtract) # Output: 6
print(result_multiply) # Output: 12
print(result_divide) # Output: 5.0
Packages

•Packages are directories containing multiple modules,

allowing hierarchical organization.

•They help manage large projects by grouping related code

together.
Creating a Package
Let's go through the process of creating a package named my_package with two
modules (module1.py and module2.py) in PyCharm and then using the package in a
main.py file.
Step 1: Open PyCharm
Open PyCharm and create a new project or open an existing one where you want to
create the package.
Step 2: Create a New Directory for the Package
Right-click on the project folder in the Project Explorer pane on the left side of the
PyCharm window.
Select "New" and then choose "Directory."
Name the directory my_package and click "OK."
Step 3: Create Python Modules

• Inside the my_package directory, create two Python modules named module1.py and
module2.py.
• Right-click on the my_package directory.
• Select "New" and then choose "Python File."
• Name the first file module1.py and click "OK."
• Repeat the process to create the second file named module2.py.
Step 4: Add Python Code to the Modules

Edit the module1.py and module2.py files and add some Python code to them.

# my_package/module1.py

def func1():
print("Function 1 from module 1")

# my_package/module2.py

def func2():
print("Function 2 from module 2")
Step 5: Create __init__.py

• Right-click on the my_package directory (not the modules) and select "New" ->
"Python File."
• Name the file __init__.py and click "OK."
• Your package structure should now look like this:

my_package/
__init__.py
module1.py
module2.py
Step 6: Using the Package

• Create a new Python file named main.py in the project folder (not inside the
my_package directory).
• Inside main.py, import and use the functions from the package.

# main.py

from my_package import module1, module2

module1.func1() # Output: Function 1 from module 1


module2.func2() # Output: Function 2 from module 2
Step 7: Run the Main Program

• Right-click anywhere inside main.py editor window.


• Select "Run 'main'."
The output in the "Run" tool window at the bottom of the PyCharm window should be:

Function 1 from module 1


Function 2 from module 2
Random libraries
• Random libraries in Python are essential for various applications, including
simulations, cryptography, and statistical analyses.
• Choose the appropriate random library based on your requirements: random,
secrets, or numpy.random.
The random Module
• The random module is a built-in Python library for generating pseudo-random
numbers.
• Pseudo-random numbers are generated by a computer program using a starting value
called a seed.
Generating Random Numbers
• The random module offers functions to generate random numbers:
• random() - Returns a random float in the range [0.0, 1.0).
• randint(a, b) - Returns a random integer in the range [a, b].
• randrange(start, stop, step) - Returns a random element from the given range.
Example: Generating Random Numbers

import random

# Generate a random float between 0 and 1


random_float = random.random()

# Generate a random integer between 1 and 10


random_int = random.randint(1, 10)

# Generate a random element from the list


fruits = ['apple', 'banana', 'cherry', 'orange']
random_fruit = random.choice(fruits)
The secrets Module
• The secrets module provides more secure random number generation.
• It is suitable for cryptographic applications and generating secure tokens.
Generating Cryptographically Secure Random Data
• The secrets module offers functions for secure random data:
• token_bytes(n) - Returns n random bytes.
• token_hex(n) - Returns a random string of n hexadecimal digits.
• token_urlsafe(n) - Returns a random URL-safe string of n characters.
Example: Generating Secure Tokens

import secrets

# Generate 16 bytes of secure random data


secure_bytes = secrets.token_bytes(16)

# Generate a random URL-safe string of length 20


secure_token = secrets.token_urlsafe(20)
The numpy.random Module
• NumPy provides additional random functionality through the numpy.random
module.
• NumPy is widely used for numerical computations and data manipulation.
Generating Random Data with NumPy
• NumPy's random module allows generating random arrays:
numpy.random.rand(shape) - Returns an array of given shape with random floats in [0.0,
1.0).
• numpy.random.randint(low, high, size) - Returns an array of given size with random
integers in [low, high).
Example: Generating Random Arrays with NumPy

import numpy as np

# Generate a 3x3 array of random floats


random_floats = np.random.rand(3, 3)

# Generate a 1D array of 5 random integers between 1 and 100


random_integers = np.random.randint(1, 100, 5)
Math Library in Python
The Python math library provides various mathematical operations and functions for numeric
calculations. Here are some of the commonly used functions:
✔ math.sqrt(x): Returns the square root of x.
✔ math.pow(x, y): Returns x raised to the power of y.
✔ math.exp(x): Returns the exponential value of x (e^x).
✔ math.log(x): Returns the natural logarithm of x (base e).
✔ math.log10(x): Returns the base-10 logarithm of x.
✔ math.sin(x), math.cos(x), math.tan(x): Returns the sine, cosine, and tangent of x (in
radians).
✔ math.degrees(x), math.radians(x): Converts between degrees and radians.
✔ math.ceil(x): Returns the smallest integer greater than or equal to x.
✔ math.floor(x): Returns the largest integer less than or equal to x.
✔ math.fabs(x): Returns the absolute value of x.
✔ math.factorial(x): Returns the factorial of x.
✔ math.isqrt(x): Returns the integer square root of x.
✔ math.gcd(x, y): Returns the greatest common divisor of x and y.
✔ math.pi and math.e: Constants for π (pi) and Euler's number (e).
Example Usage: import math
# Example usage
print(math.sqrt(25)) # Output: 5.0
print(math.sin(math.pi / 2)) # Output: 1.0
print(math.factorial(5)) # Output: 120
Date and Time Functions in Python
• Python offers a robust set of built-in modules for working with date and time data.
• The primary modules for handling date and time are datetime and time.
• Python provides powerful date and time functions through the datetime and time
modules.
• Formatting dates and times as strings enables better display and interoperability.
• For handling timezones, the pytz module is a valuable addition to Python's built-in
capabilities.
Working with Dates using the datetime module
• Importing the datetime module: from datetime import datetime
• Creating a date object: date_obj = datetime(year, month, day)
• Getting the current date: current_date = datetime.now()
• Extracting date components: year = date_obj.year, month = date_obj.month, day =
date_obj.day
Formatting Dates as Strings
• Converting dates to strings: date_str = date_obj.strftime(format)
• Common date format codes:
❑ %Y: 4-digit year
❑ %m: 2-digit month
❑ %d: 2-digit day
❑ %H: 2-digit hour (24-hour format)
❑ %M: 2-digit minute
❑ %S: 2-digit second
❑ %A: Full weekday name
❑ %B: Full month name
Working with Time using the time module
• Importing the time module: import time
• Getting the current time in seconds since the epoch: current_time = time.time()
• Converting seconds since the epoch to a readable time: readable_time =
time.ctime(current_time)
Formatting Time as Strings
• Converting time to strings: time_str = time.strftime(format)
• Common time format codes:
%H: 2-digit hour (24-hour format)
%M: 2-digit minute
%S: 2-digit second
Working with Date and Time Differences
• Finding the difference between two dates: time_difference = date_obj1 - date_obj2
• Getting the difference in seconds: time_difference.total_seconds()
• Finding the difference between two times: time_difference = time_obj1 - time_obj2
Timezones and pytz module
• Handling timezones in Python using the pytz module.
• Importing the pytz module: import pytz
• Getting a timezone object: timezone = pytz.timezone('timezone_name')
• Localizing a datetime object: localized_datetime = timezone.localize(datetime_obj)
File handling in Python
File handling in Python refers to the process of working with files on the computer's
filesystem. It involves tasks such as reading data from files, writing data to files, and
performing various file-related operations, such as creating, deleting, and modifying
files. Python provides built-in functions and methods to make file handling
straightforward and convenient.

The open() function is the primary tool for file handling in Python. It allows you to open a
file and get a file object that you can use to perform file operations. The basic syntax of the
open() function is:
file = open('filename', 'mode’)

Here, 'filename' is the name of the file you want to open, and 'mode' specifies the purpose
for which you want to open the file (e.g., read, write, append, etc.).
Some common file modes are:

'r': Read mode. The file is opened for reading (default).

'w': Write mode. The file is opened for writing. If the file already exists, its

content will be truncated. If the file doesn't exist, a new file will be created.

'a': Append mode. The file is opened for writing, but data is appended to the

end of the file. If the file doesn't exist, a new file will be created.

'b': Binary mode. Used in combination with other modes for binary files (e.g.,

'rb' for reading binary files).


Once you have opened the file, you can perform various operations:

Reading from a File:

read(size): Reads size number of characters from the file. If size is not specified, it reads

the entire file content.

readline(): Reads a single line from the file.

readlines(): Reads all lines from the file and returns them as a list.
Once you have opened the file, you can perform various operations:

Reading from a File:

read(size): Reads size number of characters from the file. If size is not specified, it reads

the entire file content.

# Open the file in read mode

with open("sample.txt", "r") as file:

content = file.read()

print(content)
Once you have opened the file, you can perform various operations:

Reading from a File:

readline(): Reads a single line from the file.

# Open the file in read mode


with open("sample.txt", "r") as file:
line = file.readline()
while line:
print(line.strip()) # Use strip() to remove the newline character
line = file.readline()
Once you have opened the file, you can perform various operations:

Reading from a File:

readlines(): Reads all lines from the file and returns them as a list.

# Open the file in read mode

with open("sample.txt", "r") as file:

lines_list = file.readlines()

print(lines_list)
Writing to a File:
The write() function in Python is used to write data to a file that has been opened in write or
append mode. It allows you to add content to the file, either creating a new file or
overwriting the existing content, depending on the file mode.
file.write(data)
Parameters:
data: The data to be written to the file. It can be a string or a bytes object (in binary mode).
Return Value:
The write() function does not return anything. It writes the data to the file and moves the file
pointer to the end of the written data.
Example: Writing to a File in Write Mode
# Open a file in write mode
with open("example.txt", "w") as file:
file.write("Hello, this is an example.\n")
file.write("We are writing to a file in Python.\n")
In this example, we open a file named "example.txt" in write mode using the open()
function with mode "w". We use a with statement to automatically close the file
after we are done writing.
We then use the write() method of the file object to write two lines of text to the
file. The \n at the end of each line represents a newline character to add a line break
between the two lines.
After running this code, the "example.txt" file will contain the following content:
Hello, this is an example.
We are writing to a file in Python.
Example: Writing to a File in Append Mode
# Open a file in append mode
with open("example.txt", "a") as file:
file.write("This is an additional line appended to the file.\n")
In this example, we open the same "example.txt" file, but this time, we use the
append mode "a" in the open() function. This mode allows us to add data to the end
of the existing content without overwriting it.
We use the write() method to append an additional line to the end of the file.
After running this code, the "example.txt" file will have the following content:
Hello, this is an example.
We are writing to a file in Python.
This is an additional line appended to the file.

It is important to note that the write() function does not automatically add
newline characters, so if you want to write multiple lines, you need to include
\n to separate them. Additionally, be cautious when using the write function
in write mode ("w"), as it will overwrite the existing content of the file. If you
want to preserve the existing content and add new data, use append mode
("a").
Manipulating file pointer using seek
To manipulate the file pointer using seek, you'll need to open the file in an
appropriate mode that allows reading or writing. Then, you can use the
seek() method to move the file pointer to the desired position within the file.
Here's how you can do it in Python:
Opening a file and manipulating the file pointer for reading:
# Open the file in read mode ('r')
with open('example.txt', 'r') as file:
# Move the file pointer to the 10th character from the beginning of the file
file.seek(10)

# Read the content from the current position


content = file.read()
print(content)
Opening a file and manipulating the file pointer for writing:
# Open the file in write mode ('w')
with open('example.txt', 'w') as file:
# Move the file pointer to the 5th character from the beginning of the file
file.seek(5)
# Write content from the current position
file.write("Hello, World!")
The seek() method takes two arguments: the offset (number of bytes or
characters to move) and an optional whence parameter, which
determines the reference position for the offset calculation.
By default, whence is set to
• 0 (meaning the offset is relative to the beginning of the file)
• 1 (current position)
• 2 (end of the file).
However, for text files in Python, the seek() method mainly works with a
position relative to the beginning of the file, using the number of
characters.
An example program that demonstrates the use of the seek() method with all three whence
parameters (0, 1, and 2) in Python:

def demonstrate_seek(file_path):
with open(file_path, 'r+') as file:
# Read the initial content of the file
print("Initial content:")
print(file.read())

# Seek to the beginning of the file (whence=0)


file.seek(0, 0)
file.write("Seek method demonstration.\n")

# Seek to the current position (whence=1) and write


file.seek(0, 1)
file.write("Current position: {}\n".format(file.tell()))
# Seek to the end of the file (whence=2) and write
file.seek(0, 2)
file.write("End of the file.\n")

# Seek backward 20 characters from the end of the file and write
file.seek(-20, 2)
file.write("Going back 20 characters.\n")

# Move 10 characters forward from the current position and write


file.seek(10, 1)
file.write("Going forward 10 characters.\n")

# Reset the file pointer to the beginning and read the final content
file.seek(0, 0)
print("Final content:")
print(file.read())

if __name__ == "__main__":
# Seek to the end of the file (whence=2) and write
file.seek(0, 2)
file.write("End of the file.\n")

# Seek backward 20 characters from the end of the file and write
file.seek(-20, 2)
file.write("Going back 20 characters.\n")

# Move 10 characters forward from the current position and write


file.seek(10, 1)
file.write("Going forward 10 characters.\n")

# Reset the file pointer to the beginning and read the final content
file.seek(0, 0)
print("Final content:")
print(file.read())

if __name__ == "__main__":
file_path = "example.txt"
with open(file_path, "w") as file:
file.write("0123456789ABCDEFGHIJ")

demonstrate_seek(file_path)
Introduction to Tkinter and Python Programming
❑ Tkinter is a standard Python library used for creating graphical user interfaces
(GUI).
❑ It provides a set of widgets and functions that allow developers to build
interactive and visually appealing desktop applications.
❑ Tkinter is based on the Tcl/Tk GUI toolkit, which is widely used and
well-supported across different platforms.
❑ Python, on the other hand, is a versatile and popular programming language
known for its simplicity, readability, and extensive libraries.
❑ Combining Python with Tkinter allows developers to build cross-platform GUI
applications efficiently.
Why use Tkinter?
• Easy to learn and use: Tkinter's straightforward API and simple syntax make it easy
for beginners to grasp and start building GUI applications quickly.
• Cross-platform: Tkinter is available on most operating systems, including Windows,
macOS, and Linux, ensuring that your application can run on multiple platforms
without modification.
• Widely supported: Being a part of the Python standard library, Tkinter is
well-maintained and actively supported, ensuring compatibility with future Python
versions.
• Large community: The popularity of Python and Tkinter means that you can find
numerous tutorials, resources, and community support online.
Getting Started with Tkinter:
Tkinter is included in the Python standard library, so you don't need to install any
additional packages.
Importing Tkinter:
To begin, import the tkinter module:
import tkinter as tk

Creating a Tkinter Application:


The fundamental element of a Tkinter application is the Tk object, representing the main
window. To create a simple window, you can do the following:
root = tk.Tk() # Create the main window
root.mainloop() # Start the main event loop
Adding Widgets:
Tkinter offers various widgets like buttons, labels, textboxes, etc., to build the GUI. You
can add them to the main window using geometry managers (pack, grid, place).
# Example: Adding a label and button
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()

button = tk.Button(root, text="Click Me!", command=some_function)


button.pack()
Handling Events:
Widgets like buttons can trigger events (e.g., button clicks). You can define
functions to handle these events.
def some_function():
print("Button clicked!")

button = tk.Button(root, text="Click Me!", command=some_function)


Main Event Loop:
The mainloop() method runs the event loop, which waits for user actions and responds
to them. It's essential to include this at the end of your Tkinter application to make it
interactive.
root.mainloop()
Some examples of Tkinter programs that include various widgets:
Example 1: Simple Tkinter Window with Label
import tkinter as tk
root = tk.Tk()
root.title("Basic Tkinter Window")
root.geometry("300x200")

label = tk.Label(root, text="Hello, Tkinter!")


label.pack()

root.mainloop()
Example 2: Tkinter Window with Button and Label

import tkinter as tk

def on_button_click():
label.config(text="Button clicked!")

root = tk.Tk()
root.title("Tkinter Button Example")

label = tk.Label(root, text="Press the button!")


label.pack()

button = tk.Button(root, text="Click Me!", command=on_button_click)


button.pack()

root.mainloop()
Example 3: Tkinter Entry and Output Example
import tkinter as tk

def show_output():
output_label.config(text="Your name is: " + entry.get())

root = tk.Tk()
root.title("Tkinter Entry Example")

entry = tk.Entry(root, width=30)


entry.pack()

output_label = tk.Label(root, text="")


output_label.pack()

button = tk.Button(root, text="Show Name", command=show_output)


button.pack()

root.mainloop()
Example 4: Check Button and Radio Button
import tkinter as tk
checkbutton1 = tk.Checkbutton(root, text="Option 1",
def show_options(): variable=var1)
selected_options = "Selected options: " checkbutton2 = tk.Checkbutton(root, text="Option 2",
if var1.get(): variable=var2)
selected_options += "Option 1 " checkbutton3 = tk.Checkbutton(root, text="Option 3",
if var2.get(): variable=var3)
selected_options += "Option 2 "
if var3.get(): checkbutton1.pack()
selected_options += "Option 3 " checkbutton2.pack()
output_label.config(text=selected_options) checkbutton3.pack()

def show_selected_language(): output_label = tk.Label(root, text="")


selected_language = "Selected language: " + output_label.pack()
selected_language_var.get()
output_label2.config(text=selected_language) show_button = tk.Button(root, text="Show Checkbutton
Options", command=show_options)
root = tk.Tk() show_button.pack()
root.title("Tkinter Checkbutton and Radiobutton Example")
# Add Radiobutton example
var1 = tk.BooleanVar() selected_language_var = tk.StringVar()
var2 = tk.BooleanVar() selected_language_var.set("Python")
var3 = tk.BooleanVar()
radiobutton1 = tk.Radiobutton(root, text="Python", show_language_button = tk.Button(root, text="Show Selected
variable=selected_language_var, value="Python") Language", command=show_selected_language)
radiobutton2 = tk.Radiobutton(root, text="Java", show_language_button.pack()
variable=selected_language_var, value="Java")
radiobutton3 = tk.Radiobutton(root, text="C++", root.mainloop()
variable=selected_language_var, value="C++")
output_label = tk.Label(root, text="")
radiobutton1.pack() output_label.pack()
radiobutton2.pack()
radiobutton3.pack() show_button = tk.Button(root, text="Show Options",
command=show_options)
output_label2 = tk.Label(root, text="") show_button.pack()
output_label2.pack()
root.mainloop()

You might also like