1 Python Advanced
Python methods:
# Instance method
# function vs method
class Class1:
def func():
print('hi')
print(type (Class1.func)) # access funtion directly from class (function)
object = Class1()
print(type (object.func)) ##function becomes a method when called via object/instance
# of a class.
# Classmethod
class Person:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def full_name(self):
return f"{self.first_name} {self.last_name}"
@classmethod
def other(cls):
return Person('John', 'Cena', 25)
obj1 = Person.other()
print(obj1.full_name())
#
# Static method
class multiplier:
# static method are used for grouping similar functions
# or uitility methods under a class
@staticmethod
def mutli_by_2(c):
return 2*c + 100
@staticmethod
def mutli_by_5(f):
return 5*f + 100
m = multiplier.mutli_by_2(25)
print(m)
m1 = multiplier.mutli_by_5(50)
print(m1)
Higher order functions:
# Higher order functions
def sum1(x):
return x + 1
def sum2(func, x):
result = func(x)
return result
print(sum2(sum1,5))
O/p:
6
Closure:
If a variable goes out of scope or if function is removed from the current namespace. Even then if variable is remembered then this concept is called Clossure.
Closusre requirements:
1- Nested function
2- Nested function refer value from Outer function(enclosing function)
3- Outer function should return nested function
# Outer enclosing function
def sum1(a):
# Nested function
def sum2():
print(a)
return sum2 # Returning Nested function
int1 = sum1(5)
int1()
O/p:
5
Decorators:
A function which takes another function as an argument and extends its behavior without changing the original function is called a Decorator. (add functionality to an existing code).
from functools import wraps
class decorator:
def __init__(self, n):
self.n = n
def __call__(self, fn):
@wraps(fn)
def wrapper(*args, **kwargs):
print(self.n*'*')
result = fn(*args, **kwargs)
print(result)
print(self.n*'*')
return result
return wrapper
@decorator(10)
def sum(a, b, c):
return a + b + c
sum(5, 6, 4)
O/p:
**********
15
**********
Python Generators:
# Generator function
n = 0
def my_gen():
global n
n += 1
print('Printed first')
yield n
n += 1
print('Printed 2nd')
yield n
for item in my_gen():
print(item)
O/p:Printed first1Printed 2nd2
2 SQL Server DB Connection1) start the services in management studio
SQL server configuration manger start services
2) start the sql server
3) create DB, queryCREATE TABLE EMPLOYEE ( NAME CHAR(20) NOT NULL, AGE INT, INCOME FLOAT );
insert into EMPLOYEE values ('emp1', 31, 90000.00);
select * from EMPLOYEE;
Step 1: Install pyodbc(base) C:\Users\user1>pip install pyodbc
Step2: Retrieve the server nameServer name: User\User1SQL
Step 3: Obtain the database nameDatabase name: sql_db
Step 4: Get the table nameTable name: dbo.EMPLOYEE
O/p:
Printed first
1
Printed 2nd
2
2 SQL Server DB Connection
1) start the services in management studio
SQL server configuration manger start services
2) start the sql server
3) create DB, query
CREATE TABLE EMPLOYEE (
NAME CHAR(20) NOT NULL,
AGE INT,
INCOME FLOAT );
insert into EMPLOYEE values ('emp1', 31, 90000.00);
select * from EMPLOYEE;
Step 1: Install pyodbc
(base) C:\Users\user1>pip install pyodbc
Step2: Retrieve the server name
Server name: User\User1SQL
Step 3: Obtain the database name
Database name: sql_db
Step 4: Get the table name
Table name: dbo.EMPLOYEE
Connect Python IDE to SQL Server:
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};' 'Server=User1\User1SQL;' 'Database=sql_db;' 'Trusted_Connection=yes;')
cursor = conn.cursor()cursor.execute('SELECT * FROM sql_db.dbo.EMPLOYEE')
for row in cursor: print(row)
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=User1\User1SQL;'
'Database=sql_db;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM sql_db.dbo.EMPLOYEE')
for row in cursor:
print(row)
##Insert values to SQL server Table from Python:
import pyodbc conn = pyodbc.connect('Driver={SQL Server};' 'Server=User1\User1SQL;' 'Database=sql_db;' 'Trusted_Connection=yes;')
cursor = conn.cursor()cursor.execute('SELECT * FROM sql_db.dbo.EMPLOYEE1')
cursor.execute(''' INSERT INTO sql_db.dbo.EMPLOYEE1 (NAME, AGE, INCOME) VALUES ('Bob',55,85000), ('Jenny',66,86000) ''')conn.commit()
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=User1\User1SQL;'
'Database=sql_db;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM sql_db.dbo.EMPLOYEE1')
cursor.execute('''
INSERT INTO sql_db.dbo.EMPLOYEE1 (NAME, AGE, INCOME)
VALUES
('Bob',55,85000),
('Jenny',66,86000)
''')
conn.commit()
Loading data from SQL Server to Python pandas dataframe
import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=User1\User1SQL;'
'Database=sql_db;'
'Trusted_Connection=yes;')
#query = "SELECT [BusinessEntityID],[FirstName],[LastName],
# [PostalCode],[City] FROM [Sales].[vSalesPerson]"
query = "SELECT * FROM sql_db.dbo.EMPLOYEE1"
df = pd.read_sql(query, conn)
df.head(3)
import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=User1\User1SQL;'
'Database=sql_db;'
'Trusted_Connection=yes;')
#query = "SELECT [BusinessEntityID],[FirstName],[LastName],
# [PostalCode],[City] FROM [Sales].[vSalesPerson]"
query = "SELECT * FROM sql_db.dbo.EMPLOYEE1"
df = pd.read_sql(query, conn)
df.head(3)
3 Random password Generation
import random
# Function to shuffle characters of a string
def shuffle(string):
tempList = list(string) # string to list
random.shuffle(tempList) # Random shuffling list
return ''.join(tempList) # join the random shffled templist to String
char1_uppercase=chr(random.randint(65,90))
char2_lowercase=chr(random.randint(97,122))
char3_special =chr(random.randint(35,38))
char4_lowercase=chr(random.randint(97,122))
char5_lowercase=chr(random.randint(97,122))
char6_lowercase=chr(random.randint(97,122))
char7_lowercase=chr(random.randint(97,122))
char8_lowercase=chr(random.randint(97,122))
password = char1_uppercase + char2_lowercase + char3_special +\ char4_lowercase + char5_lowercase + char6_lowercase + \ char7_lowercase + char8_lowercase
password = shuffle(password)
print("password is :", password)password is : fkmTh#bm
No comments:
Post a Comment