0% found this document useful (0 votes)
20 views

Python 2 [Two]

A simple Python learning document for freshers. Python 2.

Uploaded by

sadiqmw2014
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python 2 [Two]

A simple Python learning document for freshers. Python 2.

Uploaded by

sadiqmw2014
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

INTRODUCTION TO

OBJECT ORIENTED PROGRAMMING

IN

PYTHON
{Lecture Note II}

Compiled by

SADIQ MOHAMMED WAZIRI


(ND, B.TECH., M.SC. CS)
PYTHON’S LIBRARIES
Python's standard library is extensive and includes a wide range of modules and packages that
provide functionality for various tasks and deciding which library to use depends on the specific
requirements of your project. The exact number of standard libraries can change with different
Python versions, but there are several modules that are considered standard across all Python
installations. As of Python 3.10, there are over 200 standard libraries.
Some commonly used standard libraries in Python include:
1. Built-in Functions: Functions like print(), len(), and range() are part of the built-in
functions and do not require import statements.
2. Data Types and Structures: Modules for working with data structures like lists (list),
dictionaries (dict), sets (set), and tuples (tuple).
3. File I/O and OS: Modules for file operations (os, os.path, shutil), working with
directories, and interacting with the operating system.
4. Mathematics: Modules for mathematical operations (math, random), complex numbers
(cmath), and decimal arithmetic (decimal).
5. Dates and Time: Modules for working with dates and time (datetime, time, calendar).
6. Regular Expressions: Module for working with regular expressions (re).
7. Networking: Modules for working with network protocols (socket, http, urllib).
8. Databases: Modules for database interactions (sqlite3, dbm).
9. Debugging and Profiling: Modules for debugging (pdb) and profiling (cProfile, profile).
10. Testing: Modules for testing (unittest, doctest).
11. Data Serialization: Modules for data serialization and deserialization (json, pickle).
12. Concurrency and Threading: Modules for concurrent programming (threading,
multiprocessing).
13. Cryptographic Services: Modules for cryptographic operations (hashlib, hmac, ssl).
14. GUI Programming: Modules for graphical user interfaces (tkinter).
15. Graphics and Visualization: Modules for working with graphics and visualization
(turtle, pygame, matplotlib).
...and many more.
The Python Standard Library documentation provides detailed information about all the modules
available in the standard library.
You can explore these modules (in https://docs.python.org/3/library) based on your specific
programming needs. Python's rich standard library is one of its strengths, making it versatile for
various applications.

THE IMPORT STATEMENT


The ‘import’ statement in Python is used to bring in external modules or libraries into your
code. It allows you to access the functionality provided by these modules, extending the

2
November, 2023
capabilities of your Python programs. Here are a few reasons why the import statement is
essential:
1. Modularity and Reusability
Python programs can be organized into separate modules, each focusing on specific tasks
or functionalities.
The import statement enables you to reuse code from other modules, promoting
modularity and reducing redundancy.
2. Access to External Libraries
Python has a vast standard library and an extensive ecosystem of third-party libraries.
The import statement allows you to access the functionalities provided by these external
libraries, expanding the capabilities of your programs without having to write everything
from scratch.
3. Namespace Management
The import statement helps manage namespaces by preventing naming conflicts.
For example, if two modules have functions with the same name, you can import them
under different names to avoid conflicts.
4. Code Readability
Importing modules makes your code more readable and understandable. It indicates
explicitly where certain functions or classes come from.
Readers of your code can quickly identify which external resources your program relies
on.
5. Code Organization
The import statement supports code organization. You can separate your program logic
into different files or packages and import them as needed.
This enhances code maintainability and makes it easier to collaborate with others.
6. Dynamic Loading
Python allows dynamic loading of modules, meaning you can import modules at runtime,
based on certain conditions.
This flexibility allows you to load only the modules needed for specific parts of your
program, improving resource efficiency.
Here's a simple example to illustrate the import statement:
# Importing the math module to use its functions
import math

# Using functions from the math module


print(math.sqrt(25)) # Calculates the square root of 25

3
November, 2023
In the above example, import math brings the entire math module into the current namespace,
allowing for the use of one of its functions, the sqrt().
Overall, the import statement is a fundamental feature in Python that facilitates code
organization, reuse, and access to a wide range of functionalities provided by the standard library
and external libraries.

GRAPHICS AND VISUALIZATION (Working with the “turtle” library)


You can draw plain shapes in Python using various libraries. Turtle is one of the commonly used
libraries for creating graphical applications, including drawing shapes. It is a built-in Python
module that provides a simple way to create graphics and drawings. It should be noted that turtle
doesn’t need to be installed separately if Python is already installed. Libraries like turtle are
standard libraries in Python, which means they come bundled with Python by default. You can
start using these libraries without any additional installation steps. All one needs to do is to
import them in their Python scripts, and then begin drawing shapes with turtle.
Here's an example of how to draw basic shapes (square, triangle, and circle) using the turtle
module:
import turtle

# Create a turtle # Draw a triangle


screen pen.penup()
screen = pen.goto(-50, -50)
turtle.Screen() pen.pendown()
for _ in range(3):
# Create a turtle pen.forward(100)
object pen.right(120)
pen = turtle.Turtle()
# Draw a circle
# Draw a square pen.penup()
pen.penup() pen.goto(0, -150)
pen.goto(-50, 50) pen.pendown()
pen.pendown() pen.circle(50)
for _ in range(4):
pen.forward(100) # Close the turtle graphics window
pen.right(90) when clicked
screen.exitonclick()
provides a simple way to create graphics and
drawings.
You can draw plain shapes in Python using
various libraries. One of the commonly used Here's an example of how to draw basic
libraries for creating graphical applications, shapes (square, triangle, and circle) using
including drawing shapes, is `turtle`. the `turtle` module:
`Turtle` is a built-in Python module that

4
November, 2023
import turtle
# Draw a triangle
# Create a turtle pen.penup()
screen pen.goto(-50, -50)
screen = pen.pendown()
turtle.Screen() for _ in range(3):
pen.forward(100)
# Create a turtle pen.right(120)
object
pen = turtle.Turtle() # Draw a circle
pen.penup()
# Draw a square pen.goto(0, -150)
pen.penup() pen.pendown()
pen.goto(-50, 50) pen.circle(50)
pen.pendown()
for _ in range(4): # Close the turtle graphics window
pen.forward(100) when clicked
pen.right(90) screen.exitonclick()

In the example, the turtle moves to the specified positions and draws the shapes. The positions,
sizes, and angles can be modified to create different shapes. When the code is run, a window will
pop up displaying the drawn shapes. The window closes by clicking inside it.

Try to experiment with the code to create more complex shapes or combine multiple shapes to
create interesting patterns. The `turtle` module provides various methods for controlling the
turtle's movement, direction, and pen settings, allowing you to create a wide range of drawings
and graphics.

BASIC TURTLE COMMANDS


Creating a Turtle
To create a turtle, use the turtle.Turtle() constructor. You can assign it to a variable, and then use
that variable to control the turtle.

import turtle
t = turtle.Turtle()

Moving the Turtle


t.forward(distance): Moves the turtle forward by the specified distance.
t.backward(distance): Moves the turtle backward by the specified distance.
t.right(angle): Turns the turtle to the right by the specified angle in degrees.
t.left(angle): Turns the turtle to the left by the specified angle in degrees.

Drawing Commands
t.pendown(): Puts the pen down, so the turtle will draw while moving.

5
November, 2023
t.penup(): Lifts the pen up, so the turtle will not draw while moving.
t.pensize(width): Sets the width of the pen.
t.pencolor(color): Sets the pen color.

A sample code for drawing a square with turtle


import turtle

# Create a turtle
t = turtle.Turtle()

# Draw a square
for _ in range(4):
t.forward(100) # Move forward by 100 units
t.right(90) # Turn right by 90 degrees

# Close the turtle graphics window when clicked


turtle.done()

Here, the turtle moves forward by 100 units and turns right by 90 degrees, repeating this process
four times to create a square.

ADVANCED TURTLE COMMANDS


Repeating Patterns
You can use loops to create intricate patterns. For example, to draw a circle, you can simulate it
using a polygon with many sides.
User Interaction
turtle.onclick(function): Calls the specified function when the turtle window is clicked.
turtle.onkey(function, key): Calls the specified function when the specified key is pressed.

Customizing the Turtle Window


turtle.bgcolor(color): Sets the background color of the turtle window.
turtle.title(title): Sets the title of the turtle window.
turtle.setup(width, height): Sets the dimensions of the turtle window.
Example: Drawing a Circle Using Polygons:
import turtle
# Create a turtle
t = turtle.Turtle()
# Draw a circle using polygons
num_sides = 36 # Number of sides to approximate a circle
side_length = 20 # Length of each side of the polygon

6
November, 2023
for _ in range(num_sides):
t.forward(side_length) # Move forward by the side length
t.right(360 / num_sides) # Turn right by the angle for the
polygon
# Close the turtle graphics window when clicked
turtle.done()

Here, the turtle approximates a circle by drawing a polygon with 36 sides.

GUI PROGRAMMING (Working with the “tkinter” library)


Tkinter is the library for graphical user interfaces. As a standard library, one only imports it and
start creating GUI applications with it.

BASIC TKINTER CONCEPTS


Creating a GUI Window
To create a basic window, you can use the Tk() class from the tkinter module:

import tkinter as tk

root = tk.Tk() # Create the root window


root.mainloop() # Start the main event loop

The mainloop() function runs the GUI application and waits for user interactions.

Widgets
Labels: Used to display text or images.
Buttons: Trigger actions when clicked.
Entry: Allows users to input text.
Frames: Containers for organizing widgets.
Canvas: Provides a drawing area for custom graphics.
Checkbuttons: Allows users to select multiple options.
Radiobuttons: Allows users to select one option from several.
Listbox: Displays a list of items.
Menu: Creates menu bars and dropdown menus.

Example: Creating a Simple GUI Application with a Button and Label:

import tkinter as tk

# Function to be called when the button is clicked


def on_button_click():

7
November, 2023
label.config(text="Hello, " + entry.get())

# Create the main window


root = tk.Tk()
root.title("Simple GUI Application")

# Create a label
label = tk.Label(root, text="Enter your name:")
label.pack()

# Create an entry field


entry = tk.Entry(root)
entry.pack()

# Create a button
button = tk.Button(root, text="Submit", command=on_button_click)
button.pack()

# Start the main event loop


root.mainloop()

In the given example, a GUI window with a label, an entry field, and a button is created. When
the user enters their name in the entry field and clicks the button, the label's text is updated to
greet the user.

More Advanced Concepts


Layout Management
pack(): Organizes widgets in blocks before placing them in the parent widget.
grid(): Organizes widgets in a table-like structure.
place(): Places widgets using absolute positioning.
Event Handling
You can bind functions to events such as button clicks, keypresses, mouse movements, etc.
Dialog Boxes
tkinter provides dialog boxes for messages, warnings, errors, file selection, and more.
Customizing Widgets
You can change widget appearance, fonts, colors, etc., to match the desired style.
Menu Bars and Menus
Create menu bars and dropdown menus for your application.

Example: Creating a Menu Bar with tkinter.

import tkinter as tk
from tkinter import messagebox

# Function to show an about message


def show_about():

8
November, 2023
messagebox.showinfo("About", "This is a simple tkinter
application.")

# Create the main window


root = tk.Tk()
root.title("Menu Bar Example")

# Create a menu bar


menu_bar = tk.Menu(root)

# Create a file menu


file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open")
file_menu.add_command(label="Save")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

# Create a help menu


help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About", command=show_about)

# Add menus to the menu bar


menu_bar.add_cascade(label="File", menu=file_menu)
menu_bar.add_cascade(label="Help", menu=help_menu)

# Configure the menu bar


root.config(menu=menu_bar)

# Start the main event loop


root.mainloop()

In the example, a menu bar with "File" and "Help" menus is created. The "About" option under
the "Help" menu displays an informational message when clicked.
These are just some of the basic and more advanced concepts of tkinter. Exploring the official
tkinter documentation and tutorials can help learn more about creating sophisticated GUI
applications tailored to your specific needs.

MODULAR PROGRAMMING IN PYTHON


Python does have a concept similar to sub-programs or modules in other programming languages
like QBasic. In Python, modules are created and reused in other Python scripts: These modules
are separate Python files containing functions, classes, and variables. Modularity (and
maintainability) is achieved by organizing code into modules.

9
November, 2023
Creating a Module
Let's say you have a Python file called “mymodule.py” containing the following functions:

# mymodule.py

def greet(name):
return f"Hello, {name}!"

def add_numbers(a, b):


return a + b

Using the Module in Another Python Script:


You can use the functions defined in mymodule.py in another Python script by importing the
module as shown below:

# main.py

import mymodule

name = "Yusuf"
result = mymodule.greet(name)
print(result)

num1 = 10
num2 = 20
sum_result = mymodule.add_numbers(num1, num2)
print(f"The sum of {num1} and {num2} is: {sum_result}")

The “mymodule” module is imported into the “main.py” script, and the functions greet and
add_numbers are used. This allows one to organize one’s code into smaller, reusable pieces,
similar to the concept of sub-programs or modules in other programming languages.
Python doesn't use the term "sub-programs" explicitly, but the concept of modules achieves the
same goal—encouraging modular and reusable code. Python's approach to modules is flexible
and aligns with the language's focus on simplicity and readability.

SIMPLE PROJECTS (Using the Pygame Library).


Pygame is a popular Python library for creating 2D games. It provides functions and classes for
handling graphics, sound, input, and more.

10
November, 2023
To create a simple game using Pygame, for eaxmple, we'll create a basic game where the player
controls a character that can move left and right to avoid obstacles falling from the top of the
screen.
First, make sure you have Pygame installed. You can install it using “pip” if you haven't already:
pip install pygame

Project 1
Here is an example of a basic game created where the player controls a character that can move
left and right to avoid obstacles falling from the top of the screen.
import pygame
import random

# Initialize Pygame
pygame.init()

# Constants
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)

# Initialize the game window


window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Dodge the Obstacles!")

# Load game assets


player_image = pygame.image.load("player.png")
player_width, player_height = player_image.get_size()
obstacle_image = pygame.image.load("obstacle.png")
obstacle_width, obstacle_height = obstacle_image.get_size()
# Game variables
player_x = WIDTH // 2 - player_width // 2
player_y = HEIGHT - player_height - 20
player_speed = 8
obstacle_x = random.randint(0, WIDTH - obstacle_width)
obstacle_y = -obstacle_height
obstacle_speed = 5

clock = pygame.time.Clock()

# Main game loop


running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Move the player


keys = pygame.key.get_pressed()

11
November, 2023
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < WIDTH - player_width:
player_x += player_speed

# Move the obstacle


obstacle_y += obstacle_speed
if obstacle_y > HEIGHT:
obstacle_x = random.randint(0, WIDTH - obstacle_width)
obstacle_y = -obstacle_height

# Collision detection
player_rect = pygame.Rect(player_x, player_y, player_width,
player_height)
obstacle_rect = pygame.Rect(obstacle_x, obstacle_y,
obstacle_width, obstacle_height)
if player_rect.colliderect(obstacle_rect):
print("Game Over!")
running = False

# Clear the screen


window.fill(WHITE)

# Draw game objects


window.blit(player_image, (player_x, player_y))
window.blit(obstacle_image, (obstacle_x, obstacle_y))

# Update the display


pygame.display.flip()

# Limit frames per second


clock.tick(30)
# Quit Pygame
pygame.quit()

The code assumes that there are two image files named "player.png" and "obstacle.png" for the
player and obstacle sprites, respectively. You can replace these images with your own sprites.
In this game, the player can move left and right using the arrow keys to avoid the falling
obstacles. The game checks for collisions between the player and the obstacles. When a collision
occurs, it prints "Game Over!" to the console and exits the game.
Activity
Now, study well the code and modify the game further by adding more obstacles, increasing
difficulty, or incorporating additional features to make it more engaging!

12
November, 2023
Project 2
Here's an example of a simple calculator GUI using the “tkinter” library in Python.
import tkinter as tk

# Function to update the input field when buttons are clicked


def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + str(number))

# Function to perform the calculation when the "=" button is


clicked
def calculate():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, result)
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "Error")

# Function to clear the input field when the "C" button is


clicked
def clear():
entry.delete(0, tk.END)

# Create the main window


root = tk.Tk()
root.title("Calculator")

# Entry field to display input and results


entry = tk.Entry(root, width=16, borderwidth=5, font=("Arial",
20), justify="right")
entry.grid(row=0, column=0, columnspan=4)

# Define buttons for digits and operations


buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', 'C', '=', '+'
]
# Create and place the buttons in the grid
row_val = 1
col_val = 0
for button in buttons:
tk.Button(root, text=button, width=5, height=2,
font=("Arial", 16),

13
November, 2023
command=lambda button=button: button_click(button)
if button != '=' else calculate()).grid(row=row_val,
column=col_val)
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1

# Start the main loop


root.mainloop()

Here, users can perform calculations by clicking the buttons, and the results will be displayed in
the entry field. The calculator supports basic arithmetic operations: addition, subtraction,
multiplication, and division. The "C" button clears the input field, and the "=" button calculates
the result.
Activity
Study the calculator program and modify it to calculate percentages or any other simple
calculations.

14
November, 2023

You might also like