0% found this document useful (0 votes)
6 views28 pages

Python

The document provides an introduction to the Internet of Things (IoT) and Raspberry Pi, detailing IoT's definition, applications, advantages, and disadvantages. It covers the components of Raspberry Pi 3, Python programming basics, and the creation of classes and modules in Python. Additionally, it discusses setting up a Python execution environment, using virtual environments, and managing packages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views28 pages

Python

The document provides an introduction to the Internet of Things (IoT) and Raspberry Pi, detailing IoT's definition, applications, advantages, and disadvantages. It covers the components of Raspberry Pi 3, Python programming basics, and the creation of classes and modules in Python. Additionally, it discusses setting up a Python execution environment, using virtual environments, and managing packages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

1.

Python Introduction and Raspberry PI


1.1 Define IoT (Internet of Things)
The Internet of Things (IoT) refers to the network of physical objects—“things”—
embedded with sensors, software, and other technologies to connect and exchange
data with other devices and systems over the internet. These objects can be anything
from household appliances and wearable devices to industrial machines and smart
cities infrastructure. IoT enables automation, monitoring, and control remotely,
improving efficiency and convenience.
Key aspects of IoT include connectivity, data collection, and intelligent processing,
allowing real-world objects to be controlled and tracked digitally.

1.2 List Applications of IoT


IoT is widely used across many sectors:
 Smart Homes: Automated lighting, thermostats, security cameras.
 Healthcare: Remote patient monitoring, wearable fitness trackers.
 Agriculture: Soil sensors for irrigation control.
 Industry: Predictive maintenance, asset tracking.
 Transportation: Fleet management, smart traffic signals.
 Retail: Inventory management, smart shelves.
 Energy: Smart grids, consumption monitoring.
Each application leverages IoT’s ability to collect real-time data and enable remote
control.

1.3 List Advantages and Disadvantages of IoT


Advantages:
 Automation of routine tasks.
 Enhanced efficiency and productivity.
 Real-time data collection and analytics.
 Improved safety and security.
 Cost savings through predictive maintenance.
 Better resource management.
Disadvantages:
 Privacy and security risks due to data exposure.
 High initial setup cost.
 Dependency on internet connectivity.
 Complexity in integration and standardization.
 Potential job displacement due to automation.
Understanding these helps in designing better IoT systems and mitigating risks.

1.4 Identify Components of Raspberry Pi-3


The Raspberry Pi 3 is a compact, single-board computer widely used for IoT and
learning programming.
Key components include:
 CPU: Quad-core ARM Cortex-A53 processor.
 RAM: 1GB LPDDR2.
 GPIO Pins: 40 pins for hardware interfacing.
 HDMI Port: For display output.
 USB Ports: Typically 4 ports.
 Ethernet Port: For wired network connection.
 Wi-Fi and Bluetooth: Built-in wireless connectivity.
 MicroSD Slot: For OS and storage.
 Camera and Display Interfaces: CSI and DSI connectors.
These components enable it to serve as a fully functional PC and IoT hub.

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.

1.6 Build a PC Using Raspberry Pi-3


You can build a basic personal computer using Raspberry Pi by connecting:
 Monitor: Via HDMI.
 Keyboard and Mouse: Via USB ports.
 Storage: MicroSD card with OS installed.
 Power Supply: 5V micro USB charger.
 Network: Wired or wireless for internet access.
With the right peripherals, Raspberry Pi runs a full desktop environment like Raspberry
Pi OS, capable of web browsing, coding, and media playback, functioning as a low-cost
PC.

1.7 Install Operating System into Raspberry Pi


Steps to install an OS:
 Download the OS image (e.g., Raspberry Pi OS) from the official website.
 Use imaging software like Balena Etcher to flash the OS image onto a microSD
card.
 Insert the microSD card into the Raspberry Pi.
 Power up the device; it boots into the OS.
 Complete initial setup such as regional settings and network connection.
This process makes Raspberry Pi ready for programming and IoT projects.

1.8 Familiarize to Python Programming Language


