Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python projects

# How To Validate An Email Address In Python
# Using "re" package
import re   
  
regex = '^[a-z0-9]+[._]?[a-z0-9]+[@]w+[.]w{2,3}$'  
  
def check(email):   
  
    if(re.search(regex,email)):   
        print("Valid Email")   
    else:   
        print("Invalid Email")   
      
if __name__ == '__main__' :   
      
    email = "rohit.gupta@mcnsolutions.net"  
    check(email)   
  
    email = "praveen@c-sharpcorner.com"  
    check(email)   
  
    email = "inform2atul@gmail.com"  
    check(email)
Comment

python projects

# How to Perform Motion Detection Using Python

# Importing the Pandas libraries  
import pandas as panda  

# Importing the OpenCV libraries  
import cv2  

# Importing the time module  
import time  

# Importing the datetime function of the datetime module  
from datetime import datetime 

# Assigning our initial state in the form of variable initialState as None for initial frames  
initialState = None  

# List of all the tracks when there is any detected of motion in the frames  
motionTrackList= [ None, None ]  

# A new list 'time' for storing the time when movement detected  
motionTime = []  

# Initialising DataFrame variable 'dataFrame' using pandas libraries panda with Initial and Final column  
dataFrame = panda.DataFrame(columns = ["Initial", "Final"])

# starting the webCam to capture the video using cv2 module  
video = cv2.VideoCapture(0)  

