Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

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)

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.

data.iloc[0:5] # first five rows of dataframe
data.iloc[:, 0:2] # first two columns of data frame with all rows
data.iloc[[0,3,6,24], [0,5,6]] # 1st, 4th, 7th, 25th row + 1st 6th 7th columns.
data.iloc[0:5, 5:8] # first 5 rows and 5th, 6th, 7th columns of data frame (county -> phone1).

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'



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?

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

for python online classes. please contact 8897520530

or whatsup--8897520530

skype-durgam.anil1@gmail.com


for contents please click on below link

Tuesday, April 6, 2021

input function in python

# -*- coding: utf-8 -*- """ Created on Tue Apr 6 22:22:06 2021 @author: Onyx1 #input from the user #syntax:input() a=input() b=input() print(a+b) a=int(input("please enter number") ) #string type b=int(input("please enter number ")) #string type print(a,type(a)) print(b,type(b)) print(a+b) a=input("enter your name") print(a, type(a)) a =float(input("please enter floating values")) print(a,type(a)) a= int(input("enter number")) print(a,type(a)) """ #raw_input------python 2.x version input

doc string in python

""" #docstring def basha(): ''' company name:Harish company author:Harish program description: addition , substraction, multiplication functions file date of started:06-04-2021 date modified:08-04-2022 second user: '''''' print("Basha") #__doc__ -------> docstring print(basha.__doc__) ''' def basha1(): """ company_name:Harish company author:Harish program description: addition , substraction, multiplication functions file date of started:06-04-2021 date modified:08-04-2022 second user: """ print("Basha") #__doc__ -------> docstring print(type(basha1)) print(basha1.__doc__) '''

Monday, April 5, 2021

operators in python

""" Created on Mon Apr 5 21:18:07 2021 @author: Onyx1 #class-3-05-04-2021 #addition a=10 b=20 print(a+b) #substraction print(b-a) print(a-b) #multiplication print(a*b) #division print(a/b) #floor division print(a//b) #power print(a**b) #python 2.x print("anl") #operators #arthimatic operation #assignment operators #logical operators #conditional #identify #membership #bitwise #arthimatic operation # +,-,*,/,%,//,**---> operators #assignment operators a=10 b=20 a=a+b b=b-a a=a*b print(a) b=30+50 print("b-",b) a=20 b=10 a=a/b print(a) a=20 b=10 a=a//b print(a) a=20 b=10 a=a**b print(a) #logical operators #& | ! #and a=4#0100 b=2#0010 a = a & b print(a) a=10#1010 b=8#1000 a = a & b print(a) a=4 #0100 b=2 #0010 harish=a|b #0110--6 print(harish) #not....not available a=2 #0010 a!=3 #0011 print(a) #conditional operator a=5 a==5 #5==5 if (a==5): print("this is harish") a>5 #comparison greater than a<4 #comparison less than a<=5 #less than or equal to a>=10 # greater than or equal to a!=10 #not equal to #identify #is #is not #is if two values true then return True same object #is not if two value not True then return False same object x=["rose","lilli"] b=["rose","lilli"] a=x #print(a,x) #print(id(a),id(x)) #print(b,id(b)) print(x is a) #true print(x is b) #False print(x is not b)#True print(x is not a)#false """ #membership #in #not in x=["rose","lilli"] print("rose" in x) #if member exist ---true print("chicken" not in x ) #not exist ---true print("lilli" not in x ) #false

Saturday, April 3, 2021

Operations on numbers in python