Python is a popular, high-level programming language known for its simplicity and
readability. It’s widely used for web development, data analysis, automation, and IoT
applications on Raspberry Pi. Python’s syntax is clean and close to English, making it
beginner-friendly. It supports multiple programming paradigms like procedural, object-
oriented, and functional programming.
Python's extensive libraries make it a powerful tool for many applications, including
interfacing with hardware on Raspberry Pi.

1.9 List Different Versions of Python


 Python 2.x: Legacy version, no longer actively maintained.
 Python 3.x: Current version, recommended for all new development.
 Python 3 introduced many improvements like better Unicode support and new
syntax features.
 It’s important to know the version installed, as some code differs between
Python 2 and 3.
Most systems now use Python 3 due to its active support.

1.10 Compare Python Programming Language with Java Programming


Language
Feature Python Java

Syntax Simple, concise, easy to learn Verbose, strict syntax

Typing Dynamically typed Statically typed

Compiled to bytecode, runs


Execution Interpreted
on JVM

Memory Automatic with garbage Automatic with garbage


Management collection collection

Scripting, web, AI, data Enterprise apps, Android


Use Cases
science apps

Generally slower due to Faster, due to compiled


Performance
interpretation nature

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.

1.11 List Features of Python Programming


 Easy to Learn and Use: Clean syntax and readability.
 Interpreted Language: No compilation needed, immediate execution.
 Portable: Runs on multiple platforms without modification.
 Extensive Standard Library: Rich in modules and packages.
 Supports OOP: Classes, inheritance, and polymorphism.
 Dynamic Typing: Variable types are determined at runtime.
 Automatic Memory Management: Includes garbage collection.
 Open Source: Large community and third-party libraries.
 Supports Multiple Programming Paradigms: Procedural, functional, and
OOP.

1.12 Set the Execution Environment for Python


To run Python, you need to set up an environment:
 Install Python interpreter from python.org or via package managers.
 Configure environment variables so Python commands run in the terminal.
 Install an IDE or code editor (like IDLE, VSCode, PyCharm) for development.
 Optionally set up virtual environments for managing dependencies.
 On Raspberry Pi, Python is usually pre-installed.
1.13 Execute Python Script (Command Prompt, Script, and IDE) in Different
Ways
 Command Prompt/Terminal: Run scripts using python filename.py.
 Interactive Mode: Type python to enter REPL where commands run instantly.
 Script Files: Save code in .py files and execute.
 Using IDEs: Write, debug, and run Python code with graphical tools like IDLE or
VSCode.
 On Raspberry Pi: Use terminal or graphical IDEs to execute Python code.
2.Basic of Python programming
2.1 Declare and Initialize Variables
In Python, variables are used to store data values. Unlike many other programming
languages, Python does not require explicit declaration of variable types. A variable is
created by simply assigning a value using the = operator.
Example:
x = 10 # Integer variable
name = "Alice" # String variable
price = 19.99 # Floating-point variable
The variable name should follow naming conventions: start with a letter or
underscore, followed by letters, digits, or underscores. Python is dynamically typed, so
the type is inferred at runtime based on the assigned value.

2.2 Use Comments, Indentation in Programs


 Comments: Comments are used to explain code and are ignored by the
interpreter. In Python, a comment starts with #.
Example:
# This is a single-line comment
 Indentation: Python uses indentation (whitespace at the beginning of a line) to
define code blocks. Unlike other languages that use braces {}, Python requires
consistent indentation (usually 4 spaces) to group statements.
Incorrect indentation will cause syntax errors. For example, inside if or for blocks, code
must be indented.

2.3 Discuss Data Types: Booleans, Numbers


 Booleans: Represent truth values — True or False. Used for conditional checks.
 Numbers: Python supports several numeric types:
o int: Integer numbers (e.g., 5, -3).
o float: Floating-point numbers (e.g., 3.14).
o complex: Complex numbers (e.g., 2 + 3j).
Python automatically converts numbers between types when necessary. Boolean
values can also be treated as integers (True = 1, False = 0).

2.4 Use Decision Making Statements to Solve Different Problems


Decision making in Python is done using conditional statements: if, if-else, and if-elif-
else.
Example:
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
Conditions are evaluated to True or False. elif is used for multiple conditions.

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.

2.6 Perform Operations on Lists, Tuples, Sets, and Dictionaries


