Search This Blog

Monday, 29 November 2021

Comments in Python

Comments:


In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters. 

The syntax of comments in various programming languages varies considerably.

Comments in Python:

Comments are used to make program more readable and to give basic understanding to program reader that what program does and from where it starts, where it ends, etc.

Syntax:

A comment in Python starts with the hash character, # , and extends to the end of the physical line. A hash character within a string value is not seen as a comment, though. To be precise, a comment can be written in three ways - entirely on its own line, next to a statement of code, and as a multi-line comment block.

Example:
-------------------------------------------------
import datetime
import random

def date():
    #function displays date
def grn():
    #Now try to understand what this function does and tell in comment.
-------------------------------------------------


WILL U BE ABLE TO UNDERSTAND, WHAT THAT PROGRAM DOES, NO?
NOW Understand ->

def grn():
    #g - generate r - random n - number (This function generates random number)

So NOW Will u Able to Understand What this Function does?
How u understand about this program? ...... By Comment ->

    # - generate r - random - number (This function generates random number)

this is comment, started with "#" tag.
In every programming language Comment syntax may be different, like in C/C++ it started with " // "



Types of Comments:

1) Single Line Comments: 

We discussed above, is an example of Single Line Comment

2) Multiline Comments:

Multiline Comment is started with ''' (three apostrophe sign) 
Multiline comment helps to write a Paragraph in our Programs
in singleline comment you can only write a note till that line ends
in multiline comment you can write a note till you close it again with again ''' (three apostrophe sign).

THANKS I hope YOU will get SOME Knowledge from this blog.

Python PIP Package Manager

Python Package Manager (pip):

pip is a package-management system written in Python used to install and manage software packages. It connects to an online repository of public packages, called the Python Package Index. ... Python 2.7. 9 and later (on the python2 series), and Python 3.4 and later include pip (pip3 for Python 3) by default.

Command-line interface

An output of pip install virtualenv

One major advantage of pip is the ease of its command-line interface, which makes installing Python software packages as easy as issuing a command:

pip install some-package-name

Users can also easily remove the package:

pip uninstall some-package-name

Most importantly, pip has a feature to manage full lists of packages and corresponding version numbers, possible through a "requirements" file. This permits the efficient re-creation of an entire group of packages in a separate environment (e.g. another computer) or virtual environment. This can be achieved with a properly formatted file and the following command, where requirements.txt is the name of the file:

pip install -r requirements.txt

To install some package for a specific python version, pip provides the following command, where ${version} is replaced by 2, 3, 3.4, etc.:

pip${version} install some-package-name

Using setup.py

Pip provides a way to install user-defined projects locally with the use of setup.py file. This method requires the python project to have the following file structure:

example_project/
├── exampleproject/      Python package with source code.
|    ├── __init__.py     Make the folder a package.
|    └── example.py      Example module.
└── README.md            README with info of the project.

Within this structure, user can add setup.py to the root of the project (i.e. example_project for above structure) with the following content:

from setuptools import setup, find_packages

setup(
    name='example',  # Name of the package. This will be used, when the project is imported as a package.
    version='0.1.0',
    packages=find_packages(include=['exampleproject', 'exampleproject.*'])  # Pip will automatically install the dependences provided here.
)

After this, pip can install this custom project by running the following command, from the project root directory:

pip install -e .


Python Modules

 Modules: 

A module is a file containing code written by someone else which can imported and used in our program.
A module file can be written by You, Me, or by any Programmer.




Suppose you need to display the date in program, so for that we can use datetime library which come by default and is written by Python Developers, so in that library some function are written already, when we import that file in out program, then in place we import that file, that line replaces by that file content/functions.
This all happen when we compile our program, Below is an example: Learn Practically :

Suppose we have made a file: intelligentdevelopers.py
We are making our own Module/Library:
-----------------------------------------------
def welcome():           # this defines a function
    print("Welcome in Intelligent Developers Blog")

-----------------------------------------------

save this as intelligentdevelopers.py
Now in current Directory make a new file, this our main program named: program.py
which contains following code:

-----------------------------------------------
import intelligentdevelopers         #this import the library/modules in this program
welcome()                               # here we call our defined function in that module/library

-----------------------------------------------

OUTPUT:
D:\> python program.py
Welcome in Intelligent Developers Blog
D:\>

So I hope you understand how this works:
our module that we maded, that is replaced on that line where we import it and then compiler compiles that program.

So finally this code executes:
----------------------------------------------
def welcome():           # this defines a function
    print("Welcome in Intelligent Developers Blog")

welcome()                               # here we call our defined function in that module/library
----------------------------------------------

in place of 

import intelligentdevelopers 

this code replaced:

def welcome():           # this defines a function
    print("Welcome in Intelligent Developers Blog")

so Thanks, for Learning from this blog.
If you have any problem in this comment below your problem.
THANKS.

Saturday, 20 November 2021

Write a Python program to test whether a passed letter is a vowel or not.

Introduction:
This program test whether a passed letter is vowel or not.

PROGRAM:
def is_vowel(char):
    all_vowels = 'aeiou'
    return char in all_vowels
print(is_vowel('c'))
print(is_vowel('e'))				 

Output:  
True
False                                                                                                                                                                                                                                                                                                                                                                          

Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user

Introduction
Here we are writing a program to find whether a given number is even or odd.

PROGRAM
----------------------------------------------
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
    print("This is an odd number.")
else:
    print("This is an even number.")
----------------------------------------------
RESULTS : 

Enter a number: 5                                                                                             
This is an odd number.

Write a Python program to calculate number of days between two dates.

INTRODUCTION

The function returns date object with same year, month and day. All arguments are required. Arguments may be integers, in the following ranges:

  • MINYEAR <= year <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year

If an argument outside those ranges is given, ValueError is raised.

  • Note: The smallest year number allowed in a date or datetime object. MINYEAR is 1.
  • The largest year number allowed in a date or datetime object. MAXYEAR is 9999.
PROGRAM
----------------------------------------------
from datetime import date
f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)  
----------------------------------------------
Output:
9

Friday, 19 November 2021

Object tracking with OpenCV Python

 Contents:

1) Introduction to the Project
2) Uses of Object Tracking
3) Tools and Softwares used
4) Python Program.

Introduction to the Project:

Object tracking is an application of deep learning where the program takes an initial set of object detections and develops a unique identification for each of the initial detections and then tracks the detected objects as they move around frames in a video.

In other words, object tracking is the task of automatically identifying objects in a video and interpreting them as a set of trajectories with high accuracy

Uses of Object Tracking:

Object tracking is used for a variety of use cases involving different types of input footage. Whether or not the anticipated input will be an image or a video, or a real-time video vs. a prerecorded video, impacts the algorithms used for creating object tracking applications.

The kind of input also impacts the category, use cases, and applications of object tracking. Here, we will briefly describe a few popular uses and types of object tracking, such as video tracking, visual tracking, and image tracking

Tools and Softwares needer:

1) Python 3.x

2) OpenCV-Python

Hardware requirements: Camera


MAIN PROGRAM:


import cv2
cam = cv2.VideoCapture(0)
track = cv2.TrackerCSRT_create()
suc,img=cam.read()
img = cv2.flip(img,1)
bbox = cv2.selectROI("Tracking",img,False)
track.init(img,bbox)

def drawbox(img):
x,y,w,h=int(bbox[0]),int(bbox[1]),int(bbox[2]),int(bbox[3])
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)

while 1:
suc,img = cam.read()
img = cv2.flip(img,1)
suc,bbox=track.update(img)
if suc:
drawbox(img)
else:
pass
cv2.imshow("Tracking",img)
if cv2.waitkey(1) & 0xff == ord('q'):
break


Tutorial:




Making your own haarcascade OpenCV Python

What are Haarcascades?


Haar Cascade classifiers are an effective way for object detection. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.

  • Positive images – These images contain the images which we want our classifier to identify.
  • Negative Images – Images of everything else, which do not contain the object we want to detect.

Requirements:

Make sure you have python, OpenCV installed on your pc (all the latest versions).
The haar cascade files can be downloaded from the OpenCV Github repository

dasar_haartrain Tool, download from here -> Click Here

Tutorial on How to Train our own haarcascade:


Thursday, 18 November 2021

Read a text file and display the number of vowels/consonants/uppercase/lowercase ,characters in the file

 Read a text file and display the number of vowels/consonants/uppercase/lowercase, characters in the file

f=open("poem.txt","r")
vowels='aeiouAEIOU'
v=0
c=0
u=0
l=0
for i in f.read():
if i.isalpha():
if i.isupper():
u=u+1
else:
l=l+1
if i in vowels:
v=v+1
else:
c=c+1
print("Vowels=",v)
print("consonants=",c)
print("uppercase letters=",u)
print("lowercase letters=",l)
f.close()



Output:-
Vowels= 16
consonants= 24
uppercase letters= 1
lowercase letters= 39

Python program to create a CSV file named “students.csv” to store Roll , name and percentage of students

 Python program to create a CSV file named “students.csv” to store Roll , name and percentage of students

#writing records in csv file
import csv
f=open('student.csv','w',newline='')
stdwriter=csv.writer(f,delimiter=',')
stdwriter.writerow(['Rollno','Name','Marks']) # write header row
stdrec= [
['101', 'Nikhil', '99'],
['102', 'Sanchit', '98'],
['103', 'Aditya', '98'],
['104', 'Sagar', '87'],
['105', 'Prateek', '88'],
]
stdwriter.writerows(stdrec)
f.close()



Output:-
Rollno,Name,Marks
101,Nikhil,69
102,Sanchit,98
103,Aditya,98
104,Sagar,87
105,Prateek,88
106,Abhay,99

program to pass a string to a function. Return and print reverse of it

 Write a program to pass a string to a function.return and print reverse of it

def reverse(n):
n1=""
for i in n:
n1=i+n1
print("Reverse ",n1)
def main():
n=input("Enter any string ")
reverse(n)
"""
if __name__=='__main__':
main()
"""
#or
#function calling
main()




Output:-
(1). Enter any string apple
Reverse elppa
(2). Enter any string bat
Reverse tab
(3). Enter any string computer
Reverse retupmoc

python program to pass a string to the Function. Return and display the longest word

 Write a python program to pass a string to the function .Return and display the longest word

def longest_word(n):
n1=""
for i in n.split():
if len(i)>len(n1):
n1=i
print("longest word ",n1)
def main():
#n=input("Enter any string ")
n="Hello how are you greeting you"
print("String is ",n)
longest_word(n)
"""
if __name__=='__main__':
main()
"""
#or
#function calling
main()

Output:-
(1). String is Hello how are you greeting you
longest word greeting
(2).If n=”Nice to meet you” then,

String is Nice to meet you
longest word Nice

program to take input for a number calculate and display its factorial

Write a program to take input for a number calculate and display its factorial.

def fact(n):
f=1
i=1
while i<=n:
f=f*i
i=i+1
print("Factorial = ",f)
def main():
a=int(input("Enter any no "))
fact(a)
"""
if __name__=='__main__':
main()
"""
#or
#function calling
main()


Output:-
(1). Enter any no 5
Factorial = 120
(2). Enter any no 8
Factorial = 40320
(3). Enter any no 10
Factorial = 3628800

Mask Detection for COVID-19 disease

Contents:

1) Introduction of the Project
2) Functions and Module Used
3) Software requirements to run the Program
4) Main Program

1) Introduction of the Project

In today’s world, all the things have become
computerized.

As we all know, COVID-19 can spread when
People breathe, talk, cough or sneeze.
Wearing a mask keeps the virus from reaching
Others. It also can stop the virus from reaching
You.

So this program simply Detect all Faces
Camera, then detect Mask on their faces with
The help of Artificial Intelligence (A.1.)
Machine Learning (M.L.).

If someone found without Mask on his/her face
Then “Be Safe Mask not Found” text will be
printed on screen or Custom

required action can be taken by that
Organization who using this Program.

For example: If someone is without Mask then
By using SSH and Arduino this Program will
Close the door or whatever we will set.

2) Functions and Module used:

cv2.VideoCapture(0):

Cv2 is the module for real-time computer vision.
VideoCapture(0) used for capturing frames from
Camera on number (0).

cv2.CascadeClassifier(“Haarcascade.xml”):

This function reads the trained file for
Mask Detection. Haarcascade.xml is the file
contains all Coordinates codings of AI and ML for
Mask Points. We can train this our Own.

cv2.read():

This function reads the frames from Camera
Number (0) which we set above using VideoCapture

detectMultiScale():

This function detect Co-ordinates for Masks which
we trained from above function CascadeClassifer.

cv2.imshow():

This function Displays the Captured Frames which
We captured from cv2.read() function.

3) Software/Hardware Requirements to run the Program:

1) OpenCV-Python, This is Most Important because This is the main library we use in this program
2) Python 3.x, This is required because, I have tested on this only.
3) Pip3, This is required because packages we install will be installed by this program
4) Camera required, We can change this later by using real-time or from saved Image
5) Windows,Linux,Mac any OS support this because python is Cross-Platform
6) NumPy Library, We will not use this library but This will Installed with OpenCV-Python

Files for Downloading:

1) Haarcascade for Mask Trained by Me, Click Here
2) Haarcascade for Face come with OpenCV-Python by default. Click here for Download Manually

4) Main Program:

import cv2
import numpy as np
cam = cv2.VideoCapture(0)

obj = cv2.CascadeClassifier("myhaar.xml")
face = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

while 1:
r,img = cam.read()
img = cv2.flip(img,3)
mask = obj.detectMultiScale(img,1.3,5)
faces = face.detectMultiScale(img,1.3,5)
for (x,y,w,h) in mask:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(img,"Very Good! Keep it Up",(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),3,cv2.LINE_AA)
if len(mask) == 0:
print("Mask Not Found! Be Safe from CORONA.")
for (x1,y1,w1,h1) in faces:
cv2.rectangle(img,(x1,y1),(x1+w1,y1+h1),(0,0,255),2)
cv2.putText(img,"Be Safe! Mask Not Found.",(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3,cv2.LINE_AA)
cv2.imshow("A",img)
if cv2.waitKey(1) == ord('q'):
break
cv2.destroyAllWindows()


Tutorial:






how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...