dd=3
mm=4
yyyy=2021
print(dd,mm,yyyy,end="",sep="kfdjdskjgshgjhsfdjghdsjfg")
print("03-04-2021")
dd=3
mm=4
yyyy=2021
#print("dd-",dd,"mm-",mm,"yyyy-",yyyy,end="",sep="")
#print("03-04-2021")
#print("dd{}-mm-{}-yyyy-{}".format(mm,dd,yyyy))
#print("%d-%d-%d",dd,mm,yyyy)
#print(dd,mm,yyyy)
#boolean=2values
#True----->1
#False---->0
a=True
print(a)
a=False
print(a)
print(True)
print(False)
#operations on number
#+,_,/,%,**,<,>>=,<=,!,!=
#addition---'+'
a=1054545454545454545454421231545313248432132454
b=206545423132468484543545484843415454564545121324874987524154879848544564654564564654548798798
a=a+b
#print(a)
a=a+a+b+a+a+b+b+a+a+b+b+b+b+a+a+b+b+a+a+b+a+b+b+b
b=a+a+b+a+a+b+b+a+a+b+b+b+b+a+a+b+b+a+a+b+a+b+b+b
#print(a+b)
#subtraction ---'-'
a=20
b=10
c=a-b
print(c)
#multiplication---'*'
a=205454564545454545132132156456451234156456451545456456451341
b=10657484564354846454654845645467484546546546
c=454545454546545453423132545454545465456456454554
print(a*b*c)
print(a*b*c*a*b*c)
#BODMAS
#B-brackets
#O-of
#D-division
#M-multiplication
#A-addition
#s--substraction
print((5*4)+10)
#division---'/' a=10
b=2
#print(type(a),type(b))
c=a/b
print(c)
a=10
b=2
#print(type(a),type(b))
c=a/b
print(c)
#floor division
a=11
b=2
#print(type(a),type(b))
c=a//b
print(c)
a=115465454564564545454545454545
b=2
#print(type(a),type(b))
c=a//b
print(c)
#power **
print(2**5)
print((2**5)**2)
print(10**2)
""" print "jyothi laxmi" #2.0
#integer----int
#string-----str
#float------float
#char--------xxxxxx not available

Tuesday, March 16, 2021

django day6 class html input

https://drive.google.com/file/d/1z8wgE8vx-OeX4j-0ii7LjAHMddpDKMNk/view?usp=sharing

Monday, March 8, 2021

django day4 first app running

your app urls.py ===================== from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.home,name="home"), path('contact',views.contact,name="contact") ] your app views.py ====================== from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): #1+2 #HttpResponse("

this is homepage

") #return HttpResponse("

this is test2 app homepage

") return render(request, "home.html", {'name': "the king"}) def contact(request): return HttpResponse("

this is app contactpage

") template--home.html ========================

this is templates page home page{{name}}

this is templates page home page{{name}}

this is templates page home page{{name}}

this is templates page home page{{name}}

this is templates page home page{{name}}

this is templates page home page{{name}}

project urls.py ============================= from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',include('test2.urls')), path('admin/', admin.site.urls), ]

Sunday, March 7, 2021

django day3

#urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.home,name="home"), path('contact',views.contact,name="contact"), path('aboutus',views.aboutus,name="aboutus"), path('admin/', admin.site.urls), ] #views.py from django.http import HttpResponse def home(request): #1+2 #HttpResponse("

this is homepage

") return HttpResponse("

this is firstpage

") def contact(request): return HttpResponse("

this is contactpage

") def aboutus(request): return HttpResponse("

about page

")

Friday, March 5, 2021

sep, end in print method in python

""" print(10,20,30,sep='@') print(10,20,end='') print(" ", 30) #print(input("enter number")) #print("you opened django server with IP:http://127.0.0.1:8000\n") def ranjith(): print("ranjith is basha") print("chandu is king") ranjith() def connect(): print("you opened django server with IP:http://127.0.0.1:8000\n") def disconnect(): print("it is disconnected") connect() while(1): print("basha") disconnect() i=0 if(i==0): print("rajinikanth") else: print("ramyakrishna") """

Friday, February 12, 2021

day 35 table widget and text widget