# using infinite loop to capture the frames from the video 
while True:  

   # Reading each image or frame from the video using read function 

   check, cur_frame = video.read()  

   

   # Defining 'motion' variable equal to zero as initial frame 

   var_motion = 0  

   

   # From colour images creating a gray frame 

   gray_image = cv2.cvtColor(cur_frame, cv2.COLOR_BGR2GRAY)  

   

   # To find the changes creating a GaussianBlur from the gray scale image  

   gray_frame = cv2.GaussianBlur(gray_image, (21, 21), 0)  

   

   # For the first iteration checking the condition

   # we will assign grayFrame to initalState if is none  

   if initialState is None:  

       initialState = gray_frame  

       continue  

       

   # Calculation of difference between static or initial and gray frame we created  

   differ_frame = cv2.absdiff(initialState, gray_frame)  

   

   # the change between static or initial background and current gray frame are highlighted 

   

   thresh_frame = cv2.threshold(differ_frame, 30, 255, cv2.THRESH_BINARY)[1]  

   thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2)  

   

   # For the moving object in the frame finding the coutours 

   cont,_ = cv2.findContours(thresh_frame.copy(),   

                      cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  

   

   for cur in cont:  

       if cv2.contourArea(cur) < 10000:  

           continue  

       var_motion = 1  

       (cur_x, cur_y,cur_w, cur_h) = cv2.boundingRect(cur)  

       

       # To create a rectangle of green color around the moving object  

       cv2.rectangle(cur_frame, (cur_x, cur_y), (cur_x + cur_w, cur_y + cur_h), (0, 255, 0), 3)  

       

  # from the frame adding the motion status   

   motionTrackList.append(var_motion)  

   motionTrackList = motionTrackList[-2:]  

   

   # Adding the Start time of the motion 

   if motionTrackList[-1] == 1 and motionTrackList[-2] == 0:  

       motionTime.append(datetime.now())  

       

  # Adding the End time of the motion 

   if motionTrackList[-1] == 0 and motionTrackList[-2] == 1:  

       motionTime.append(datetime.now())  

       

  # In the gray scale displaying the captured image 

   cv2.imshow("The image captured in the Gray Frame is shown below: ", gray_frame)  

   

   # To display the difference between inital static frame and the current frame 

   cv2.imshow("Difference between the  inital static frame and the current frame: ", differ_frame)  

   

   # To display on the frame screen the black and white images from the video  

   cv2.imshow("Threshold Frame created from the PC or Laptop Webcam is: ", thresh_frame)  

   

   # Through the colour frame displaying the contour of the object

   cv2.imshow("From the PC or Laptop webcam, this is one example of the Colour Frame:", cur_frame)  

   

   # Creating a key to wait  

   wait_key = cv2.waitKey(1)  

   

   # With the help of the 'm' key ending the whole process of our system   

   if wait_key == ord('m'):  

       # adding the motion variable value to motiontime list when something is moving on the screen  

       if var_motion == 1:  

           motionTime.append(datetime.now())  

       break 

# At last we are adding the time of motion or var_motion inside the data frame  
for a in range(0, len(motionTime), 2):  

   dataFrame = dataFrame.append({"Initial" : time[a], "Final" : motionTime[a + 1]}, ignore_index = True)  

   
# To record all the movements, creating a CSV file  
dataFrame.to_csv("EachMovement.csv")  

# Releasing the video   
video.release()  

# Now, Closing or destroying all the open windows with the help of openCV  
cv2.destroyAllWindows()
Comment

python projects

# Python Calculator

from tkinter import *

root = Tk()
root.geometry("500x500")
root.resizable(0, 0)
root.title('Python Calculator')

expression = ""

input_text = StringVar()

# clear


def btn_clear():
    global expression
    expression = ""
    input_text.set("")

# click


def btn_click(item):
    global expression
    expression = expression + str(item)
    input_text.set(expression)

# calculate


def btn_equal():
    global expression
    result = str(eval(expression))
    input_text.set(result)
    expression = ""


# input frame
input_frame = Frame(root, width=312, height=50, bd=0,
                    highlightbackground="black", highlightcolor="black",
                    highlightthickness=2)

input_frame.pack(side=TOP)

# input field inside the frame
input_field = Entry(input_frame, font=('arial', 18, 'bold'),
                    textvariable=input_text, width=50, bg="#eee", bd=0, justify=RIGHT)

input_field.grid(row=0, column=0)

input_field.pack(ipady=10)

# button frame
btns_frame = Frame(root, width=312, height=272.5, bg="grey")

btns_frame.pack()

# first row
clear = Button(btns_frame, text="CLEAR", fg="black", width=32,
               height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
               btn_clear()).grid(row=0, column=0, columnspan=3, padx=1, pady=1)
divide = Button(btns_frame, text="/", fg="black", width=10,
                height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
                btn_click("/")).grid(row=0, column=3, padx=1, pady=1)

# second row
seven = Button(btns_frame, text="7", fg="black", width=10,
               height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
               btn_click(7)).grid(row=1, column=0, padx=1, pady=1)
eight = Button(btns_frame, text="8", fg="black", width=10,
               height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
               btn_click(8)).grid(row=1, column=1, padx=1, pady=1)
nine = Button(btns_frame, text="9", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
              btn_click(9)).grid(row=1, column=2, padx=1, pady=1)
multiply = Button(btns_frame, text="*", fg="black", width=10,
                  height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
                  btn_click("*")).grid(row=1, column=3, padx=1, pady=1)

# third row
four = Button(btns_frame, text="4", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
              btn_click(4)).grid(row=2, column=0, padx=1, pady=1)
five = Button(btns_frame, text="5", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
              btn_click(5)).grid(row=2, column=1, padx=1, pady=1)
six = Button(btns_frame, text="6", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
             btn_click(6)).grid(row=2, column=2, padx=1, pady=1)
minus = Button(btns_frame, text="-", fg="black", width=10,
               height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
               btn_click("-")).grid(row=2, column=3, padx=1, pady=1)

# fourth row
one = Button(btns_frame, text="1", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
             btn_click(1)).grid(row=3, column=0, padx=1, pady=1)
two = Button(btns_frame, text="2", fg="black", width=10, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
             btn_click(2)).grid(row=3, column=1, padx=1, pady=1)
three = Button(btns_frame, text="3", fg="black", width=10,
               height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
               btn_click(3)).grid(row=3, column=2, padx=1, pady=1)
plus = Button(btns_frame, text="+", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
              btn_click("+")).grid(row=3, column=3, padx=1, pady=1)

# fourth row
zero = Button(btns_frame, text="0", fg="black", width=21, height=3, bd=0, bg="#fff", cursor="hand2", command=lambda:
              btn_click(0)).grid(row=4, column=0, columnspan=2, padx=1, pady=1)
point = Button(btns_frame, text=".", fg="black", width=10,
               height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
               btn_click(".")).grid(row=4, column=2, padx=1, pady=1)
equals = Button(btns_frame, text="=", fg="black", width=10,
                height=3, bd=0, bg="#eee", cursor="hand2", command=lambda:
                btn_equal()).grid(row=4, column=3, padx=1, pady=1)

root.mainloop()
Comment

python projects

# How to code a simple rock, paper, scissors game on Python
import random

your_input = input("Enter a choice (r = rock, p = paper, s = scissors): ")
user = ""
if your_input.lower() == "r":
    user = "rock"
if your_input.lower() == "p":
    user = "paper"
if your_input.lower() == "s":
    user = "scissors"

possible = ["rock", "paper", "scissors"]
computer = random.choice(possible)

print(f"
You chose {user}, computer chose {computer}.
")

if user == computer:
    print(f"Both players selected {user}. It's a tie!")
elif user == "rock":
    if computer == "scissors":
        print("Rock smashes scissors! You win!")
    else:
        print("Paper covers rock! You lose!")
elif user == "paper":
    if computer == "rock":
        print("Paper covers rock, You win!")
    else:
        print("Scissors cuts paper! You lose!")
elif user == "scissors":
    if computer == "paper":
        print("Scissors cuts paper! You win!")
    else:
        print("Rock smashes scissors! You lose!")
Comment

python projects

# How to Create Caesar Cipher Using Python
import string
import sys

# The word to be encoded shifts by 5 to the right, while the word to be decoded shifts by 5 to the left.
shift = 5

print(' Caesar Cipher '.center(40, '*'))
choices = ['e', 'd']
user_choice = input('Do you wish to [e]ncode, [d]ecode, or quit (any other letter)?: ').lower()

if user_choice not in choices:
    print('Program closed.')
    sys.exit()

word = input('Enter the word: ')


# ENCODING FUNCTION
def encode_words(words, shifts):
    """This encodes a word using Caesar cipher."""

    # Variable for storing the encoded word.
    encoded_word = ''

    for i in words:

        # Check for space and tab
        if ord(i) == 32 or ord(i) == 9:
            shifted_word = ord(i)

        # Check for punctuations
        elif i in string.punctuation:
            shifted_word = ord(i)

        # Check if the character is lowercase or uppercase
        elif i.islower():
            shifted_word = ord(i) + shifts

            # Lowercase spans from 97 to 122 (decimal) on the ASCII table
            # If the chars exceeds 122, we get the number it uses to exceed it and add to 96 (the character before a)
            if shifted_word > 122:
                shifted_word = (shifted_word - 122) + 96

        else:
            shifted_word = ord(i) + shifts

            # Uppercase spans from 65 to 90 (decimal) on the ASCII table
            # If the chars exceeds 90, we get the number it uses to exceed it and add to 64 (the character before A)
            if shifted_word > 90:
                shifted_word = (shifted_word - 90) + 64

        encoded_word = encoded_word + chr(shifted_word)

    print('Word:', word)
    print('Encoded word:', encoded_word)


# DECODING FUNCTION
def decode_words(words, shifts):
    """This decodes a word using Caesar cipher"""

    # Variable for storing the decoded word.
    decoded_word = ''

    for i in words:

        # Check for space and tab
        if ord(i) == 32 or ord(i) == 9:
            shifted_word = ord(i)

        # Check for punctuations
        elif i in string.punctuation:
            shifted_word = ord(i)

        # Check if the character is lowercase or uppercase
        elif i.islower():
            shifted_word = ord(i) - shifts

            # If the char is less 122, we get difference subtract from 123 (the character after z)
            if shifted_word < 97:
                shifted_word = (shifted_word - 97) + 123

        else:
            shifted_word = ord(i) - shifts

            # If the char is less 65, we get difference and subtract from 91 (the character after Z)
            if shifted_word < 65:
                shifted_word = (shifted_word - 65) + 91

        decoded_word = decoded_word + chr(shifted_word)

    print('Word:', word)
    print('Decoded word:', decoded_word)


def encode_decode(words, shifts, choice):
    """This checks if the users want to encode or decode, and calls the required function."""

    if choice == 'e':
        encode_words(words, shifts)
    elif choice == 'd':
        decode_words(words, shifts)


encode_decode(word, shift, user_choice)
Comment

python projects

# How to Write a Python program to access a specific item in a singly linked list using index value.

class Node:
    # Singly linked node
    def __init__(self, data=None):
        self.data = data
        self.next = None
class singly_linked_list:
    def __init__(self):
        # Createe an empty list
        self.tail = None
        self.head = None
        self.count = 0
	
    def append_item(self, data):
        #Append items on the list
        node = Node(data)
        if self.head:
            self.head.next = node
            self.head = node
        else:
            self.tail = node
            self.head = node
        self.count += 1
    
    def __getitem__(self, index):
        if index > self.count - 1:
            return "Index out of range"
        current_val = self.tail
        for n in range(index):
            current_val = current_val.next
        return current_val.data


items = singly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')

print("Search using index:")
print(items[0])
print(items[1])
print(items[4])
print(items[5])
print(items[10])

# Sample Output:

# Search using index:
# PHP
# Python
# Java
# Index out of range
# Index out of range
Comment

python projects

# How to send emails with python using SMTP
# import SMTP library into your project using the command below

import smtplib

# Assuming you created two new Gmail and yahoo email accounts, create a connection to the Gmail email server by using the code below.

connection = smtplib.SMTP("smtp.gmail.com")

# Create variables to hold your email credentials

my_email = "sampleemail@gmail.com"
my_password = "passwaord"

# Secure your connection.
# It's important that you secure your connection to the Gmail mail servers.
# Securing your connection to the servers will prevent unauthorized access to your email in the event it's intercepted in transit.

# This is done by calling the tls function on your connection.

connection.starttls()

# The tls function is an inbuilt method that encrypts your email data sent via the connection established to email servers.
# The method is drawn from transport layer security protocol designed to provide communications security over a network.

#log in to your email account
# Run the code below to log in. The log-in method takes two parameters to facilitate a successful log-in: your email and password.
# Make sure there are no typos on the email and password held on the variables we created earlier.

connection.login(user=my_email, password=my_password)

# Sending the email.
# We are going to call the sendmail method on our connection. The method takes up 3 parameters :
# The sending address.
# The recipient's address. ( Avoid typos while typing it out to avoid errors.)
# The message with its subject and its body. Run the following command.

connection.sendmail(from_addr=my_email, to_addrs="receipient_email@yahoo.com", msg=" Subject: My_subject 

 My message body"

# Note: The subject and the body are separated using back slashes with an n to create new lines between them.
# Close the connction.
# Close the connection to the Gmail mail servers.

connection.close()
Comment

python projects

# Python Snake Game
import pygame
import time
import random

pygame.init()

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 10

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)


def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])


