To check the version of install version of python is :
Type cmd>python --version
python 3.6.0
Python practice examples
Python Input function to accept input from a user
In Python, we have the following two functions to handle input from a user and system.
input(prompt) to accept input from a user.
print() to display output on the console.
1) Given a two integer numbers return their product and if
the product is greater than 1000, then return their sum
#Given a two integer numbers return their product and if the
product
# is greater than 1000, then return their sum
def multiplcation_of_number(num1 ,num2):
product = num1 * num2
if product > 1000:
return num1 + num2
else:
return product
num1 =90
num2 =34
result = multiplcation_of_number(num1,num2)
print(result)
#######################################################
number1 = int(input("Enter the first number"))
number2 = int(input("Enter the second number"))
multi =number1 *number2
if multi > 1000:
sumoftwonumbers= number1 + number2
print(sumoftwonumbers)
else:
print(multi)
-----------------------------------------------------------------------------------
Python input() function always converts the user input into a
string then returns it to the calling program.
Python Program to check user input is a number or string
user_input =input("Enter the input")
print("\n")
if user_input.isdigit():
print("The input is number")
else:
print("the input is string")
Second Approch
user_input = input("Enter your Age")
print("\n")
try:
val = int(user_input)
print("Input is an integer", val)
except ValueError:
try:
val = float(user_input)
print("Input is a float number",val)
except ValueError:
print("No...........input is not number it is string")
2) Given a string, display only those characters which are
present at an even index number.
def CharAtEvenIndex(str):
for i in range(0, len(str)-1, 2):
print("index[",i,"]", str[i])
inputStr = "pynative"
print("origanal string is" ,inputStr)
print("Printing only even index char")
CharAtEvenIndex(inputStr)
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
3)Given a string and an integer number n, remove characters
from a string starting from zero up to n and return a new string
def is_first_last_same(number_list):
print("Given list is", number_list)
firstElement = number_list[0]
lastElement = number_list[-1]
if (firstElement == lastElement):
return
else:
return
number_list = [10, 20, 30, 40, 10,30]
print("The result is", is_first_last_same(number_list))
--------------------------------------------------------------------------------------------------------------------------
5 ) Given a list of numbers, Iterate it and print only those
numbers which are divisible of 5
def num_divisable_by_5(numlist):
print("given list is :",numlist)
print("The number divisable by 5")
for num in numlist:
if (num % 5 == 0):
print(num)
numlist = [10, 20, 30, 40 ,50]
num_divisable_by_5(numlist)
Question 7: Return the total count of sub-string “Emma”
appears in the given string
sampleStr = "Emma is good developer. Emma is a writer"
cnt = sampleStr.count("Emma")
print(cnt)
----------------------------------------------------------------------------------------------------------------
By default python’s print() function ends with a newline. A programmer with C/C++
background may wonder how to print without newline.
Python’s print() function comes with a parameter called ‘end’. By default, the value of this
parameter is ‘\n’, i.e. the new line character. You can end a print statement with any
character/string using this parameter.
---------------------------------------------------------------------------------------------------------------------
How to get current date and time in
Python?
In this article, you will learn to get today's date and current date and time in
Python. We will also format the date and time in different formats using strftime()
method.
How to get current date and time in
Python?
In this article, you will learn to get today's date and current date and time in
Python. We will also format the date and time in different formats using strftime()
method.
Python get today's date
Example 7: Time object to represent time
Time object represent the time
The strftime() method returns a string representing date and time
using date, time or datetime object.
How to achive the multithreading in python
multithreading in python can be achive by importing the threading module
cmd used is
conda install -c conda-foege tbb
What is thread?
It is the execution of a tiny sequence of program instruction that can be managed
independently and is a distinctive part of the operating system. Modern OS manages
multiple programs using a time-sharing technique. In Python, there are two different
kinds of thread. These are:
Kernel Threads
User-space threads or User threads
How to create thread in python
1) Without creating a class
2) By extending thread class - it is most common method of thread class
3) Without extending thread class
1)without creating a class
Every process has one thread which is always executing that is main thread()
##################################################################
#create the thread without creating the thread class
from threading import*
def new():
for x in range(6):
print("The child is executing ",current_thread().getName())
t1=Thread(target=new)
t1.start()
t1.join()
print("Bye", current_thread().getName())
----------------------------------------------------------------------------------------------------
-------
By extending Thread class
You can override the run() and init() methods
In addition to the methods, the threading module has the Thread class that
implements threading. The methods provided by the Thread class are as follows −
run() − The run() method is the entry point for a thread.
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
isAlive() − The isAlive() method checks whether a thread is still executing.
getName() − The getName() method returns the name of a thread.
setName() − The setName() method sets the name of a thread
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
Daemon Threads
computer science, a daemon is a process that runs in the background.
GIL :Global interpreter Lock
A lock that allow only one thread at a time to execute in oython
Needed in Cpython because memory management I not thread safe
Avoid
-use multiprocessing
Use different, free-threaded python implement (Jypython)
Use Pythn as wrapper third partu lobaries
String Methods
String is ordered , immutable , text representations.
Note: All string methods returns new values. They do not change the original
string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of whe
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of whe
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified valu
rfind() Searches the string for a specified value and returns the last position of
rindex() Searches the string for a specified value and returns the last position of
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
The difference between the index() method and the find() is that the find()
method return -1 if string not found.
Join() method –
The join() method takes all items in an iterable and joins them into one
string.
My_tuple =(“John” , ”peter” , ” Vicky”)
X = “#” .join(My_tuple)
Print(x)
Python String zfill() Method
The zfill() method adds zeros (0) at the beginning of the string, until it
reaches the specified length.
If the value of the len parameter is less than the length of the string, no
filling is done.
Syntax:-
string.zfill(len)
The Difference between the JSON and the python object json is that
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.
Example
Import the json module:
import json
Parse JSON - Convert from JSON to
Python
If you have a JSON string, you can parse it by using the json.loads() method.
The result will be a Python dictionary.
Example
Convert from JSON to Python:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
Try it Yourself »
Convert from Python to JSON
If you have a Python object, you can convert it into a JSON string by using
the json.dumps() method.
Example
Convert from Python to JSON:
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Try it Yourself »
You can convert Python objects of the following types, into JSON strings:
dict
list
tuple
string
int
float
True
False
None
Example
Convert Python objects into JSON strings, and print the values:
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Try it Yourself »
When you convert from Python to JSON, Python objects are converted into the JSON
(JavaScript) equivalent:
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Example
Convert a Python object containing all the legal data types:
import json
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
Try it Yourself »
Format the Result
The example above prints a JSON string, but it is not very easy to read, with no indentations and
line breaks.
The json.dumps() method has parameters to make it easier to read the result:
Example
Use the indent parameter to define the numbers of indents:
json.dumps(x, indent=4)
Try it Yourself »
You can also define the separators, default value is (", ", ": "), which means using a comma and a
space to separate each object, and a colon and a space to separate keys from values:
Example
Use the separators parameter to change the default separator:
json.dumps(x, indent=4, separators=(". ", " = "))
Try it Yourself »
Order the Result
The json.dumps() method has parameters to order the keys in the result:
Example
Use the sort_keys parameter to specify if the result should be sorted or not:
json.dumps(x, indent=4, sort_keys=True)
Try it Yourself »
NumPy Introduction
NumPy is a Python library used for working with arrays.
NumPy stands for Numerical Python
Why Use NumPy?
In Python we have lists that serve the purpose of arrays, but they are slow to
process.
NumPy aims to provide an array object that is up to 50x faster than
traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources
are very important.
NumPy Array Slicing
Slicing arrays
Slicing in python means taking elements from one given index to another
given index.
We pass slice instead of index like this: [start:end].
shape of an Array
The shape of an array is the number of elements in each dimension.
Joining NumPy Arrays
Joining means putting contents of two or more arrays in a single array
We pass a sequence of arrays that we want to join to
the concatenate() function, along with the axis. If axis is not explicitly passed,
it is taken as 0.
Splitting NumPy Arrays
Computer Vision
OpenCV is an open source package/ library , which is aimed at real time
computer vision.
The library is cross-platform it can support te python,java, ,etc
It was originally developed by intel
It is free for use under the open source BSD licence
Application Area includes
1. 1)2D and 3D features toolkit
2. 2)Facial recognition
3. 3)Human computer interaction
4. Motion understanding
5. Object identification
6. Segmentation and recognition
7. Motion tracking
The function cv2.imread() to read an image. The image should be in the working
directory or a full path of image should be given.
cv2.IMREAD_COLOR
Loads a color image. Any transparency of image will be neglected. It is the
default flag.
cv2.IMREAD_GRAYSCALE
Loads image in grayscale mode
cv2.IMREAD_UNCHANGED
Loads image as such including alpha channel
Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.
Display an image
Use the function cv2.imshow() to display an image in a window. The window
automatically fits to the image size.
First argument is a window name which is a string. second argument is our image.
You can create as many windows as you wish, but with different window names.
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
A screenshot of the window will look like this (in Fedora-Gnome machine):
cv2.waitKey() is a keyboard binding function. Its argument is the time in
milliseconds. The function waits for specified milliseconds for any keyboard event. If
you press any key in that time, the program continues. If 0 is passed, it waits
indefinitely for a key stroke. It can also be set to detect specific key strokes like, if
key a is pressed etc which we will discuss below.
cv2.destroyAllWindows() simply destroys all the windows we created. If you want
to destroy any specific window, use the function cv2.destroyWindow() where you
pass the exact window name as the argument.
Use the function cv2.imwrite() to save an image.
First argument is the file name, second argument is the image you want to save.
cv2.imwrite('messigray.png',img)
This will save the image in PNG format in the working directory.
Color image loaded by OpenCV is in BGR mode.
Getting Started with Videos
Goal
Often, we have to capture live stream with camera. OpenCV provides a very simple
interface to this. Let’s capture a video from the camera (I am using the in-built
webcam of my laptop), convert it into grayscale video and display it. Just a simple
task to get started.
To capture a video, you need to create a VideoCapture object. Its argument can be
either the device index or the name of a video file. Device index is just the number to
specify which camera. Normally one camera will be connected (as in my case). So I
simply pass 0 (or -1). You can select the second camera by passing 1 and so on.
After that, you can capture frame-by-frame. But at the end, don’t forget to release the
capture.
A computer can not read the image as the matrix of 0 -255
For a colour image the three images Red Green Blue
For gray and black-White img there is only one channel
IF it is color image it as 3D matrix with the 3 Channel
IF image is Black-White it has 2D matix
OpenCv it is computer Library designed for computer visoion problem in 19997
in intel
If opencv is not install then open the conda prompt I that
(base) C:\Users\varsha.shinde>cd
C:\Users\varsha.shinde\Anaconda3\etc\jupyter
conda install -c conda-forge opencv
import cv2
img=cv2.imread("C:\\Users\\varsha.shinde\\Pictures\\16.png",1)
cv2.imshow("Test",img)
cv2.waitKey(0)
imread()- To read the image
imshow() – to show the image
waitkey(0)-open the image untile we press any key
resized =cv2.resize(img,(int(img.shape[1]/2), int(img.shape[0]/2)))
Face Detaection using OpenCV
Step 1
Create a cascade classifier ,it will contaions the features of face
Step 2
Opencv will read the image and features of file
Step 3
Display the image with the rectangular face box
import cv2
face_cascade =
cv2.CascadeClassifier('C:\\Users\\varsha.shinde\\.jupyter\\haarcascade_fron
talface_default.xml')
img = cv2.imread("C:\\Users\\varsha.shinde\\Desktop\\download.jfif")
gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for(x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h), (255,0,0),3)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
VGA = 640*480
HD =1280 *720
FHD =1120*1080
4k = 3840* 2160
Import cv2, time
Video = cv2.VideoCapture(0)
A=1
While True:
A=a +1
Check, frame = video.read()
Print(frame)
Gray= cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # convert each
frame into gray scale image
Cv2.imshow(“capturing”,gray)
Key= cv2.waitKey(1)
If key ==ord(‘q’)
Break
Print(a)
Video.release()
Cv2.destoyAllWindows
Crop and resize the image
import cv2
img =
cv2.imread("C:\\Users\\varsha.shinde\\Desktop\\car.jfif")
print(img.shape)
imgResize = cv2.resize(img,(100,100))
print(imgResize.shape)
imgCropped =img[0:200,200:500]
cv2.imshow("Image", img)
cv2.imshow("Image Resize" ,imgResize)
cv2.imshow("Image Resize" ,imgCropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
image height and width is given by
img.shape() function
cv2.FILLED -method fill the color in the particular shape
printing the shape using the OpenCV
we can write the content inside the image
import cv2
import numpy as np
img = np.zeros((512,512,3),np.uint8)
print(img)
#img[200:300,100:300] =255,0,0 it dhows the recatngular
box in green color
#cv2.line(img,(0,0),(300,300),(0,255,0)) #print the diagonal
line
cv2.line(img,(0,0),(img.shape[1],img.shape[0]),(0,255,0),3)
#print the diagonaaly stright line
cv2.rectangle(img,(0,0),(250,350),(0,0,255),cv2.FILLED)
cv2.circle(img,(400,50),30,(255,255,0),5)
cv2.putText(img,"OPENCV",
(300,100),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0),1)
#write the text in the image
cv2.imshow("Image",img)
cv2.waitKey(0)
Joining the images
import cv2
import numpy as np
img
=cv2.imread("C:\\Users\\varsha.shinde\\Desktop\\car.jfif")
imHor = np.hstack((img,img))
imgVer = np.vstack((img,img))
cv2.imshow("Horizonal",imHor)
cv2.imshow("Verticale",imgVer)
cv2.waitKey(0)
cv2.destroyAllWindows()
Contours/Shape Detection
Drawing Functions in OpenCV
----------------------------------------------------------------------
project 1
Motion detection
----------------------------------------------------------------------
----------------------------------------------------------------------
pytesseract library
Tesseract is an optical character recognition engine for various operating systems,
It is free software, released under the Apache License. Originally developed by
Hewlett-Packard as proprietary software in the 1980s, it was released as open
source in 2005 and development has been sponsored by Google since 2006