from tkinter import * import pymysql def create_table(): conn=pymysql.connect(host="localhost",user="root",password="",db="sslabs") mycursor=conn.cursor() print("inside create table") #mycursor.execute("CREATE TABLE hotel (id INT AUTO_INCREMENT PRIMARY KEY, dosa VARCHAR(255), add VARCHAR(255), idle VARCHAR(255) )") #sql = "INSERT INTO hotel (dosa, idle, add) VALUES (%s, %s, %s)" mycursor.execute("CREATE TABLE hotel (id INT AUTO_INCREMENT PRIMARY KEY, dosa VARCHAR(255),idle VARCHAR(255), sum VARCHAR(255))") #1234514532 #sub=e3.get() #val = (dosa1, idle1) #mycursor.execute(sql, val) conn.commit() print(mycursor.rowcount, "record inserted.") def display(): #create_table() conn=pymysql.connect(host="localhost",user="root",password="",db="sslabs") mycursor=conn.cursor() #print("First Name: %s\nstandard:%s\nsubject:%s" % (e1.get(),e2.get(),e3.get())) #query = "SELECT * FROM student" ## getting records from the table #mycursor.execute(query) ## fetching all records from the 'cursor' object #records = mycursor.fetchall() ## Showing the data #for record in records: #print(record) a=e1.get() a=int(a) print(type(a)) b=e2.get() b=int(b) print(type(b)) sql = "INSERT INTO hotel (dosa, idle,sum) VALUES (%s, %s,%s)" c=a+b #sub=e3.get() val = (a,b,c) mycursor.execute(sql, val) Label(praveen , text=a).grid(row=5) conn.commit() praveen=Tk() #root=Tk() praveen.geometry("500x300") #root.geometry("500x300") praveen.title("Hotel management") #root.title("Hostel management") Label(praveen, text="dosa").grid(row=0) Label(praveen , text="idle").grid(row=1) e1=Entry(praveen) name=e1.grid(row=0,column=1) #e3=Entry(root) #name=e3.grid(row=0,column=1) e2=Entry(praveen) standard = e2.grid(row=1,column=1) Button(praveen,text='Quit', command=praveen.quit).grid(row=2,column=0,sticky=W,pady=4) Button(praveen,text='display', command=display).grid(row=2,column=1,sticky=W,pady=4) #Button(praveen,text='Insert', command=create_table).grid(row=2,column=2,sticky=W,pady=4) mainloop() # -*- coding: utf-8 -*- """ Created on Thu Feb 11 22:45:50 2021 @author: Onyx1 """ from tkinter import * import pymysql root = Tk() # specify size of window. root.geometry("250x170") # Create text widget and specify size. T = Text(root, height = 5, width = 52) T.pack() # Create label l = Label(root, text = "Fact of the Day") l.config(font =("Courier", 14)) l.pack() Fact = """A man can be arrested in Italy for wearing a skirt in public.""" # Create button for next text. b1 = Button(root, text = "Next", ) b1.pack() # Create an Exit button. b2 = Button(root, text = "Exit", command = root.destroy) b2.pack() # Inserroot The Fact. #root.insert(root.END, Fact) root.mainloop()

day 36 menu bar using python

#from tkinter import Toplevel, Button, Tk, Menu ,Label from tkinter import * top = Tk() def display_text(): w = Label(top,text="Hello Tkinter") #new_win=Tk() #new_win.geometry("300*400") w.pack() menubar = Menu(top) file = Menu(menubar, tearoff=0) file.add_command(label="New",command=display_text) file.add_command(label="Open") file.add_command(label="Save") file.add_command(label="Save as...") file.add_separator() file.add_command(label="print") file.add_command(label="print preview") file.add_command(label="Close") file.add_command(label="Exit", command=top.quit) menubar.add_cascade(label="File", menu=file) edit = Menu(menubar, tearoff=0) edit.add_command(label="Undo") edit.add_command(label="Cut") edit.add_command(label="Copy") edit.add_command(label="Paste") edit.add_separator() edit.add_command(label="Delete") edit.add_command(label="Select All") menubar.add_cascade(label="Edit", menu=edit) help = Menu(menubar, tearoff=0) help.add_command(label="About") menubar.add_cascade(label="Help", menu=help) view = Menu(menubar, tearoff=0) view.add_command(label="View") menubar.add_cascade(label="View", menu=view) top.config(menu=menubar) top.mainloop()

Thursday, February 11, 2021

pandas table with dictionary

df = pd.DataFrame( { "Name": [ "Braund, Mr. Owen Harris", "Allen, Mr. William Henry", "Bonnell, Miss. Elizabeth", ], "Age": [22, 35, 58], "Sex": ["male", "male", "female"], } ) print(df) output: Name Age Sex 0 Braund, Mr. Owen Harris 22 male 1 Allen, Mr. William Henry 35 male 2 Bonnell, Miss. Elizabeth 58 female

python class topic video