Python provides several built-in data structures:
 List: Ordered, mutable, allows duplicates. Example: [1, 2, 3].
 Tuple: Ordered, immutable, allows duplicates. Example: (1, 2, 3).
 Set: Unordered, mutable, no duplicates. Example: {1, 2, 3}.
 Dictionary: Key-value pairs, unordered, mutable. Example: {"name": "Alice",
"age": 25}.
Operations include adding/removing elements, accessing by index or key,
concatenation (lists and tuples), and set operations (union, intersection).

2.7 Identify Members of Lists, Tuples, Sets, and Dictionaries Using


Membership Operator
Python provides the in and not in operators to check membership.
Example:
lst = [1, 2, 3]
if 2 in lst:
print("2 is in the list")

dct = {'a': 1, 'b': 2}


if 'a' in dct:
print("Key 'a' found")
For dictionaries, in checks for keys.

2.8 Process Strings Using Operators and Built-in Functions


Strings in Python are sequences of characters. They support operators and functions:
 Concatenation: "Hello " + "World" → "Hello World"
 Repetition: "Hi" * 3 → "HiHiHi"
 Membership: 'H' in "Hello" → True
 Built-in methods: .lower(), .upper(), .split(), .strip(), .replace(), .find()
Strings are immutable, so methods return new strings.

2.9 Build Functions With/Without Arguments


Functions allow reusable blocks of code.
Syntax:
def greet():
print("Hello!")

def add(a, b):


return a + b
Functions can have:
 No arguments.
 Positional or keyword arguments.
 Default parameter values.
Calling a function executes the code inside.
2.10 Solve Problems by Using Recursive Method of Problem Solving
Recursion is when a function calls itself to solve smaller instances of a problem.
Example (factorial):
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Recursion continues until a base case is reached.

2.11 Differentiate Between Recursive and Iterative Way of Problem Solving


 Recursive Approach: Function calls itself with smaller input; elegant for
divide-and-conquer problems; can be memory-intensive due to call stack.
 Iterative Approach: Uses loops to repeat operations; generally more memory-
efficient; sometimes less intuitive.
Example: Calculating factorial can be done recursively or with a for loop iteratively.
3.Classes and Packages
3.1 Define Class with Its Members and Create Instances of Class
A class in Python is a blueprint for creating objects (instances). It groups data
(attributes) and functions (methods) that operate on the data. A class encapsulates
both state and behavior.
Syntax:
class Car:
def __init__(self, brand, model):
self.brand = brand # Attribute
self.model = model # Attribute

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.

3.2 Implement Different Types of Inheritance


Inheritance allows a new class (child/subclass) to acquire properties and methods
from an existing class (parent/superclass), promoting code reuse.
Types of inheritance:
 Single inheritance:
 class Animal:
 def speak(self):
 print("Animal sound")

 class Dog(Animal):
 def speak(self):
 print("Bark")
 Multiple inheritance:
 class Flyer:
 def fly(self):
 print("Flying")

 class Bird(Animal, Flyer):


 pass
 Multilevel inheritance: A class derived from a derived class.
 Hierarchical inheritance: Multiple subclasses inherit from one superclass.

3.3 Use super() to Call Methods of a Superclass


The super() function allows calling a method from a parent class inside a child class,
especially useful to extend or customize behavior without rewriting.
Example:
class Parent:
def greet(self):
print("Hello from Parent")

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.

3.4 Use Python Identity Operator


Python provides identity operators to compare whether two variables reference the
same object in memory.
 is operator: Returns True if both refer to the same object.
 is not operator: Returns True if both refer to different objects.
Example:
a = [1, 2, 3]
b=a
c = [1, 2, 3]

print(a is b) # True
print(a is c) # False
Useful for checking object identity rather than value equality.

3.5 Create and Import Modules and Packages


 A module is a .py file containing functions, classes, and variables.
Example module math_utils.py:
def add(a, b):
return a + b
 Importing a module:
 import math_utils
 print(math_utils.add(5, 3))
 A package is a directory containing multiple modules and an __init__.py file
(can be empty).
 Importing from packages:
 from mypackage import mymodule
