Unit IV – Python Programming (Detailed Notes)
1. Introduction to Python Programming Language
Python is a high-level, interpreted programming
language created by Guido van Rossum and first
released in 1991. It emphasizes code readability and
has a syntax that allows programmers to express
concepts in fewer lines of code. Python is an open-
source language that is widely used for web
development, data science, automation, and particularly
for IoT applications, especially with Raspberry Pi.
Key Features
Easy and readable syntax
Interpreted language (no need to compile)
Supports multiple programming paradigms
(procedural, OOP, functional)
Dynamically typed language
Vast collection of libraries and frameworks
Excellent community support
In IoT, Python is used for:
Sensor data collection
Device control and automation
Interfacing with APIs and cloud services
Developing lightweight web servers for data
visualization
2. Python Programming Environment
To start programming in Python, the following setup is
required:
Install Python from https://www.python.org
Choose an IDE like IDLE, VS Code, PyCharm, or Jupyter
Notebook
Write and run `.py` files using terminal or IDE run
options
To check installation, open terminal and type:
python --version
To run a Python script:
python myscript.py
3. Python Expressions
An expression is a combination of values and operators
that can be evaluated to produce a result.
Types of expressions:
Arithmetic expressions: perform basic math operations
Relational expressions: compare values
Logical expressions: combine boolean values
Assignment expressions: assign values to variables
Example:
x = 10
y = 5
sum = x + y
print('Sum:', sum)
4. Strings
Strings are sequences of characters enclosed in single,
double, or triple quotes. Python strings are immutable.
Common string operations
Indexing and slicing: s[0], s[1:4]
Concatenation: s1 + s2
Repetition: s * 3
Length: len(s)
Membership: 'a' in s
Common string methods
s.upper(), s.lower(), s.strip(), s.replace(), s.split()
Example:
s = ' Hello IoT '
print(s.strip()) # Removes
whitespace
print(s.upper()) # Converts to
uppercase
print(s.replace('IoT', 'Python'))
5. Functions
Functions are blocks of code that execute when called.
They help make code modular and reusable.
Defined using the `def` keyword
Can take parameters and return values
Help break code into smaller logical parts
Example:
def add(a, b):
return a + b
result = add(4, 5)
print('Result:', result)
6. Data Types in Python
Python supports a variety of built-in data types.
int – Integer numbers (e.g., 5)
float – Floating point numbers (e.g., 3.14)
str – Strings (e.g., 'IoT')
bool – Boolean values (True or False)
list – Mutable ordered collection (e.g., [1,2,3])
tuple – Immutable ordered collection (e.g., (1,2,3))
dict – Key-value mapping (e.g., {'sensor': 'temp'})
set – Unordered collection of unique items (e.g., {1,2,3})
Example:
info = {
'device': 'Raspberry Pi',
'status': True
}
print(info['device']) # Output:
Raspberry Pi
7. Flow Control
Python includes conditional statements and loops for
decision making and repetition.
Conditional Statements
if – executes block if condition is true
elif – checks next condition if previous was false
else – executes when no other condition is true
x = 10
if x > 0:
print('Positive')
elif x == 0:
print('Zero')
else:
print('Negative')
Loops
for loop – iterates over a sequence
while loop – repeats while a condition is true
for i in range(5):
print(i)
x = 0
while x < 5:
print(x)
x += 1
Loop Control
break – exits the loop
continue – skips to next iteration
pass – placeholder with no action
8. Importing Libraries
Libraries allow access to pre-written code and
functions. Python has many standard and external
libraries.
Standard Libraries
math – mathematical functions
datetime – date and time operations
random – random number generation
os – operating system interaction
IoT Related Libraries
RPi.GPIO – control Raspberry Pi GPIO pins
time – delay and timing functions
Adafruit_DHT – interface with DHT sensors
Example:
import math
print(math.sqrt(16)) # Output: 4.0
from math import pi
print(pi) # Output: 3.14159...