Python 2 [Two]
Python 2 [Two]
IN
PYTHON
{Lecture Note II}
Compiled by
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
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.
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.
import turtle
t = turtle.Turtle()
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.
# 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
Here, the turtle moves forward by 100 units and turns right by 90 degrees, repeating this process
four times to create a square.
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()
import tkinter as tk
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.
import tkinter as tk
7
November, 2023
label.config(text="Hello, " + entry.get())
# Create a label
label = tk.Label(root, text="Enter your name:")
label.pack()
# Create a button
button = tk.Button(root, text="Submit", command=on_button_click)
button.pack()
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.
import tkinter as tk
from tkinter import messagebox
8
November, 2023
messagebox.showinfo("About", "This is a simple tkinter
application.")
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.
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}!"
# 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.
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)
clock = pygame.time.Clock()
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
# 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
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
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
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