Modules and packages help organize code into reusable units.

3.6 Use Local and Global Variables


 Local variables are declared inside a function and accessible only within that
function.
 Global variables are declared outside functions and accessible anywhere in
the module.
Example:
x = 10 # Global variable

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.7 Set Up the Virtual Environment for Python Application


A virtual environment is a self-contained directory with its own Python interpreter
and packages, used to manage dependencies separately from the system Python.
Creating a virtual environment:
python -m venv myenv
Activating:
 Windows: myenv\Scripts\activate
 Linux/Mac: source myenv/bin/activate
Virtual environments avoid version conflicts between projects.

3.8 Install Packages


Packages can be installed using pip, Python’s package manager.
Example:
pip install requests
To install in a virtual environment, activate it first.
List installed packages:
pip list
Uninstall package:
pip uninstall package_name

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.

3.10 Use datetime Package in Python Application


The datetime module provides classes for manipulating dates and times.
Example:
from datetime import datetime, timedelta

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)

# Parsing date string


dt = datetime.strptime("2023-06-01", "%Y-%m-%d")
print(dt)
Useful for time-stamping, scheduling, and time-based calculations.
4.Exception handling and Multithreading
4.1 Difference Between Compile-Time Errors, Runtime Errors, and Logical
Errors
 Compile-Time Errors: These errors occur when the source code violates the
syntax rules of the programming language. In Python, since it is an interpreted
language, syntax errors are caught when the code is parsed before execution.
Example: Missing a colon after if statement.
 Runtime Errors: These occur during the execution of the program. They cause
the program to stop unexpectedly if not handled. Examples include division by
zero, file not found, or accessing invalid list index.
 Logical Errors: These errors occur when the program runs without crashing but
produces incorrect results due to flaws in the algorithm or logic. These are the
hardest to detect and debug because no error message is generated.

4.2 List Common Compile-Time Errors and Runtime Errors


 Common Compile-Time Errors:
o Syntax errors (e.g., missing parentheses, incorrect indentation)
o Misspelled keywords or variable names
o Incorrect use of operators
 Common Runtime Errors:
o ZeroDivisionError: Dividing a number by zero
o FileNotFoundError: Accessing a file that does not exist
o IndexError: Accessing a list with an invalid index
o KeyError: Accessing a dictionary with a non-existent key
o TypeError: Performing unsupported operations between incompatible
types

4.3 Using try/except, finally, and else Blocks to Handle Exceptions


Python provides a robust way to handle exceptions to avoid program crashes using
try-except blocks.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("No exceptions occurred.")
finally:
print("This block always executes.")
 try: Contains code that may raise exceptions.
 except: Handles specific exceptions.
 else: Executes if no exceptions occur.
 finally: Executes always, useful for cleanup code.

4.4 Usage of raise Statement


The raise statement is used to explicitly trigger an exception in code, either a built-in
or user-defined exception.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
else:
print("Age is valid.")

check_age(15) # Raises ValueError


This helps enforce rules and improve error reporting.

4.5 Create User-Defined Exception Classes


Custom exceptions allow more precise error handling tailored to application needs.
class CustomError(Exception):
def __init__(self, message):
self.message = message

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.

4.6 Define Multithreading


Multithreading is a technique where multiple threads (smaller units of a process) run
concurrently within a single program to improve performance, especially for I/O-bound
tasks.
Each thread runs independently but shares the same memory space, allowing efficient
communication between threads.

4.7 List Pros and Cons of Multithreading


Pros:
 Improves program responsiveness
 Efficient utilization of CPU during waiting times (e.g., I/O operations)
 Enables parallel execution of multiple tasks
Cons:
 Complexity in writing thread-safe code
 Risk of race conditions and deadlocks
 Python's Global Interpreter Lock (GIL) limits true parallelism in CPU-bound tasks

4.8 Create Threads Using Threading Module


Python’s built-in threading module is used to create and manage threads.
Example:
import threading

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.

4.10 Design Threads Using start, join, isAlive, getName, setName,


