Python Programming
Python Programming
P ython
P rogramming
P ython is a powerful, versatile, and beginner-friendly
programming language. In this introduction, we'll explore the
fundamentals of P ython, its syntax, and how it can be used to
solve a variety of problems.
Data Types
Python supports a variety of data types, including integers, floats, strings,
booleans, lists, tuples, and dictionaries. Each data type has its own properties
and uses.
Dynamic Typing
Python is dynamically typed, meaning variables can hold values of different
data types. This flexibility allows for rapid prototyping and easier code
maintenance.
Variables and Operators
Variables
1 Store and manipulate data
Arithmetic Operators
2
Perform basic mathematical calculations
Comparison Operators
3
Compare values and make decisions
In Python, variables allow you to store and work with data. Arithmetic operators like +, -, *, and / enable you to perform
calculations. Comparison operators like <, >, ==, and != help you make logical comparisons between values. These
fundamental building blocks form the backbone of Python programming.
Arithmetic Operators: Addition, S ubtraction,
Multiplication, Divis ion, Modulus ,
Exponentiation, Floor Divis ion
Subtraction
a = 10
2
b=4
c =a -b
Multiplication
a=6
3
b=7
c=a*b
Division
a = 15
4
b=3
c =a /b
Add Two Numbers
# This program adds two numbers
num1 = 1.5
num2 = 6.3
,
# calculate the square root
num_sqrt = num ** 0.5
# ‘** 0.5’ is the exponentiation operator
# in Python, which is used to calculate the square root.
Output
Good Morning! It is rainy today
we have included the end= ' ' after the end of the first print() statement
The equal to operator The not equal to The greater than The less than operator
checks if two values are operator checks if two operator checks if the checks if the first value
the same. It returns values are different. It first value is larger than is smaller than the
True if they are equal, returns True if they are the second. It returns second. It returns True if
and False if they are not equal, and False if True if the first value is the first value is less,
not. they are equal. greater, and False if it is and False if it is not.
not.
The greater than or equal to operator checks if the first The less than or equal to operator checks if the first
value is larger than or equal to the second. It returns value is smaller than or equal to the second. It returns
True if the first value is greater or equal, and False if it is True if the first value is less or equal, and False if it is
not. not.
Introduction to
Conditional
Statements in
Python
Explore the power of conditional logic in Python, where programs
can make decisions based on specific criteria. Learn how to
leverage if, elif, and else statements to create dynamic and
adaptive applications.
Python if...else Statement
if if condition:
# body of if statement
if condition:
If
# body of if statement
else:
else:
# body of else statement
if condition1:
If # code block 1
elif condition2:
elif # code block 2
else:
else: # code block 3
The if - els e S tatement
number = int(input('Enter first number: '))
if number > 0:
print('P os itive number')
els e:
print('Negative number')
if number > 0:
print('P os itive number')
els e:
print('Zero')
print('This s tatement is always executed')
The if-elif-else Statement
The short hand
number = 10
if number > 0:
print('Positive')
number = 10
if number > 0: print('Positive')
Ternary Operator in Python if...else
grade = 40
if grade >= 50: This code can be compactly written as
Flexible Conditions
2 The condition can be any valid Python expression that evaluates to True or
False.
Infinite Loops
If the condition never becomes false, the loop will
3
continue to execute indefinitely, known as an infinite
loop.
The while loop is a powerful tool for creating repetitive tasks and processing data in Python. It allows your program to
execute a block of code multiple times until a specific condition is no longer met, making it ideal for a wide range of
applications, from counting and data manipulation to game logic and more.
Python program that uses a while loop to print the first 10 natural numbers (i.e., from 1 to 10):
counter = 0
while counter < 2:
print('This is inside loop')
counter = counter + 1
else:
print('This is inside else block')
The for Loop
Iterative Power 1
The for loop in Python allows you to iterate
over a sequence, such as a list, string, or
range, executing a block of code for each 2 Concis e S yntax
element. The basic syntax is for item in sequence:,
where item represents the current element
being processed in each iteration.
Vers atile Applications 3
The for loop is ideal for a wide range of
tasks, from data processing and
manipulation to automating repetitive
operations.
Python for Loop
languages = [‘Pascal', 'Python', ‘Cobol‘, ’C’]
for x in languages:
print(x)
for x in language:
print(x)
for x in range(4):
print(x)
for x in range(6):
print(x)
for x in range(2,6):
print(x)
for x in range(2,30,3):
print(x)
for x in adj:
for y in fruits:
print(x, y)
continue
2
Skips the current iteration and moves to the next
pass
3
Acts as a placeholder, doing nothing
Python's loop control statements provide fine-grained control over the execution of loops.
The break statement allows you to exit a loop prematurely, while continue skips the current iteration and moves to the next.
The pass statement serves as a placeholder, doing nothing, which can be useful during the development process.
Python break
for i in range(5):
if i == 3:
break
print(i)
Continue Statement
for i in range(5):
if i == 3:
continue
print(i)
Python pass Statement
3 Modules
Organize and distribute related functions and data in self-contained
packages, enabling code reuse and maintainability.
Create a Function def greet():
print('Hello World!')
Python Function Call
def greet():
print('Hello World!')
# call the function
greet()
print('Outside function')
Python Function Arguments
# function with two arguments
# function call
square = find_square(3)
print('Square:', square)
Default Argument in Python Functions
def greet(name, message="Hello"):
print(message, name)
If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Python Function With Arbitrary Arguments
# program to find sum of multiple numbers
def find_sum(*numbers): Sometimes, we do not know in advance the
result = 0 number of arguments that will be passed into a
for num in numbers: function.
You can also send arguments with the key = value syntax..
This way the order of the arguments does not matter
Python Function passing a List as an Argument
def my_function(food):
for x in food:
print(x)
my_function(fruits)
You can send any data types of argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function.
Python Library Functions
print() 1
prints the string inside the
quotation marks.
2 sqrt()
returns the square root of a
number.
pow() 3
returns the power of a
number.
These library functions are defined inside the module. And to use them, we must include the
module inside our program.
Python Library Functions
import math
power = pow(2, 3)
print("2 to the power 3 is",power)
Introduction to
Python Modules ,
P ackages , and F iles
P ython modules, packages, and files are fundamental building
blocks that allow you to organize and reuse your code. They help
you manage complexity, improve code readability, and promote
collaboration within larger projects.
Unders tanding Python Modules
def greeting(name):
print("Hello, " + name) Importing Module named module_greet.py
import module_greet
module_greet.greeting(“Binu”)
Python Modules
Let us create another module. Type the following and save it as module_greet.py
Creating Module named module_dictionary.py
Teacher = {
"name": “Thomas Jacob K",
"age": 46,
Importing Module named module_dictionary.py
"school": "RM HSS",
"place": "Vadavucode" import module_dictionary
}
na = module_dictionary.Teacher["name"]
print(na)
File I/O Operations
R eading Files
1 Load data from files
Writing Files
2
Save data to files
File Modes
3
Control read/write access
Python provides powerful file input/output (I/O) operations, allowing you to read data from and write data to files on your
computer's file system. This includes the ability to open files in different modes (e.g., read, write, append) and handle
file-related tasks like creating, modifying, and deleting files and directories.
Navigating the File System in Python
1 os module
import os
print([Link]())
1 os module
import os
if [Link]("[Link]"):
print("The File is Available")
[Link]("[Link]")
else:
print("The file does not Exist")
Navigating the File System in Python
Changing Directory in Python List Directories and Files in Python
import os [Link]()
# change directory
Making a New Directory in Python
[Link]('C:\\Python33')
print([Link]()) [Link]('test')
To create a new file in Python, use the open() method, with one of
the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
VV
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
print([Link]())
f = open(“d:\\binu\[Link]", “r")
print([Link]())
VV
f = open(“d:\\binu\[Link]", “r")
print([Link]())
print([Link]())
VV
import csv
import csv
with open(‘[Link]', 'r') as file:
reader = [Link](file)
import csv
with open(‘[Link]', 'r') as file:
csv_file = [Link](file)
for row in csv_file:
print(row)
The [Link]() class can be used to read the CSV file into a dictionary,
offering a more user-friendly and accessible method.
In this example, we have read data from the [Link] file and print each row as a dictionary.
1 What is PIP?
PIP is a package manager for Python packages, or modules if you like
2 What is a Package?
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
4 Installing PIP
If you do not have PIP installed, you can download and install it from this
page [Link]
1 Python pip
pip is the standard package manager for Python.
We can use pip to install additional packages that are not available in the
Python standard library.
Numpy
Pillow
Pygame
We can install all these packages and their dependencies by using a single
command
import pandas as pd
import pandas as pd
car = ["Breza", "Wagon R", "XL 6", "Alto K 10", "Ertiga", "Baleno", "Swift", "S-Presso","celerio","Ignis","Fronx"]
Price = [13.5, 8.5, 16.5, 8, 14.5,10.8,11.2,7.5,7.8,8.5,14.3]
# create a DataFrame
data = {‘Model': car, 'Weight': Price}
df = [Link](data)
Pandas provides a
convenient way to visualize
data directly from
DataFrames and Series
using the plot() method.
String Manipulation
2
Modify and transform strings
String Methods
3
Powerful built-in functions
String Formatting
4
Combine strings dynamically
Strings are a fundamental data type in Python, allowing you to work with text. You can access individual characters,
perform operations like concatenation and slicing, and leverage a rich set of string methods to manipulate and format
text. These string-handling capabilities are essential for tasks like data processing, text analysis, and user input
handling.
Lists and Tuples
Lists
Ordered collections of items that can hold different data types. Great
for storing and manipulating sequences of data.
Tuples
Immutable ordered collections, similar to lists but with fixed sizes.
Useful for storing data that should not be changed.
List Operations
Access, modify, and manipulate list elements using indexing, slicing,
and built-in methods like append(), remove(), and sort().
Dictionaries and S ets
Dictionaries S ets
Python's built-in dictionary data structure stores key- Sets are unordered collections of unique elements.
value pairs, allowing for efficient lookup and access They are commonly used for operations like
to data. membership testing, intersection, and union.
1 2 3
2 Temperature Converter
A tool that can convert temperatures between Celsius, F ahrenheit,
and K elvin scales.
3 Guessing Game
An interactive game where the user tries to guess a randomly
generated number within a certain range.
1 Why is Python preferred for AI development ?
Python’s simplicity, extensive libraries, and similarity to human language
make it ideal for AI. Libraries like TensorFlow, PyTorch and Scikit-learn provide
powerful tools for AI tasks.
Python allows for dynamic modification and execution of code without recompilation,
facilitating iterative testing and tweaking commonly required in AI and machine learning
projects.
2
OpenCV in P ython
OpenCV is a powerful library for computer vision tasks, providing
a wide range of tools for image and video processing. This
presentation will guide you through the basics of OpenCV in
Python, exploring practical examples and applications.
Opening and Displaying Images
Import OpenCV Read Image
Start by importing the OpenCV library using the Use `[Link]()` to read an image from your file
`import cv2` command. system.
import cv2
#reading image
img = [Link]('D:/[Link]')
#printing its shape
print('Image Dimensions :', [Link])
#Output - Run the above python program, and you shall get the following output.
Image Dimensions : (400, 640, 3)
imshow() – Display or Show Image
# display an image using opencv cv2 library, you can use [Link]() function
# The syntax of imshow() function is [Link](window_name, image)
#window_name is the title of the window in which the image will be shown.
#Python Program
import cv2
#reading image
img = [Link]('D:/[Link]')
# displaying image
[Link]('Example - Show image in a window', img)
[Link](0) # waits until a key is pressed
[Link]() # destroys the window showing image
[Link](0) is important for holding the execution of the python program at this statement, so that the image window stays
visible.
If you do not provide this statement, [Link]() executes in fraction of a second and the program closes all the windows it
opened, which makes it almost impossible to see the image on the window
S aving Images in Different
Formats
1 Image Format 2 S aving Function
OpenCV supports various Use `[Link]()` to save the
image formats like JPEG, P NG, image to a specified file path.
and BMP.
import cv2
#reading image
img = [Link]('D:/[Link]')
# writing image in another format
isWritten = [Link]('D:/[Link]', img)
If isWritten:
print('Image is successfully saved as file.')
Manipulating Image Properties
Res izing Cropping Rotating
Resize the image using Crop the image using slicing to Rotate the image using
`[Link]()` to adjust its extract a specific region. `[Link]()` to change its
dimensions. orientation.
Specify the starting and ending
Specify the desired width and coordinates . Choose the rotation type: 90, 1 80,
height. or 270 degrees.
Acces s ing Webcam and Opening Video S treams
Open Webcam
Access the webcam using `[Link](0)`,
where 0 represents the default camera.
Read Frames
Continuously read frames from the webcam using `[Link]()`.
Display Frames
Display each frame in a window using `[Link]()`.
Break Loop
Exit the loop when a key is pressed using `[Link] ey(1 )`.
Capture Video using Python OpenCV cv2 library from Webcam
Python Program
import cv2
2 Write Frames
Write frames to the video file using `[Link](frame)`.
3 Release Resources
Release the video writer and webcam objects using `[Link]()`
and `[Link]()`.
Saving a Video using Python OpenCV cv2 library from Webcam
import cv2
while [Link]():
ret, frame = [Link]()
if not ret:
break
[Link](frame) # Write the frame to the video file
#finding faces, their sizes, drawing rectangles, and noting the ROI
for (x,y,w,h) in faces:
[Link](img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
[Link](roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
Thank you