Python Practice Examples: Input (Prompt) Print
Python Practice Examples: Input (Prompt) Print
Python Practice Examples: Input (Prompt) Print
else:
return product
num1 =90
num2 =34
result = multiplcation_of_number(num1,num2)
print(result)
#######################################################
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
print("\n")
if user_input.isdigit():
else:
Second Approch
print("\n")
try:
val = int(user_input)
except ValueError:
try:
val = float(user_input)
print("Input is a float number",val)
except ValueError:
def CharAtEvenIndex(str):
print("index[",i,"]", str[i])
inputStr = "pynative"
CharAtEvenIndex(inputStr)
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
def is_first_last_same(number_list):
lastElement = number_list[-1]
if (firstElement == lastElement):
return
else:
return
--------------------------------------------------------------------------------------------------------------------------
5 ) Given a list of numbers, Iterate it and print only those
numbers which are divisible of 5
def num_divisable_by_5(numlist):
if (num % 5 == 0):
print(num)
num_divisable_by_5(numlist)
Question 7: Return the total count of sub-string “Emma”
appears in the given string
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.
What is thread?
Kernel Threads
User-space threads or User threads
Every process has one thread which is always executing that is main thread()
##################################################################
def new():
for x in range(6):
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
Method Description
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
index() Searches the string for a specified value and returns the position of whe
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
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
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
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
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 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
Example
Convert from JSON to Python:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
Example
Convert from Python to JSON:
import json
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 »
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:
Try it Yourself »
Example
Use the sort_keys parameter to specify if the result should be sorted or not:
NumPy Introduction
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.
shape of an Array
The shape of an array is the number of elements in each dimension.
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):
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.
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")
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
Print(frame)
Cv2.imshow(“capturing”,gray)
Key= cv2.waitKey(1)
If key ==ord(‘q’)
Break
Print(a)
Video.release()
Cv2.destoyAllWindows
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.waitKey(0)
cv2.destroyAllWindows()
img.shape() function
import cv2
import numpy as np
img = np.zeros((512,512,3),np.uint8)
print(img)
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)
cv2.imshow("Image",img)
cv2.waitKey(0)
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