activeCount, and currentThread Methods
 start(): Begins thread execution.
 join(): Waits for thread completion.
 is_alive(): Checks if a thread is currently running.
 getName(): Gets the thread’s name.
 setName(): Sets the thread’s name.
 activeCount(): Returns the number of currently active threads.
 currentThread(): Returns the current thread object.
Example:
thread.setName("MyThread")
print(thread.getName())
print(thread.is_alive())
print(threading.activeCount())
print(threading.currentThread())

4.11 Achieve Thread Synchronization in Multithreaded Environment


Because threads share memory, synchronization prevents race conditions using locks
or semaphores.
import threading

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

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


label.pack()

root.mainloop()
This simple program opens a window displaying a label.

5.2 Design GUI Using Different Geometry Managers


Geometry managers control widget placement inside a window. Tkinter provides three
main geometry managers:
 pack(): Places widgets in blocks before or after each other (top, bottom, left,
right). It’s simple but less flexible.
 grid(): Places widgets in a 2D grid of rows and columns. Ideal for complex
layouts.
 place(): Positions widgets at an exact x,y coordinate. Useful for precise control.
Example using grid():
label1 = tk.Label(root, text="Name")
label1.grid(row=0, column=0)
entry1 = tk.Entry(root)
entry1.grid(row=0, column=1)
Choosing the right manager depends on the layout complexity.

5.3 Use Various Widgets in Tkinter Library


Widgets are elements like buttons, labels, text boxes, checkboxes, radio buttons, and
menus.
Common Tkinter widgets include:
 Label: Displays text or images.
 Button: Triggers a function when clicked.
 Entry: Single line text input.
 Text: Multi-line text input.
 Checkbutton: Checkbox for boolean options.
 Radiobutton: Grouped radio buttons for exclusive choice.
 Listbox: Displays a list of items.
 Menu: Dropdown menu bar.
Example adding a button:
button = tk.Button(root, text="Click Me", command=lambda: print("Button clicked"))
button.pack()

5.4 List Attributes of Widgets


Widgets have many customizable attributes that control appearance and behavior:
 text: The displayed text.
 bg or background: Background color.
 fg or foreground: Text color.
 font: Font type, size, and style.
 width and height: Size of the widget.
 state: Active, disabled, or normal.
 relief: Border style (flat, raised, sunken).
 command: Function called on events like button press.
Example setting attributes:
label.config(text="Welcome", bg="yellow", fg="blue", font=("Arial", 14, "bold"))

5.5 Handle Events Generated by Various Widgets


Events are user actions such as clicks, key presses, or mouse movements. Event
handling links these actions to code.
 Use the command attribute for simple widgets like buttons.
 Use bind() method for more complex events, specifying event types like
<Button-1> for left click or <Key> for key press.
Example binding a click event:
def on_click(event):
print("Clicked at", event.x, event.y)

label.bind("<Button-1>", on_click)
Events help create interactive GUIs.

5.6 Create Patterns to Use Regular Expressions


Regular expressions (regex) are patterns used to match strings. They are powerful
tools for searching, replacing, and validating text.
 Use the re module in Python.
 Basic symbols: . (any character), * (zero or more), + (one or more), ? (optional).
 Character classes: [abc], [0-9], \d (digit), \w (word character).
 Anchors: ^ (start of string), $ (end of string).
Example pattern to match email addresses:
import re
pattern = r"^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"

5.7 Validate Data Using Regular Expressions


Regex is often used to validate user inputs such as emails, phone numbers, and
passwords.
Steps:
 Compile the regex pattern.
 Use match() or search() functions to check input.
 Return validation result (True/False).
Example email validation:
def validate_email(email):
pattern = r"^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
return True
return False

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.

6.2 List Modes of Opening a File


File modes specify how the file is accessed:
 'r': Read mode (default), file must exist.
 'w': Write mode, creates a new file or truncates existing.
 'a': Append mode, adds to end of file.
 'r+': Read and write mode.
 'b': Binary mode, used with other modes (e.g., 'rb', 'wb').
 'x': Create mode, creates a new file and fails if file exists.
Each mode suits different use cases depending on file operation requirements.

6.3 Delete Files and Folders


Python’s os and shutil modules allow file and directory management:
 Delete a file with os.remove(path).
 Delete an empty directory with os.rmdir(path).
 Delete directories with contents using shutil.rmtree(path).
Example:
import os
os.remove("old_file.txt")
Careful deletion prevents loss of important data.

6.4 Connect to MySQL Database


Raspberry Pi can connect to MySQL using Python’s mysql-connector-python or
PyMySQL libraries.
Steps:
 Import the connector module.
 Establish a connection using credentials: host, user, password, and database.
 Create a cursor object to execute SQL queries.
 Handle exceptions for connection failures.
Example:
import mysql.connector
conn = mysql.connector.connect(host="localhost", user="pi", password="raspberry",
database="testdb")
cursor = conn.cursor()
This enables Raspberry Pi to manage databases for data-driven applications.

6.5 Perform Creation of Table, Insert, Update Entries, Execute Stored


Procedures
Once connected:
 Use CREATE TABLE SQL command to define tables.
 Insert data using INSERT INTO.
 Update existing data using UPDATE.
 Execute stored procedures using CALL procedure_name().
Example:
cursor.execute("CREATE TABLE users(id INT PRIMARY KEY, name VARCHAR(50))")
cursor.execute("INSERT INTO users VALUES(1, 'Alice')")
cursor.execute("UPDATE users SET name='Bob' WHERE id=1")
conn.commit()
Databases organize and manipulate structured data efficiently.

6.6 Store Images Using BLOB Data Type


BLOB (Binary Large Object) stores binary data like images in databases.
 Convert image file to binary data in Python.
 Insert binary data into MySQL BLOB fields.
 Retrieve and convert back to image for display or processing.
Example:
with open('image.jpg', 'rb') as file:
binary_data = file.read()

cursor.execute("INSERT INTO images (data) VALUES (%s)", (binary_data,))


conn.commit()
BLOB support enables multimedia storage in applications.

6.7 Use Breadboard, Resistor, Transistors, Diode, Capacitors, Inductors,


Transformers, and Adaptors
In hardware prototyping:
 Breadboard allows assembling circuits without soldering.
 Resistors control current flow.
 Transistors act as switches or amplifiers.
 Diodes allow current flow in one direction.
 Capacitors store electrical energy.
 Inductors resist changes in current.
 Transformers change voltage levels.
 Adaptors supply regulated power.
Understanding these components is vital for interfacing hardware with Raspberry Pi.

6.8 Work with I2C and SPI Interface of Raspberry Pi


Raspberry Pi supports communication protocols:
 I2C (Inter-Integrated Circuit): Two-wire protocol for multiple device
communication using SDA (data) and SCL (clock) lines.
 SPI (Serial Peripheral Interface): Faster, four-wire full-duplex communication
used for sensors, displays, and memory devices.
Python libraries like smbus (I2C) and spidev (SPI) help interact with these interfaces.
Example (I2C):
import smbus
bus = smbus.SMBus(1)
device_address = 0x48
data = bus.read_byte_data(device_address, 0)
These interfaces expand Raspberry Pi’s connectivity options.

6.9 Turn On and Off LED Using Python Program


A common beginner project involves controlling an LED:
 Connect LED to GPIO pins through a resistor.
 Use RPi.GPIO or gpiozero library in Python.
 Set pin mode and output HIGH to turn ON, LOW to turn OFF.
Example:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

GPIO.output(18, GPIO.HIGH) # LED ON


time.sleep(2)
GPIO.output(18, GPIO.LOW) # LED OFF

GPIO.cleanup()
This demonstrates hardware-software interaction.

6.10 Make a Buzzing Sound with Raspberry Pi and Python Program


Using a buzzer connected to GPIO pins:
 Setup GPIO pin as output.
 Send PWM (Pulse Width Modulation) signals or simply turn the buzzer ON/OFF to
produce sound.
Example:
import RPi.GPIO as GPIO
import time

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.

6.11 Connect to Wired or Wireless Network


Raspberry Pi can connect to:
 Wired Ethernet: Automatically configured with DHCP when plugged into a
network.
 Wireless Wi-Fi: Configured via Raspberry Pi OS GUI or editing
wpa_supplicant.conf for headless setup.
Python can manage network connections and monitor status.
Networking enables IoT and remote control applications.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy