0% found this document useful (0 votes)
4 views103 pages

Python Programming

This document serves as an introduction to Python programming, covering its syntax, data types, and basic operations. It explains key concepts such as variables, operators, conditional statements, and loops, providing examples for clarity. The content is aimed at beginners, emphasizing Python's versatility and ease of use for solving various problems.

Uploaded by

aleenacshss
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views103 pages

Python Programming

This document serves as an introduction to Python programming, covering its syntax, data types, and basic operations. It explains key concepts such as variables, operators, conditional statements, and loops, providing examples for clarity. The content is aimed at beginners, emphasizing Python's versatility and ease of use for solving various problems.

Uploaded by

aleenacshss
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to

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.

Aleena paul , HSST Computer Science, vps-Ashtamichira


Python S yntax and Data Types
S yntax B as ics
Python follows a simple and readable syntax, using whitespace indentation to
define code blocks. This makes it easy for beginners to write and understand
Python programs.

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

Addition and Multiplication and Modulus and Floor Division


S ubtraction Division Ex ponentiation
Floor division, also known
The most basic arithmetic More complex operators, The modulus operator as integer division,
operators, addition and multiplication and division returns the remainder of a truncates the result to the
subtraction allow you to enable you to scale division, while nearest whole number,
combine or separate numeric values up or exponentiation raises a providing a way to work
numeric values to perform down, revealing number to a specified with whole numbers in
calculations. relationships between power, unlocking division operations.
quantities. advanced mathematical
capabilities.
Sample Program: Performing Basic
Arithmetic Operations
Addition
a=5
1
b=3
c=a+
b

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

# Add two numbers


sum = num1 + num2

# Display the sum


print(sum)

In Python, anything inside print() is displayed on the screen


Everything we want to display on the screen is included inside the parentheses ()

The text we want to print is placed within double quotes


We can also use single quotes to print text on the screen
Add Two Numbers
# This program adds two numbers
num1 = 10
num2 = 6

# Add two numbers


sum = num1 + num2

# Display the sum


print(“Sum of given numbers is “, sum)

In Python, anything inside print() is displayed on the screen


Everything we want to display on the screen is included inside the parentheses ()

The text we want to print is placed within double quotes


We can also use single quotes to print text on the screen
Add Two Numbers
# This program adds two numbers
num1 = 1.5
num2 = 6.3

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

The sum of 1.5 and 6.3 is 7.8


Add Two Numbers With User Input
# This program adds two numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))


We use the built-in function
input() to take the input.
Enter first number: 1.5
Since, input() returns
Enter second number: 6.3
a string we convert the
The sum of 1.5 and 6.3 is 7.8
string into number using
the float() function.
Calculate the Square Root
# This program reads one number
a = float(input('Enter first side: '))

,
# 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.

print(‘The square root of %0.3f is %0.3f'%(num ,num_sqrt))

The square root of 8.000 is 2.828


Calculate the Area of a Triangle using Heron's formula
# This program reads 3 numbers
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2 # s is the semi-perimeter of the triangle,

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
# ‘** 0.5’ is the exponentiation operator
# in Python, which is used to calculate the square root.

print('The area of the triangle is %0.2f' %area)


The area of the triangle is 14.70
Python Basic Input and Output
Syntax of print()

print(object= sep= end= file= flush=)


Here,

•object - value(s) to be printed


•sep (optional) - allows us to separate multiple objects inside print().
•end (optional) - allows us to add specific values like new line "\n", tab "\t“ etc
•file (optional) - where the values are printed. It's default value is [Link] (screen)
•flush (optional) - boolean specifying if the output is flushed or buffered. Default: False
Python print() with end Parameter

print('Good Morning!', end= ' ')


print('It is rainy today')

Output
Good Morning! It is rainy today

we have included the end= ' ' after the end of the first print() statement

Hence, we get the output in a single line separated by space

print('Good Morning!', end= ‘\t')


print('It is rainy today')
we get the output as same as above
Comparis on Operators : Equal to, Not Equal
to, Greater Than, Les s Than, Greater Than or
Equal to, Les s Than or Equal to
Equal to (==) Not Equal to (!=) Greater Than (>) Les s Than (<)

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.

Greater Than or Equal to (>=) Les s Than or Equal to (<=)

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

print('This s tatement is always executed')


The if - else Statement
The if-elif-els e S tatement
number = int(input('Enter first number: '))

if number > 0:
print('P os itive number')

elif number <0:


print('Negative number')

els e:
print('Zero')
print('This s tatement is always executed')
The if-elif-else Statement
The short hand

In certain situations, the if statement can be simplified into a single line.

number = 10
if number > 0:
print('Positive')

This code can be compactly written as

number = 10
if number > 0: print('Positive')
Ternary Operator in Python if...else

Python doesn't have a ternary operator.


However, we can use if...else to work like a ternary operator in other languages.

grade = 40
if grade >= 50: This code can be compactly written as

result = 'pass' grade = 40


else:
result = 'pass' if grade >= 50 else 'fail'
result = 'fail' print(result)
print(result)
Introduction to
Looping
S tatements in
P ython
Discover the power of repetition in P ython with looping
statements. Learn how to automate tasks, iterate over data, and
create dynamic programs by mastering the fundamentals of while
and for loops.
The while Loop
Repeated Execution
1 The while loop in Python repeatedly executes a block of code as long as a specific condition
remains true.

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

Python program that uses a while loop to print the first


10 natural numbers (i.e., from 1 to 10):

# Simple program to print the first 10 natural numbers

# Initialize the counter


number = 1
# Loop until the number is greater than 10
while number <= 10:
print(number)
number += 1 # Increment the counter by 1
Python program that uses a while loop to print the first 10 natural numbers (i.e., from 1 to 10):

Python program – calculate


the sum of numbers until user enters 0

# the sum of numbers until user enters 0

number = int(input('Enter a number: '))


total = 0
# iterate until the user enters 0
while number != 0:
total += number
number = int(input('Enter a number: '))
print('The sum is = ', total)
Python program that uses a while loop to print the first 10 natural numbers (i.e., from 1 to 10):

In Python, a while loop can have an optional else clause –


that is executed once the loop condition is False.

# the sum of numbers until user enters 0

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’]

# access elements of the list one by one

for x in languages:
print(x)

In the above example, we have created a list


called languages.
As the list has 4 elements, the loop iterates 4 times.
Python for Loop
language = 'Python'

# iterate over each character in language

for x in language:
print(x)

# use print(x, end=‘\t’) for vertical printing

Here, we have printed each character of the


string language using a for loop.
The for loop does not require an indexing variable to set beforehand.
Python for Loop
# iterate from x=0 to x=3

for x in range(4):
print(x)

Here, we used the for loop to iterate over a


range from 0 to 3
the range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
Python for Loop
# iterate from x=0 to x=5

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but


the values 0 to 5
the range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
Python for Loop
# iterate from x=2 to x=5

for x in range(2,6):
print(x)

The range() function defaults to 0 as a


starting value,
however it is possible to specify the starting
value by adding a parameter: range(2, 6),
which means values from 2 to 6 (but not
including 6, ie 2,3,4,5).
Python for Loop
# iterate from x=2 to x=29

for x in range(2,30,3):
print(x)

The range() function defaults to increment


the sequence by 1, however it is possible to
specify the increment value by adding a
third parameter: range(2, 30, 3):
Nested for Loop
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

The "inner loop" will be executed one time


for each iteration of the "outer loop":
Python for Loop
#find the factorial of a number provided by the user
# To take input from the user

num = int(input("Enter a number : "))


factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for j in range(1,num + 1):
factorial = factorial*j
print("The factorial of ",num,“ is ",factorial)
Loop Control Statements: break, continue,
and pass
break
1 Exits the current loop immediately

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

n = 10 Here, notice that we have used


the pass statement inside the if
# use pass inside if statement Statement .
if n > 10:
pass However, nothing happens
print('Hello') when the pass is executed.
It results in no operation
(NOP).
Functions and Modules
1 Functions
Encapsulate reusable logic into modular blocks of code that can be called
with arguments and return values.

2 P arameters and R eturns


Functions can accept input data through parameters and produce output
through return statements, making them powerful building blocks.

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

def add_numbers(num1, num2):


sum = num1 + num2
print("Sum: ", sum)

# function call with two values


add_numbers(5, 4)
Python - The return Statement
# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:', square)
Default Argument in Python Functions
def greet(name, message="Hello"):
print(message, name)

# calling function with both arguments


greet("Alice", "Good Morning")

# calling function with only one argument


greet("Bob")
Python Function With Arbitrary Arguments
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function(“Abhinav ", “Abhilash", “Abhishek")

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.

result = result + num To handle this kind of situation, we can


print("Sum = ", result) use arbitrary arguments in Python.

Arbitrary arguments allow us


# function call with 3 arguments to pass a varying number of values
during a function call.
find_sum(1, 2, 3)
We use an asterisk (*) before the parameter
name to denote this kind of argument.
# function call with 2 arguments
find_sum(4, 9)
Python Function With Keyword Arguments
def my_function(child3,child1,child2):
print("The youngest child is " + child3)

my_function(child1=“Abhinav ", child2=“Abhilash", child3=“Abhishek")

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)

fruits = ["apple", "banana", "cherry"]

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

# sqrt computes the square root


square_root = [Link](4)
print("Square Root of 4 is",square_root)

# pow() computes the power

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

What is a Module? Importing Modules Standard Library Modules


A module is a file containing You can import modules Python's standard library
Python definitions and using the `import` statement includes many useful pre-
statements. It provides a to access their functionality built modules for common
way to group related code in your Python programs. tasks, like `math`, `os`, and
together. `datetime`.
Python Modules
Module is a file that contains code to perform a specific task.
A module may contain variables, functions, classes etc
Let us create a module. Type the following and save it as [Link]

Importing Module named [Link]


Creating Module named [Link]
import example
# Python Module addition
value= [Link](4,5)
def add(a, b): # returns 9 to value
result = a + b print(value)
return result Using the module name we can access
the function using the dot . operator.
Python Modules
Let us create another module. Type the following and save it as module_greet.py
Creating Module named module_greet.py

# Python Module addition

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 2 Path manipulation


The `os` module provides The `[Link]` module offers
functions for interacting with the utilities for working with file
operating system, including file paths, such as joining, splitting,
and directory management. and normalizing them.

3 Listing files and directories


The `[Link]()` function can be used to retrieve a list of files and
directories in a specified location.
VV

Navigating the File System in Python

1 os module

import os
print([Link]())

# Output: C:\Program Files\PyScripter

We can get the present working directory using


the getcwd() method of the os module.
VV

Navigating the F ile S ys tem in Python

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

In order to remove a non-empty Renaming a Directory or a File


directory, we can use [Link]('test','new_one‘)
the rmtree() method inside
the shutil module.
Removing Directory or File in Python
import shutil
[Link]("mydir") [Link]("mydir")
[Link]("[Link]")
VV

Creating a F ile in Python

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

Creating a F ile in Python

f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())
VV

Reading a File in Python


f = open("[Link]", “r")

print([Link]())

Reading a File in Python from a specific path

f = open(“d:\\binu\[Link]", “r")

print([Link]())
VV

Loop through the file line by line


f = open("[Link]", “r")
for x in f:
print(x)

R eading 2 lines from file

f = open(“d:\\binu\[Link]", “r")
print([Link]())
print([Link]())
VV

Creating a CS V F ile in Python

import csv

with open(‘[Link]', 'w', newline='') as file:


writer = [Link](file)
[Link](["SN", “School Name", “code"])
[Link]([1, “RMHSS ", “7081"])
[Link]([2, “MCM HSS Pattimattom", “7076"])
[Link]([3, “St Marys HSS Morakkala", “7042"])

The CSV (Comma Separated Values) format is a common and


straightforward way to store tabular data.
To represent a CSV file, it should have the .csv file extension.
VV

R eading a CS V F ile in Python

import csv
with open(‘[Link]', 'r') as file:
reader = [Link](file)

for row in reader:


print(row)
Reading a CSV File using DictReader()

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.

3 Check if PIP is Installed


Open command Prompt in administrative mode and type
pip --version
C:\Windows\System32>pip --version
pip 24.0 from C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\pip (python 3.7)

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.

2 pip install numpy


this command will install the numpy library.

3 Listing Installed Packages with pip


The pip list command can be used to list all the available packages in the
current Python environment.
4 Package Information with pip show
Ex: pip show numpy command can be used to list all the details of numpy
library
1 Uninstalling a Package with pip
pip uninstall numpy

Using Requirement Files


2 Suppose we have a file [Link] which has the following entries:

Numpy
Pillow
Pygame

We can install all these packages and their dependencies by using a single
command

pip install -r [Link]


Introduction to
Pandas

Pandas is a powerful, open-source Python library widely used for


data manipulation and analysis. It provides efficient data structures
and data analysis tools, making it an essential tool for data
scientists and analysts.
What is Pandas?

1 Data Structure 2 Data Analysis 3 Performance


Pandas offers two primary Pandas provides a wide Pandas is built on top of
data structures: Series and range of functions and NumPy, providing fast
DataFrame, which allow you methods for data and efficient operations
to store and manipulate cleaning, transformation, on large datasets, even
structured (tabular, aggregation, and with limited memory
multidimensional, potentially visualization, making it a resources.
heterogeneous) and time comprehensive tool for
series data. data analysis.
Load CSV data into DataFrame
In this example, we load [Link] file into a DataFrame using pandas.read_csv() method.

import pandas as pd

# Load dataframe from csv


df = pd.read_csv(“[Link]")
print(df)
Load CSV data into DataFrame
While executing this file, an error occurred -- ModuleNotFoundError : No Module named ‘pandas’
ModuleNotFoundError

No Module named -pandas

To get rid of this, use the


following command in the
Command prompt

pip install pandas


Make sure that the command
prompt is opened in the
Administrative mode
Load CSV data into DataFrame
In this example, we load [Link] file into a DataFrame using pandas.read_csv() method.

import pandas as pd

# Load dataframe from csv


df = pd.read_csv(“[Link]“)

# Check if DataFrame is empty


if [Link]:
print('The DataFrame is empty.')
else:
print(df)
Load CSV data into DataFrame
Output
Data Visualization with Pandas
import pandas as pd
import [Link] as plt

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)

# bar graph using Pandas


[Link](x=‘Model', y='Weight', kind='bar', color='green')
[Link](‘Model Name')
[Link](‘Price')
[Link]('Car Price (Bar Graph)')
plt.tight_layout()
[Link]()
Pandas Plot

Pandas provides a
convenient way to visualize
data directly from
DataFrames and Series
using the plot() method.

This method uses


the Matplotlib library
behind the scenes to create
various types of plots.
Working with Strings
Accessing Characters
1
Retrieve individual characters

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

Acces s ing Data


Dictionaries enable quick retrieval of values using
their corresponding keys, making them ideal for tasks
like data mapping and lookups.
Sample Python Programs
1 Simple Calculator
A program that performs basic arithmetic operations like addition,
subtraction, multiplication, and division.

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.

2 What are some essential Python libraries for AI ?


Python key libraries include TensorFlow, PyTorch, Scikit-learn, NumPy, Pandas,
and Matplotlib. These libraries offer functionalities for deep learning, machine
learning, data manipulation, visualization, and more, accelerating AI model
development.
1 How does Python support rapid prototyping in AI projects ?

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.

Display Image Wait for Key Press


Utilize `[Link]()` to display the loaded image in Ensure the window remains open until you press a
a window. key using `[Link](0)`.
Syntax of [Link]()
[Link](/path/to/image, flag)
where /path/to/image has to be the complete absolute path to the image.
The flag is optional and one of the following possible values can be passed for the flag.
cv2.IMREAD_COLOR reads the image with RGB colors but no transparency channel.
This is the default value for the flag when no value is provided as the second argument for
[Link]().
cv2.IMREAD_GRAYSCALE reads the image as grey image.
If the source image is color image, grey value of each pixel is calculated by taking the average of
color channels, and is read into the array.

cv2.IMREAD_UNCHANGED reads the image as is from the source.


If the source image is an RGB, it loads the image into array with Red, Green and Blue
channels.
If the source image is ARGB, it loads the image with three color components along with
the alpha or transparency channel
Syntax of [Link]()
# Read color image using imread()
# In this example, we will read a color image.
#As the default value of the flag argument is cv2.IMREAD_COLOR, we are not passing the flag explicitly.
#Python Program

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.

3 Format Ex tens ion


Specify the desired format by adding the appropriate file extension to the
filename.
[Link]() – Save Image
# To save image to local storage using Python, use [Link]() function on OpenCV library
# The syntax [Link]() function is [Link](path, image)
# path is the complete path of the output file to which you would like to write the image .
# [Link]() returns a boolean value. True if the image is successfully written and False if the image is
# not written successfully to the local path specified

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

cap = [Link](0) # capture frames from a camera with device index=0


while(1): # loop runs if capturing has been initialized

ret, frame = [Link]() # reads frame from a camera

[Link]('Camera',frame) # Display the frame

if [Link](1) & 0xFF == ord('q'): # Wait for 25ms


break

[Link]() # release the camera from video capture

[Link]() # De-allocate any associated memory usage


Saving Video Files
1 Video Writer
Create a video writer object using `[Link]()`.

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

fourcc = cv2.VideoWriter_fourcc(*'XVID') # Define the codec and create VideoWriter object


out = [Link]('[Link]', fourcc, 20.0, (640, 480)) # creates the VideoWriter object with the specified
#parameters
# Open a sample video or a camera stream
cap = [Link](0) # 0 for the default camera, or provide a video file path

while [Link]():
ret, frame = [Link]()
if not ret:
break
[Link](frame) # Write the frame to the video file

[Link]('frame', frame) # Display the current frame

if [Link](1) & 0xFF == ord('q'):


break

[Link]() # Releases the capture object.


[Link]() # Releases the VideoWriter object
[Link]() # Closes all OpenCV windows.
Implementing Face Detection

Haarcascade Classifiers Face Detection Draw Rectangles


OpenCV provides pre-trained Use `[Link]()` to Draw rectangles around the
Haarcascade classifiers for face load the classifier and detected faces using
detection. `detectMultiScale()` to detect faces `[Link]()`.
in an image.
Python - Face Detection import cv2
alg = "haarcascade_frontalface_default.xml"
haar_cascade = [Link] (alg)
cam = [Link](0) #first / default camera
while True:
_, img = [Link]()
grayImg = [Link](img,cv2.COLOR_BGR2GRAY)
face = haar_cascade.detectMultiScale(grayImg,1.3,4)
for (x, y,w,h) in face:
[Link](img,(x, y) ,(x+w, y+h),(0,255, 0),2)
[Link]("FaceDetection", img)
key = [Link](10)
if key == 27: #escape key
break
[Link]()
[Link]()
import numpy as np
import cv2
Face & Eye Detection
face_cascade = [Link]('haarcascade_frontalface_default.xml')
eye_cascade = [Link]('haarcascade_eye.xml')
[Link]("FaceDetection", img)
k=[Link](30) & 0xff
cap= [Link](1) # using second camera
if k==27: #escape key
break
while 1:
[Link]()
ret, img = [Link]()
[Link]()
gray = [Link](img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

#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

You might also like