embedded system,Arduino,Raspberry pi,ARM7,MM32,STM32,PIC and Python,Django,Datascience and web development
Wednesday, July 13, 2022
Tuesday, May 3, 2022
python with mysql topic 1(How to create db)
using python we can create our on DB using python in mysql.
please follow the below lines of code
import pymysql
#create the database connections
con = pymysql.connect(host ="localhost",user = "root",password='')
#create the cursor object
cursor = con.cursor()
#execute the query
cursor.execute('CREATE DATABASE ANIL2')
#print the statement
print("database created successfully")
copy the above lines in Any python IDE, open mysql server. then run the above code you will see the Anil2 Database in Mysql
Thursday, March 17, 2022
file operations in python
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 23 06:55:56 2022
@author: durga
"""
# import os
# file1 = open("test123.txt")
# print(file1)
# file1 = open("img.jpg")
# print(file1)
# print(file1.read())
# file1 = open("employee_class.py")
# print(file1)
# print(file1.read())
# =============================================================================
#
# =============================================================================
# file2 = open("D:/python/Evening_batch/entry_test.py")
# print(file2)
# print(file2.read())
# =============================================================================
# file modes
# =============================================================================
# r = read default
# a = append mode
# w = write mode and opens also
# x = create new
# file1 = open("test.txt",'r')
# print(file1)
# print(file1.read())
# file1 = open("test.txt",'a')
# print(file1)
file1 = open("test.txt",'w')
print(file1)
for i in range(100,200):
file1 = open(f"test6{i}.txt",'x')
print(file1)
#t= text default, text mode
#b= binary mode..(images)
# file1 = open("test.txt",'r')
# print(file1.read())
# file2 = open("D:/python/morning_class/test7.txt",'r')
# print(file2.read())
# file2 = open("D:/python/morning_class/test.txt",'r')
# print(file2.read(7))
# file2 = open("D:/python/morning_class/test.txt",'r')
# print(file2.read(10))
# =============================================================================
# readline()
# =============================================================================
# file2 = open("D:/python/morning_class/test.txt",'r')
# print(file2.readline())
# print(file2.readline())
# print(file2.readline())
# print(file2.readline())
# print(file2.readline())
# file2 = open("D:/python/morning_class/test.txt",'r')
# print(file2.readline(10))
# print(file2.readline(7))
# =============================================================================
# close the files
#variable.close()
# =============================================================================
file2 = open("D:/python/morning_class/test.txt",'r')
print(file2.readline(10))
# file2.close()
# print(file2.readline(10))
# =============================================================================
# write the extra lines
#variable.write()
# =============================================================================
file2 = open("D:/python/morning_class/test.txt",'a')
file2.write("extraline append to nextline")
file2 = open("D:/python/morning_class/test.txt",'r')
print(file2.read())
file2.close()
#file2 = open("D:/python/morning_class/test.txt",'r')
print(file2.read())
file2 = open("D:/python/morning_class/test9.txt",'x')
file2.write("extraline append to nextline")
# file2 = open("D:/python/morning_class/test9.txt",'r')
# print(file2.read())
# file2.close()
# a= dir(os)
# print(a)
#CRUD----create,read,update,delete
# os.remove("test7.txt")
abstract base class in python
# ========================================================================
# example 4
# ========================================================================
# Python program invoking a
# method using super()
import abc
from abc import ABC, abstractmethod
class A(ABC):
def fun1(self):
print("Abstract Base Class")
class K(A):
def fun2(self):
super().fun1()
print("subclass ")
# Driver code
r = K()
r.fun2()
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 7 23:10:32 2022
@author: durga
"""
# Python program showing
# abstract base class work
# Python program showing
# abstract base class work
# from abc import ABC, abstractmethod
# class Animal(ABC):
# def move(self):
# pass
# class Human(Animal):
# def move(self):
# print("I can walk and run")
# class Snake(Animal):
# def move(self):
# print("I can crawl")
# class Dog(Animal):
# def move(self):
# print("I can bark")
# class Lion(Animal):
# def move(self):
# print("I can roar")
#
# # Driver code
# R = Human()
# R.move()
# K = Snake()
# K.move()
# R = Dog()
# R.move()
# K = Lion()
# K.move()
# from abc import ABC, abstractmethod
# class Polygon(ABC):
# @abstractmethod
# def noofsides(self):
# pass
# class Triangle(Polygon):
# # overriding abstract method
# def noofsides(self):
# print("I have 3 sides")
# class Pentagon(Polygon):
# # overriding abstract method
# def noofsides(self):
# print("I have 5 sides")
# class Hexagon(Polygon):
# # overriding abstract method
# def noofsides(self):
# print("I have 6 sides")
# class Quadrilateral(Polygon):
# # overriding abstract method
# def noofsides(self):
# print("I have 4 sides")
# # Driver code
# R = Triangle()
# R.noofsides()
# K = Quadrilateral()
# K.noofsides()
# R = Pentagon()
# R.noofsides()
# K = Hexagon()
# K.noofsides()
# Python program showing
# implementation of abstract
# class through subclassing
# import abc
# class parent:
# def geeks(self):
# pass
# class child(parent):
# def geeks(self):
# print("child class")
# # Driver code
# print( issubclass(child, parent))
# print( isinstance(child(), parent))
# Python program showing
# abstract properties
import abc
from abc import ABC, abstractmethod
class parent(ABC):
@abc.abstractproperty
def geeks(self):
return "parent class"
class child(parent):
@property
def geeks(self):
return "child class"
try:
r =parent()
print( r.geeks)
except Exception as err:
print (err)
r = child()
print (r.geeks)
c# variables
using System;
namespace HelloWorld
{
public class lecture
{
public int age;//This is the variable type of integer
//entry point of the our program
public static void Main(string[] args)
{
int age = 15;
string name = "srilatha";
float p = 15.4f;
bool is_working = true;
char c = 'a';
Console.WriteLine(age);
Console.WriteLine(name);
Console.WriteLine(p);
Console.WriteLine(c);
Console.WriteLine(is_working);
Console.Read();
}
}
}
output:
15
srilatha
15.4
a
True
Monday, February 7, 2022
how to open excel , an excel instances in python
Application = EnsureDispatch("Excel.Application")
Application.DisplayAlerts = False
Application.Visible = True
Application.AskToUpdateLinks = False
Application.EnableEvents = False
mapping_wb = Application.Workbooks.Open(os.path.join(os.getcwd(), "test.xlsx"))
ws = mapping_wb.Worksheets("color_check")
file_path = os.path.join(input_folder,test_file_name)
test_workbook = Application.Workbooks.Open(file_path)
test_sheet = test_workbook.Worksheets("test_sheet")
Application.Worksheets("test_sheet").Activate()
Wednesday, February 2, 2022
how to use pandas iloc
| data.iloc[0] # first row of data frame (Aleshia Tomkiewicz) - Note a Series data type output. | ||||||||||
| data.iloc[1] # second row of data frame (Evan Zigomalas) | ||||||||||
| data.iloc[-1] # last row of data frame (Mi Richan) | ||||||||||
| # Columns: | ||||||||||
| data.iloc[:,0] # first column of data frame (first_name) | ||||||||||
| data.iloc[:,1] # second column of data frame (last_name) | ||||||||||
data.iloc[:,-1] # last column of data frame (id)
Multiple columns and rows can be selected together using the .iloc indexer.
|
Tuesday, February 1, 2022
glob in python
import glob
glob.glob('./[0-9].*')
#['./1.gif', './2.txt']
glob.glob('*.gif')
#['1.gif', 'card.gif']
glob.glob('?.gif')
#['1.gif']
glob.glob('**/*.txt', recursive=True)
#['2.txt', 'sub/3.txt']
glob.glob('./**/', recursive=True)
# =============================================================================
#
# =============================================================================
import os
path=os.listdir("C:/Users")
print(path)
# =============================================================================
#
# =============================================================================
import glob
glob.glob('C:/')
Date and time in python using datetime modules
import datetime
year_number=2021
month_number=12
date_number=27
hours_number=15
minutes_number=50
seconds_number=30
datetime.datetime(year_number, month_number, date_number, hours_number, minutes_number, seconds_number)
# =============================================================================
#
# =============================================================================
import datetime
print (datetime.date.today())
# =============================================================================
#
# =============================================================================
from datetime import date
print (date.today())
# =============================================================================
#
# =============================================================================
from datetime import date
print (datetime.date.today().day)
print (datetime.date.today().month)
print (datetime.date.today().year)
#If you prefer to write in one sentence, write it as
print (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year)
# =============================================================================
#
# =============================================================================
from datetime import date
now = date.today()
print (now.day)
print (now.month)
print (now.year)
#You can also display the previous 3 sentences in one sentence
print (now.day, now.month, now.year)
#This code is cleaner and compact. Try to write the code in shortest way possible without affecting readability.
# =============================================================================
#
# =============================================================================
from datetime import date
now = date.today()
print (now.weekday())
# =============================================================================
#
# =============================================================================
Today = datetime.now()
print (Today.strftime("%a, %B, %d, %y"))
# =============================================================================
#
# =============================================================================
import datetime
Today = datetime.now()
print ("Today’s date is" ,Today.strftime("%c"))
# =============================================================================
#
# =============================================================================
from datetime import date,time,datetime,timedelta
Time_gap = timedelta(hours = 23, minutes = 34)
#Time_gap is the timedelta object where we can do different calculations on it.
print ("Future time is ", str(datetime.now() + Time_gap))
config parser in python
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
# =============================================================================
#
# =============================================================================
config = configparser.ConfigParser()
config.sections()
#[]
config.read('example.ini')
#['example.ini']
config.sections()
#['bitbucket.org', 'topsecret.server.com']
'bitbucket.org' in config
#True
'bytebong.com' in config
#False
config['bitbucket.org']['User']
#'hg'
config['DEFAULT']['Compression']
#'yes'
topsecret = config['topsecret.server.com']
topsecret['ForwardX11']
#'no'
topsecret['Port']
#'50022'
for key in config['bitbucket.org']:
print(key)
#user
#compressionlevel
#serveraliveinterval
#compression
#forwardx11
config['bitbucket.org']['ForwardX11']
#'yes'
excel opening with python and coloring the cells
from win32com.client.gencache import EnsureDispatch
Application = EnsureDispatch("Excel.Application")
Application.DisplayAlerts = False
Application.Visible = True
Application.AskToUpdateLinks = False
Application.EnableEvents = False
mapping_wb = Application.Workbooks.Open(os.path.join(os.getcwd(), "test.xlsx"))
ws = mapping_wb.Worksheets("color_check")
ws.Range(f"A{1}").Value = "This is testing"
#time.sleep(10)
#ws.RefreshAll()
#mapping_wb.FillColor("red")
#ws.Cells(1,4).Value = "Coin Toss Results" #This is Row D
#ws.Range(f"A{4}").Value = "coint toss Results"
cell = ws.Cells(2,4)
cell.Interior.Color = rgbToInt((255,0,0))
for i in range(2,5): # Assuming there is Cell(D2)=1, Cell(D3)=0, Cell(D4)=-1
cell = ws.Cells(i,4)
if cell.Value < 0:
cell.Interior.Color = rgbToInt((255,0,0)) # red
elif cell.Value == 0:
cell.Interior.Color = rgbToInt((211,211,211)) # grey
elif cell.Value > 0:
cell.Interior.Color = rgbToInt((0,255,0)) # green
else:
print('Error.')
ws.Columns.AutoFit()
mapping_wb.Save()
print("refresh done")
Wednesday, January 5, 2022
try except blocks checking
try :
print("try 1")
except:
print("except1")
try :
print("try 2")
except:
print("except2")
try :
print("try 3")
except:
print("except3")
try :
print("try 4")
except:
print("except4")
output:
try 1
try 2
try 3
try 4
Saturday, December 25, 2021
date time in python
# ========================================================================
# date time using python
# ========================================================================
#uncomment to import library
import pandas as pd
import datetime as dt
#converting string into datetime
df1 = pd.DataFrame(
{
"DateTime": pd.to_datetime(["2021-11-13 13:45:33",
'2021-11-14 14:13:25',
"2021-11-15 14:39:25",
"2021-11-16 15:16:43",
"2021-11-17 16:51:19"]),
}
)
#split datetime into individual date and time df column
df1['Dates'] = pd.to_datetime(df1['DateTime']).dt.date
df1['Time'] = pd.to_datetime(df1['DateTime']).dt.time
#join date and time columns into a datetime column
df1['DateTime_join'] = pd.DataFrame(
pd.to_datetime(df1['Dates'].astype(str) + ' ' + df1['Time'].astype(str)),
columns=['Datetime_join'])
print(df1)
# ========================================================================
# date time format change
# ========================================================================
import pandas as pd
dt = "02-11-2021"
dt1 = pd.to_datetime(dt)
dt1
#output# Timestamp('2021-02-11 00:00:00')
dt2 = pd.to_datetime(dt, format = "%d-%m-%Y")
dt2
#output# Timestamp('2021-11-02 00:00:00')
# ========================================================================
# date time format
# ========================================================================
import pandas as pd
dt = pd.to_datetime("02-11-2021")
dt3 = dt.strftime('%b/%d/%Y')
dt3
#output# 'Feb/11/2021'
Monday, December 13, 2021
Top 4 interview questions of python
Write a program on decorator?
def decor1(func):
def wrapper():
print("this is beauty function")
func()
return wrapper
def func1():
print("this is the normal function")
func1 = decor1(func1)
func1()
#2. Write a code for fibonacci series upto 1000
a,b=0,1
while b<1000:
print(b,end=',')
a,b=b,a+b
output:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987
#3.Write a code for show the list indexes with list values?
list1=[1,2,3,4,5]
for index,value in enumerate(list1):
print("index-"+str(index)+" value-"+str(value))
output:
index-0 value-1
index-1 value-2
index-2 value-3
index-3 value-4
index-4 value-5
a = 99311278
list1=[]
def sort1(x):
list1.append(b)
list1.sort()
for i in range(1,9):
b=a%10
a =int(a/10)
#print(a)
#print(b)
sort1(b)
print(list1)
Thursday, December 9, 2021
python interview questions of inventech solutions
1.difference between list and tuple?
2.is string is mutable or not?
3.how to remove duplicates from the list
4.what is set in python?
5.what is the lambda function
6.numpy: how to fetch the 5 columns randomly from CSV files
7.How to Copy "A" table with 1 lakh column into empty table "B"
8.query for fetching highest salary employee details from employee table?
Answers:
1.difference between list and tuple?
ans:
2.is string is mutable or not?
ans: string are immutable. we can't add anything at runtime
3.what is the lambda function
ans:What is Lambda Function in Python? Lambda Function, also referred to as 'Anonymous function' is same as a regular python function but can be defined without a name. While normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword.
4.how to remove duplicates from the list?
5.what is set in python?
6.numpy: how to fetch the 5 columns randomly from CSV files
7.How to Copy "A" table with 1 lakh column into empty table "B"
8.query for fetching highest salary employee details from employee table?
Wednesday, December 8, 2021
Polymorphism in python
polymorphism means one function with multiple forms. one function can act like multiple functions.
Example:
#polymorphism
print(len("hello"))
print(len([10,20,30]))
output:
5
3
#your defined polymorphism
def poly_test(a,b,c=0):
print(a+b+c)
poly_test(10,20)
poly_test(10,20, c=30)
output :
30
60
python classes
class anil_test2:
a = 10
def ani_test():
print(" This class inside function")
print(anil_test2)
python functions test1
def anil():
print("testing the values")
anil()
def anil_test():
print("testing is working")
anil_test()
Tuesday, May 18, 2021
python interview questions with SOC
Q1:what are difference between list and tuple?
Q2:what is decorator? what is the use of that?
Q3:what is the dictionary?
Q4: how to achieve dictionary values with single key?
Q5: how to get ip address in linux ?
Thursday, April 15, 2021
Python online training contents
-
using python we can create our on DB using python in mysql. please follow the below lines of code import pymysql #create the database conne...
-
1. Write a program to accept the integer value and print its table. Note: ...