Python
Python
1.5 List General Purpose Input and Output Pins (GPIO) on Raspberry Pi
GPIO pins allow Raspberry Pi to interface with external electronics like sensors,
motors, and LEDs.
There are 40 pins on the Raspberry Pi 3 header.
Some pins are Power pins (3.3V, 5V, GND).
The rest are GPIO pins that can be programmed as input or output.
Some pins support special functions like PWM, UART, SPI, and I2C
communication.
GPIO pins are used to read sensors, drive actuators, and communicate with
other devices.
Proper use of GPIO pins is fundamental for hardware projects.
Platform
Cross-platform Cross-platform
Dependency
Python’s simplicity makes it preferred for beginners and rapid prototyping; Java is
often chosen for large-scale applications requiring performance and robustness.
2.5 Use Loop Statements with Example to Solve Problems Which Are
Iterative
Python supports loops to execute code repeatedly:
for loop: Iterates over sequences (lists, strings).
Example:
for i in range(5):
print(i)
while loop: Repeats as long as a condition is True.
Example:
count = 0
while count < 5:
print(count)
count += 1
Loops are used for tasks like iteration, repetitive calculations, and traversing data
structures.
def display_info(self):
print(f"Car: {self.brand} {self.model}")
__init__ is the constructor, called when creating an instance.
self represents the current object.
Creating instances:
car1 = Car("Toyota", "Corolla")
car1.display_info()
Each instance has its own copy of attributes.
class Dog(Animal):
def speak(self):
print("Bark")
Multiple inheritance:
class Flyer:
def fly(self):
print("Flying")
class Child(Parent):
def greet(self):
super().greet()
print("Hello from Child")
c = Child()
c.greet()
Output:
Hello from Parent
Hello from Child
This ensures proper method resolution in inheritance hierarchies.
print(a is b) # True
print(a is c) # False
Useful for checking object identity rather than value equality.
def func():
y = 5 # Local variable
print(x, y)
func()
print(x)
# print(y) # Error: y not defined outside func
To modify a global variable inside a function, use the global keyword.
3.9 Write Programs Using Standard Mathematical Functions: sqrt, cos, sin,
pow, degrees, and fabs
Python’s math module provides common mathematical functions.
Example:
import math
print(math.sqrt(16)) # 4.0
print(math.cos(0)) # 1.0
print(math.sin(math.pi/2)) # 1.0
print(math.pow(2, 3)) # 8.0
print(math.degrees(math.pi)) # 180.0
print(math.fabs(-5)) # 5.0 (absolute value)
These functions are essential for scientific and engineering calculations.
now = datetime.now()
print("Current date and time:", now)
# Date formatting
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# Adding days
future = now + timedelta(days=5)
print("Date after 5 days:", future)
def test(value):
if value < 0:
raise CustomError("Negative value not allowed.")
try:
test(-1)
except CustomError as e:
print(f"Error occurred: {e.message}")
User-defined exceptions should inherit from the built-in Exception class.
def task():
print("Thread task running")
thread = threading.Thread(target=task)
thread.start()
thread.join()
target: Function that the thread will execute
start(): Starts the thread
join(): Waits for thread to finish
4.9 Create Multiple Threads Which Perform Different Tasks
Multiple threads can run different functions simultaneously.
Example:
def task1():
print("Task 1 running")
def task2():
print("Task 2 running")
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start()
t2.start()
t1.join()
t2.join()
Threads execute independently and may run in parallel depending on the CPU.
lock = threading.Lock()
counter = 0
def increment():
global counter
lock.acquire()
try:
counter += 1
finally:
lock.release()
threads = []
for i in range(10):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(counter)
Locks ensure that only one thread modifies shared data at a time.
5.Design Graphical user Interface and Regular
Expressions
5.1 Design a Graphical User Interface Using Tkinter Library
Tkinter is Python’s standard library for creating graphical user interfaces (GUIs). It
provides a simple way to build windows, dialogs, buttons, menus, and other UI
elements.
To design a basic GUI:
Import the tkinter module.
Create a main window using Tk() class.
Add widgets like labels, buttons, entry fields to the window.
Enter the main event loop with mainloop() to display the window and respond to
user inputs.
Example:
import tkinter as tk
root = tk.Tk()
root.title("Simple GUI")
root.mainloop()
This simple program opens a window displaying a label.
label.bind("<Button-1>", on_click)
Events help create interactive GUIs.
print(validate_email("test@example.com")) # True
print(validate_email("test@.com")) # False
This ensures data integrity before processing.
6.Data Processing and Programming Raspberry Pi
6.1 Open, Close, Read, Write, Append Data to Files Using Programs
In Python, file handling is essential for data storage and retrieval. You can open files in
various modes:
Open a file using open(filename, mode), where mode can be 'r' (read), 'w'
(write), 'a' (append), 'rb' or 'wb' for binary modes.
Read data using methods like .read(), .readline(), or .readlines().
Write data using .write() or .writelines() to add content.
Append mode allows adding data at the end without overwriting existing
content.
Close the file after operations with .close() to free system resources.
Example:
f = open("data.txt", "w")
f.write("Hello, Raspberry Pi!\n")
f.close()
Proper file handling ensures data integrity and prevents corruption.
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.cleanup()
This demonstrates hardware-software interaction.
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)
GPIO.output(23, GPIO.HIGH) # Buzzer ON
time.sleep(1)
GPIO.output(23, GPIO.LOW) # Buzzer OFF
GPIO.cleanup()
Useful for alarms and notifications.