Unit-3 Python Basics_fiot
Unit-3 Python Basics_fiot
’
Inroductionto’
Imglemntation
UNIT-IL
of fython
ToT
with
Introduction to
(ontol
while
fBo
ange
’ break lonlu
Pas
igthon funtiey
’ Modles
Pakags
Aate Time.eprations
clans
-> Ijthon a
gennal pupoe high leael PgUp
preg language'
the main iar acteniaica of tathon
ython ae;
PgDr
VO Multi paradigm progreming
longag
Sam Sntor active Jonguage
Jew tay -to arn, read and Maintain,
and proadure otunted
(VD Salable
ata Tupu B Data saucts
(0 Numbr
Numbor data type 4 used. to store
Values muni
SNunbens a
Simutabe data tpeu,
mumtr data type eyule in a
ney alloratid oljct
typeca)
'int's
#Aoaing
b=25
peint
>> type Cb)
<type 'oat>
ye 2+5J
a tut o chanactuu
<type 'str,
Samle fooquam"
'HELO wORLD!'
helle world)'
# Accsing'sud ninge
'World !'
orld
ans) 'onion, 'Caot', l'potato, Vegetdes »
Combining #
'borona,
"pa 'nang' ('aple.
'orang, mango,
(t'mange) rnt >tuits.
'banana,'pear lst a to an
lt raom iler
pear'] 'mango'hanara, 'orange, ['apee,
appende'pea)
to lem an
list
ango] 'banana, 'orange, l'aple,Hhui)ts ty(pe >»>
txaunplfruyt-a
anme the mot med itam At ’
haut all
walus. cther Toqether
type,
nd
bo dattomeound
a
>>> eatabde
eith im pareintheiu,
Unlike ist, the element of tupla
Cannet be changd,
e tuples Can e
thouglt
eramply
uiti : (" pple', "orange', "hanana')
3
edement
('appe', buange')
Combining tqla
Cpotalo ,'onúcn) )
Convesiens;r
t convnt to ting
onat to leng
>> b:2015
>>> longco)
t onvet to oat 2013L
b 2013
HoatCb)
2013·O
# Convent to lit
>>> 6= "aeiou"
S Lst (s)
Contol Flou
alaliment in
dhe
athe i atatment in
a> to 000
Pint Mor"
el:
Prit ey"
More
>>7s-'Hlo wd
int s
hybion teratey
whica
fyamples:
hellotng "Hello tootd"
'banand, 'mango'
tudut: namd': 'Ha, i'us',
thjoy';rs'
Ven charatu in a
iotbing :
poäntc
Atm n a lit
i2
print i
dhe
Range stalement in
nmmbeys
gnerate
ari thmetie
SSSYange C1o)
3,4t15i6, j8,9]
To, t, 2
S) Yange Ct0, 10, 10)
Llo, 2o, 30, 0, 50,, 60, 0, 8o, 90, too)
5) Brak Continyç'
the oreak statemnk breakout ef the
the Certne
torlotile Lovp whwuay the t
statennt continies wttu tle
iavation.
in rang Cuj256,);
y>512:
break
32
384
tit: 'apple', 'orange','hanand,' Man
'hanand :
Centnue
else
riht itam
fipple
ovange
Mango
6) Pas stalmnt
e pas stalemnt in python i
mull oevation: when a
pas statinent is ued
’ The
vequived syntacially
Atatent s dont lwant g ommand
but ye to eecte
r code
lopple','banana']
itom baunana
pas
pint dem
banana
Functions in Python
In Python, functions are reusable blocks of code that perform a specific task.
They help you organize your code, make it more readable, and allow you to
avoid repetition. Here's a breakdown of how functions work in Python:
1. Defining a Function
You define a function using the `def` keyword, followed by the function name
and parentheses `()`. If the function takes inputs (called parameters), you list
them inside the parentheses. The code block inside the function is indented.
```python
def greet():
print("Hello, world!")
```
2. Calling a Function
To execute the function, you "call" it by writing its name followed by
parentheses.
```python
greet() # Output: Hello, world!
```
```python
def greet(name):
print(f"Hello, {name}!")
```python
def add(a, b):
result = a + b
print(f"The sum is {result}")
4. Return Statement
Functions can return values using the `return` keyword. Once `return` is
executed, the function stops running and sends the value back to the caller.
```python
def multiply(a, b):
return a * b
result = multiply(4, 6)
print(result) # Output: 24
```
If no `return` is specified, the function returns `None` by default.
5. Default Parameters
You can give parameters default values, making them optional when calling the
function.
```python
def greet(name="stranger"):
print(f"Hello, {name}!")
6. Keyword Arguments
When calling a function, you can specify arguments by parameter name, which
allows you to pass them in any order.
```python
def describe_person(name, age):
print(f"{name} is {age} years old.")
```python
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
```
9. Scope
Variables defined inside a function are local to that function and can’t be
accessed outside unless returned. Variables outside are global, but to modify
them inside a function, you need the `global` keyword.
```python
x = 10
def modify():
global x
x = 20
modify()
print(x) # Output: 20
```
Key Points
- Functions make code modular and reusable.
- They can take inputs, process them, and return outputs.
- Python treats functions as "first-class citizens," meaning you can pass them as
arguments, return them from other functions, or assign them to variables.
Modules in Python
In Python, “modules” are files containing Python code (functions, classes,
variables, etc.) that you can import and use in other Python programs. They
allow you to organize your code into reusable, manageable pieces, promote
modularity, and avoid cluttering a single file with too much code. Here's a
detailed explanation of modules in Python:
1. What is a Module?
A module is simply a `.py` file that contains Python definitions and statements.
For example, if you create a file called `math_utils.py` with some functions, that
file becomes a module you can import elsewhere.
```python
# math_utils.py
def add(a, b):
return a + b
2. Importing a Module
To use the code from a module in another file, you use the `import` keyword.
```python
# main.py
import math_utils
result = math_utils.add(3, 5)
print(result) # Output: 8
```
- The `import` statement loads the entire module, and you access its contents
using the dot notation (`module_name.item`).
3. Importing Specific Items
If you only need specific functions or variables from a module, you can import
them directly using `from ... import ...`.
```python
from math_utils import add
```python
from math_utils import *
```python
import math_utils as mu
result = mu.add(3, 5)
print(result) # Output: 8
```
5. Built-in Modules
Python comes with a rich standard library of built-in modules that you can
import without creating files yourself. Examples include:
- `math`: Mathematical functions.
- `random`: Random number generation.
- `datetime`: Date and time handling.
```python
import math
```python
# math_utils.py
def add(a, b):
return a + b
if __name__ == "__main__":
print("This runs only if math_utils.py is executed directly.")
print(add(2, 3))
```
For example:
- Create `my_module.py`:
```python
# my_module.py
greeting = "Hello from my_module!"
def say_hi():
print(greeting)
```
For example:
```
my_package/
__init__.py
module1.py
module2.py
```
- `main.py`:
```python
from calculations import multiply, divide
print(multiply(4, 5)) # Output: 20
print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Output: Error: Division by zero
```
PACKAGES
In Python, packages are a way to organize and structure multiple related
modules into a single directory hierarchy. They allow you to group modules
together, making your code more modular, scalable, and easier to manage.
Essentially, a package is a directory that contains Python modules (`.py` files)
and a special `__init__.py` file, which tells Python that the directory should be
treated as a package.
---
1. What is a Package?
A package is a folder that:
- Contains one or more `.py` files (modules).
- Includes an `__init__.py` file (can be empty), which marks the folder as a
package.
- Can contain sub-packages (subdirectories with their own `__init__.py` files).
For example:
```
my_package/
__init__.py
module1.py
module2.py
```
my_package.module1.some_function()
```
# Import Specific Items
```python
from my_package.module1 import some_function
# main.py
from my_package import *
module1.some_function() # Works
module2.some_function() # Fails (not in __all__)
```
4. Example of a Package
Let’s create a simple package called `math_tools`.
Directory structure:
```
math_tools/
__init__.py
basic.py
advanced.py
```
- `basic.py`:
```python
def add(a, b):
return a + b
- `advanced.py`:
```python
def multiply(a, b):
return a * b
Updated structure:
```
math_tools/
__init__.py
basic/
__init__.py
operations.py
advanced/
__init__.py
operations.py
```
- `math_tools/basic/operations.py`:
```python
def add(a, b):
return a + b
```
- `math_tools/advanced/operations.py`:
```python
def multiply(a, b):
return a * b
```
Usage:
```python
from math_tools.basic.operations import add
from math_tools.advanced.operations import multiply
response = requests.get("https://api.example.com")
print(response.status_code)
```
8. How Python Locates Packages
Python searches for packages in:
1. The current directory.
2. Directories in `sys.path` (includes standard library and site-packages for
installed third-party packages).
Check `sys.path`:
```python
import sys
print(sys.path)
```
---
9. Practical Example
Imagine a `game` package:
```
game/
__init__.py
characters.py
utils/
__init__.py
helpers.py
```
- `characters.py`:
```python
def create_player(name):
return f"Player: {name}"
```
- `utils/helpers.py`:
```python
def roll_dice():
import random
return random.randint(1, 6)
```
- `main.py`:
```python
from game.characters import create_player
from game.utils.helpers import roll_dice
player = create_player("Alice")
score = roll_dice()
print(player) # Output: Player: Alice
print(score) # Output: (random number 1-6)
```
Key Points
- A package is a directory with an `__init__.py` file and modules/sub-packages.
- Use dot notation to navigate the package structure.
- Packages make large projects manageable and reusable.
FILE HANDLING IN PYTHON
File handling in Python refers to the process of working with files—reading
from them, writing to them, appending data, or managing them in other ways.
Python provides built-in functions and methods to perform these operations
easily and efficiently. Here's a detailed explanation of file handling in Python:
1. Basics of File Handling
Files are stored on a computer's disk, and Python allows you to interact with
them using the `open()` function, which is the primary tool for file handling.
Once a file is opened, you can read its contents, write new data, or modify it,
and then close it to free up system resources.
2. The `open()` Function
The `open()` function is used to open a file and returns a file object. It takes two
main arguments:
- File path : The name or path of the file (e.g., `"example.txt"` or
`"folder/example.txt"`).
- Mode : Specifies the purpose of opening the file (e.g., reading, writing).
Syntax:
```python
file_object = open("filename", "mode")
```
Common File Modes
| Mode | Description |
| `"r"` | Read (default). Opens file for reading; error if file doesn’t exist. |
| `"w"` | Write. Creates a new file or overwrites an existing one. |
| `"a"` | Append. Adds data to the end of the file; creates file if it doesn’t exist. |
| `"r+"`| Read and write. File must exist. |
| `"b"` | Binary mode (e.g., `"rb"`, `"wb"`). Used for non-text files like images. |
3. Opening and Closing a File
Files should always be closed after use to avoid resource leaks. You can
manually close a file with `close()`, but the best practice is to use a `with`
statement, which automatically closes the file when done.
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found.")
```
9. Deleting or Renaming Files
The `os` module also provides file management functions:
- Delete a file:
```python
import os
os.remove("example.txt")
```
- Rename a file:
```python
import os
os.rename("old_name.txt", "new_name.txt")
```
10. Example: Putting It Together
Here’s a practical example combining reading and writing:
```python
# Write some data
with open("data.txt", "w") as file:
file.write("Name: Alice\nAge: 25\n")
# Append more data
with open("data.txt", "a") as file:
file.write("Name: Bob\nAge: 30\n")
current_time = datetime.now().time()
print(current_time) # Output: 12:34:56.789012
```
3. Creating Date and Time Objects
You can manually create date, time, or datetime objects by specifying values.
#### Date Object
```python
from datetime import date
Example:
```python
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted) # Output: 2025-03-25 12:34:56
now = datetime.now()
future_date = now + timedelta(days=10)
print(future_date) # Adds 10 days to current date/time
```
#### Subtracting Time
```python
past_date = now - timedelta(hours=5, minutes=30)
print(past_date) # Subtracts 5 hours and 30 minutes
```
now = datetime.now()
print(now.year) # Output: 2025
print(now.month) # Output: 3
print(now.day) # Output: 25
print(now.hour) # Output: 12
print(now.minute) # Output: 34
print(now.second) # Output: 56
```
8. Working with Time Zones
The `datetime` module has basic timezone support with `timezone`, but for
more robust handling, use the third-party `pytz` library.
#### Using `timezone` (Built-in)
```python
from datetime import datetime, timezone
# UTC time
utc_now = datetime.now(timezone.utc)
print(utc_now) # Output: 2025-03-25 10:34:56.789012+00:00
```
# Get timezone
tz = pytz.timezone("America/New_York")
ny_time = datetime.now(tz)
print(ny_time) # Output: 2025-03-25 06:34:56.789012-04:00 (example)
dt1 = datetime(2023, 1, 1)
dt2 = datetime(2023, 12, 31)
# Add 7 days
future = now + timedelta(days=7)
print(f"7 days from now: {future.strftime('%Y-%m-%d %H:%M:%S')}")
Output (example):
```
Now: 2025-03-25 12:34:56
7 days from now: 2025-04-01 12:34:56
Event date: 2025-04-01 09:00:00
Days until event: 6
```
Key Points
- Use `datetime` for most date/time tasks.
- `strftime()` formats dates as strings; `strptime()` parses strings into dates.
- `timedelta` handles arithmetic with time intervals.
- For time zones, `pytz` is highly recommended.
- Always consider edge cases (e.g., leap years, daylight saving time) in
production code.
CLASSES IN PYTHON
In Python, classes are a fundamental part of object-oriented programming
(OOP). They allow you to define a blueprint for creating objects, which are
instances of the class. Classes encapsulate data (attributes) and behavior
(methods) into a single unit, promoting code reusability, modularity, and
organization. Here's a detailed explanation of classes in Python:
1. What is a Class?
A class is a template or blueprint that defines the properties (attributes) and
actions (methods) that objects created from the class will have. Think of a class
as a "cookie cutter" and objects as the "cookies" made from it.
2. Defining a Class
You define a class using the `class` keyword followed by the class name
(typically capitalized by convention). The body of the class contains attributes
and methods.
#### Basic Syntax
```python
class ClassName:
# Class body
pass
```
# Create objects
dog1 = Dog()
dog2 = Dog()
# Call method
dog1.bark() # Output: Woof!
dog2.bark() # Output: Woof!
```
4. The `self` Parameter
In Python, every method in a class must include `self` as its first parameter.
`self` refers to the instance calling the method, allowing access to its attributes
and other methods.
```python
class Dog:
def bark(self):
print("Woof!")
def wag_tail(self):
print("Tail wagging...")
dog = Dog()
dog.bark() # Output: Woof!
dog.wag_tail() # Output: Tail wagging...
```
5. Adding Attributes
Attributes are variables that belong to an object. They are typically initialized in
a special method called `__init__`, which is the constructor.
def bark(self):
print(f"{self.name} says Woof!")
```python
class Dog:
species = "Canis familiaris" # Class attribute
def describe(self):
print(f"{self.name} is a {self.species}")
dog1 = Dog("Buddy")
dog2 = Dog("Max")
def bark(self):
print(f"{self.name} barks!")
dog = Dog("Buddy")
dog.bark() # Output: Buddy barks!
dog.rename("Rex")
dog.bark() # Output: Rex barks!
```
@classmethod
def get_species(cls):
return cls.species
#### Example
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Generic animal sound")
def speak(self):
print(f"{self.name} the {self.breed} says Woof!")
```python
class Dog:
def __init__(self, name):
self.__secret = "I’m a good boy" # Private attribute
self.name = name
def reveal_secret(self):
print(self.__secret)
dog = Dog("Buddy")
dog.reveal_secret() # Output: I’m a good boy
# print(dog.__secret) # Raises AttributeError
```
10. Properties (Getters and Setters)
The `@property` decorator allows controlled access to attributes.
```python
class Dog:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if isinstance(value, str):
self._name = value
else:
raise ValueError("Name must be a string")
dog = Dog("Buddy")
print(dog.name) # Output: Buddy
dog.name = "Max"
print(dog.name) # Output: Max
# dog.name = 123 # Raises ValueError
```
11. Practical Example
Here’s a complete example:
```python
class Car:
total_cars = 0 # Class attribute
@classmethod
def get_total_cars(cls):
return cls.total_cars
# Create instances
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")
# Parse back
parsed_data = json.loads(json_string)
print(parsed_data["temperature"]) # Output: 25.5
```
- IoT Relevance : JSON is a standard format for sending structured data from
IoT devices to APIs or databases (e.g., AWS IoT, ThingSpeak).
2. `xml` (xml.etree.ElementTree)
- Purpose : Part of the `xml` package, `xml.etree.ElementTree` is a
lightweight module for parsing and creating XML (Extensible Markup
Language) data, a more verbose alternative to JSON.
- Use Case : Less common in IoT than JSON due to its verbosity, but useful
when interfacing with legacy systems or protocols (e.g., SOAP-based services)
that require XML.
- Key Features :
- Parse XML documents into a tree structure.
- Create or modify XML programmatically.
- Example :
```python
import xml.etree.ElementTree as ET
# Create XML
root = ET.Element("device")
ET.SubElement(root, "name").text = "Sensor2"
print(ET.tostring(root, encoding="unicode"))
```
- IoT Relevance : Useful for IoT systems integrating with enterprise software
or older protocols, though JSON is more common in modern setups.
3. `http.client` (formerly `httplib`)
- Purpose : A low-level module for making HTTP requests and handling
responses. It’s part of Python’s standard library and provides fine-grained
control over HTTP communication.
- Use Case : In IoT, it can be used to send data from devices to web servers or
APIs directly, though higher-level libraries like `requests` are often preferred
for simplicity.
- Key Features :
- Supports GET, POST, and other HTTP methods.
- Handles headers, status codes, and response data.
- Example :
```python
import http.client
conn = http.client.HTTPSConnection("api.example.com")
conn.request("GET", "/data")
response = conn.getresponse()
print(response.status) # Output: 200 (if successful)
print(response.read().decode()) # Output: Response body
conn.close()
```
- IoT Relevance : Useful for lightweight IoT devices needing to communicate
with RESTful APIs without extra dependencies (e.g., on MicroPython), though
it’s less intuitive than `requests`.
4. `urllib` (urllib.request, urllib.parse, etc.)
- Purpose : A collection of modules for working with URLs, including
fetching data (`urllib.request`), parsing URLs (`urllib.parse`), and handling URL
encoding. It’s a higher-level alternative to `http.client`.
- Use Case : In IoT, it’s handy for fetching data from web services (e.g.,
weather APIs) or posting sensor data to a server.
- Key Components :
- `urllib.request`: For opening and reading URLs.
- `urllib.parse`: For breaking down or constructing URLs.
- Example :
```python
import urllib.request
# Email details
sender = "[email protected]"
receiver = "[email protected]"
msg = MIMEText("Temperature alert: 35°C!")
msg["Subject"] = "IoT Alert"
msg["From"] = sender
msg["To"] = receiver
# Send to a server
req = urllib.request.Request("http://example.com/api", data=json_data.encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req) as response:
print(response.read().decode())