def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])


def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press C to Play Again or Q to Quit", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(
                0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(
                0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()


gameLoop()
Comment

python projects

# Python program to remove comments from a Python file

# reading the file
with open("oldfile.py") as fp:
    contents=fp.readlines()

# initialize two counter to check mismatch between "(" and ")"
open_bracket_counter=0
close_bracket_counter=0 

# whenever an element deleted from the list length of the list will be decreased
decreasing_counter=0   

for number in range(len(contents)):

    # checking if the line contains "#" or not
    if "#" in contents[number-decreasing_counter]:

        # delete the line if startswith "#"
        if contents[number-decreasing_counter].startswith("#"):
            contents.remove(contents[number-decreasing_counter])
            decreasing_counter+=1

        # delete the character after the "#"    
        else:  
            newline=""  
            for character in contents[number-decreasing_counter]:
                if character=="(":
                    open_bracket_counter+=1
                    newline+=character
                elif character==")":
                    close_bracket_counter+=1
                    newline+=character
                elif character=="#" and open_bracket_counter==close_bracket_counter:
                    break
                else:
                    newline+=character
            contents.remove(contents[number-decreasing_counter])     
            contents.insert(number-decreasing_counter,newline)   


# writing into a new file
with open("newfile.py","w") as fp:
    fp.writelines(contents)
Comment

PREVIOUS NEXT
Code Example
Python :: filter in pandas 
Python :: python text input 
Python :: write lines python with line breaks 
Python :: python insert list 
Python :: how to for loop for amount of characters in string python 
Python :: xargs to copy file from text files to another directory 
Python :: How to join train and Test dataset in python 
Python :: legend matplotlib 
Python :: pass a list to a function in python 
Python :: same elements of two sets in python 
Python :: pandas convert first row to header 
Python :: python assert is not null 
Python :: def extract_title(input_df): 
Python :: group by, aggregate multiple column -pandas 
Python :: python edit string variable 
Python :: python virtual enviroment 
Python :: django apiview pagination 
Python :: get column index of maximum value in each row pandas 
Python :: get last 3 in array python 
Python :: delete element list python 
Python :: make legend box transparent in matplotlib 
Python :: run python file from another python file 
Python :: factorial of a number in python 
Python :: add key if not exists python 
Python :: split into list into even chunks 
Python :: planets with python coding 
Python :: get names of all file in a folder using python 
Python :: python append variable to list 
Python :: prolog avg of list 
Python :: hashlib sha 256 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =