0% found this document useful (0 votes)
53 views

Python Note 2

The document provides examples of various Python concepts related to file handling, functions, decorators, lambda functions, generators, and object-oriented programming. Some key points covered include: - Reading, writing, appending and deleting files using methods like open(), read(), write(), close() etc. - Defining functions, inner functions, and using decorators to modify function behavior. - Using lambda functions and applying them within functions like filter(), map(), reduce(). - Creating generator functions and iterating over generators. - Demonstrating object-oriented programming concepts with a Square class example.

Uploaded by

Coding Knowledge
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Python Note 2

The document provides examples of various Python concepts related to file handling, functions, decorators, lambda functions, generators, and object-oriented programming. Some key points covered include: - Reading, writing, appending and deleting files using methods like open(), read(), write(), close() etc. - Defining functions, inner functions, and using decorators to modify function behavior. - Using lambda functions and applying them within functions like filter(), map(), reduce(). - Creating generator functions and iterating over generators. - Demonstrating object-oriented programming concepts with a Square class example.

Uploaded by

Coding Knowledge
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

pattern

&& star pattern


Example:refer pattern 1 -n
Output :refer pattern 1 -n

&& number pattern


Example:refer pattern 1 -n
Output :refer pattern 1 -n

&& alpabet pattern


Example:refer pattern 1 -n
Output :refer pattern 1 -n

##chr()
example:chr(65)
output:A

&& file handeling


## file.read()
Example:a = open("pattern2.py","r")
print(a.read())
Output:#inverse pyramid
def pattern(n):
k=n*2-2
for i in range(n,0,-1):
for j in range(k,0,-1):
print(end=" ")
k=k+1
for j in range(0,i):
print('*',end=' ')
print('\r')
pattern(7)

##file.read()
example:a = open("pattern2.py","r")
print(a.read(5))
a.close()
Output:# inv

##.read()
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt")
print(a.read())
a.close()
Output:hello world
we love python
we love programming

&&overwrite
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt","w")
a.close()
a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt",)
print(a.read())
a.close()
Output:>>>

##.readline()
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt","r")
print(a.readline())
Output:hello world

##.readlines()
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt","r")
print(a.readlines())
Output:['hello world\n', 'i am sri rajan\n', 'learning python\n', 'thank you']

##loop in readline
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt","r")
for line in a:
print(a.readlines())
a.close
Output:['hello world\n', 'i am sri rajan\n', 'learning python\n', 'thank you']

##.write
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt",'w')
a.write('no man')
a.close
Output:no man (in file)

##append
Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo.txt",'a')
a.write('no man')
a.close
Output:no manno man

## create new file


Example:a = open(r"C:\Users\SRI RAJAN\Documents\demo2.txt",'x')
a.write('no man')
a.close
Output: (file will be created)

## remove of file
Example:import os
os.remove(r"C:\Users\SRI RAJAN\Documents\demo2.txt")
Output: (file will be deleted)

## check if file exit


Example:import os
if os.path.exists('pattern10.py'):
os.remove('pattern10.py')
else:
print('file not exist')
Output:file not exist (if file not exist)
---------------delete the file (if file exit)
##deleting folder
Example:import os
os.rmdir('myfolder')
output:---------------------delete the whole folder

## function -------------(everything is object)


Example:def fun1(name):
return f"hello{name}"
def fun2(somefun):
return somefun('sri')
print(fun2(fun1))
Output:hellosri

Other Example:def fun1(name):


return f" hello {name + 'rajan'}"
def fun2(somefun):
return somefun('sri')
print(fun2(fun1))
Output: hello srirajan

## inner function
Example:def fun():
print('father function')
def fun2():
print('first child')
def fun3():
print('second child')
fun3()
fun2()
fun()
Output:father function
second child
first child

Example2:def fun(n):
def fun1():
return 'firt child'
def fun2():
return 'second child'
if n==1:
return fun1()
else:
return fun2()
a=fun(1)
b=fun(2)
print(a)
print(b)
Output:firt child
second child

DECORATORS IN PYTHON

## wrapper function
Example:def fun1(n):
def some():
print('hello')
n()
print('welcome')
return some
def fun2():
print('man')
ans=fun1(fun2)
ans()
Output:hello
man
welcome

## wrapper function shortcut


Example:def fun1(n):
def some():
print('hello')
n()
print('welcome')
return some
@fun1
def fun2():
print('man')
fun2()
Output:hello
man
welcome

## wrapper function with arguments


Example:def fun1(n):
def some(*a,**b):
print('hello')
n(*a,**b)
print('welcome')
return some
@fun1
def fun2(name):
print(f'{name}')
fun2('sri')
Output:hello
sri
welcome

## wrapper
Example:def fun1(n):
def some(*a,**b):
print('hello')
return some
@fun1
def fun2(name):
print(f'{name}')
fun2('sri')
Output:hello

fancy decorators
## class decorators
Example:

class Square:
def __init__(self,side):
self._side =side
@property
def side(self):
return self._side
@property
def area(self):
return self._side**2
s= Square(4)
print(s.side)
print(s.area)

Output:
4
16

singlton decorator 5:05(read that) & till 5:09

Lambda Function
## lambda
Example:
x=lambda a:a*a
print(x(3))
Output:
9

Example2:
def a(x):
return(lambda y:x+y)
t = a(10)
print(t(4))
b = a(22)
print(b(3))
Output:
14
25

#using lambda within filter(),map(),reduce()


1.. filter !!syntax: filter(function,iterables)
Example:
li=[1,2,3,4,5,6,7]
c = list(filter(lambda b:b%3==0,li))
print(c)
Output:
[3,6]

2.. map !!syntax: map(function,iterables)


Example:
li=[1,2,3,4,5,6,7]
c = list(map(lambda b:b%3!=0,li))
print(c)
Output:
[True, True, False, True, True, False, True]

3.. reduce !!syntax: reduce(function,sequence)


Example:
#reduce function do things in recursive that is add one by one
# 21+20=41
# 41+4=45
# 45+5=50
# 50+10=60
from functools import reduce
a=reduce(lambda a,b:a+b,[21,20,4,5,10])
print(a)
Output:
60

## quadratic equation using lambda


Example:
#quadratic equation
#(a+b)^2
a = lambda x,y:(x+y)**2
print(a(5,2))
Output:
49

## map(), filter(), reduce()


** 1.. map() have funct has parameter and return value
Example:
def new(s):
return s*s
x=map(new,[1,2,3,4,5,6])
print(x)
print(list(x))
Output:
<map object at 0x0000020EC2FD0D90>
[1, 4, 9, 16, 25, 36]

Example2:
def new(s,t):
return s*t
x=map(new,[1,2,3],[4,5,6])
print(x)
print(list(x))
Output:
<map object at 0x000002CF63DB0D90>
[4, 10, 18]

** 2..Filter() to filter the give iterable,list,sets


to test all the elements to be true or false
Example:
def new(s):
if s>3:
return s
x=map(new,[1,2,3,4,5,6])
print(x)
print(list(x))
Output:
<map object at 0x0000019DB9040DF0>
[None, None, None, 4, 5, 6]

** 3..reduce() used to return 1 value do sum one by one


Example:
from functools import reduce
def add(a,b):
return a+b
c=reduce(add,[1,2,3,4,5])
print(c)
Output:
15

## Filter() within map()


Example:
a=map(lambda a:a+5,filter(lambda a:a>2,[1,2,3,4,5]))
print(list(a))
Output:
[8, 9, 10]

## Map() within filter()


Example:
a=filter(lambda a:a>5,map(lambda a:a+1,[1,2,3,4,5,6]))
print(a)
print(list(a))
Output:
<filter object at 0x0000023C12240D90>
[6, 7]

## filter() and map() within reduce()


Example:
from functools import reduce
a=reduce(lambda a,b:a+b,map(lambda a:a+5,filter(lambda a:a>2,[1,2,3,4,5])))
print(a)
Output:
27

Generator function
Example:
def new(dict):
for x,y in dict.items():
yield x,y
a={1:"hi",2:"welcome"}
b=new(a)
print(b)
next(b)
Output:
<generator object new at 0x000001DAE1258BA0>
(1, 'hi')
(2, 'welcome')

Example2:
def new(a):
while a<=5:
a+=1
yield a
b=new(2)
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
Output:
3
4
5
6
error: print(next(b))
StopIteration

Example2:
def new():
n=3
yield n
n=n*n
yield n
c=new()
print(next(c))
print(next(c))
Output:
3
9

Generators with loops


Example:
def new():
n=3
yield n
n=n*n
yield n
yield n*n
yield n*2
b=new()
for a in b:
print(a)
Output:
3
9
81
18

Generator expression
Example:
a=range(1,6)
print("list",end=':')
b=[i+2 for i in a]
print(b)
c=(i+2 for i in a)
print(c)
print(next(c))
for j in c:
print(j)

g=range(1,6)
print("list",end=':')
d=(i+2 for i in g)
print(max(d)) #u also use min but after using one it became empty sequence
Output:
list:[3, 4, 5, 6, 7]
<generator object <genexpr> at 0x000001D7F53A8BA0>
3
4
5
6
7
list:7

fibonacci series using generator


Example:
#fibonacci series using generator in python
def fib():
f,s=0,1
while True:
yield f
f,s=s,f+s
for i in fib():
if i>=50:
break
print(i,end=" ")
Output:0 1 1 2 3 5 8 13 21 34

stream of number
Example:
a=range(100)
b=(x for x in a)
print(b)
for y in b:
print(y,end=" ")
#to create even
c=range(2,100,2)
d=(x for x in c)
print(d)
for y in d:
print(y,end=" ")
output:
<generator object <genexpr> at 0x00000203D5858BA0>
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
<generator object <genexpr> at 0x00000203D58C3900>
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76
78 80 82 84 86 88 90 92 94 96 98

sinwave using generator


Example:
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sb
def s(flip =2):
x = np.linspace(0,14,100)
for i in range(1,5):
plt.plot(x,np.sin(x/i*.5)*(7 -i)*flip)
sb.set()
s()
plt.show()
Output:
see in python saved .. sinwave using python

OOPs concept (object orented programing system)


class and object
Example:see in file
class car

1..inheritance 6:22:50
Example:
see in python saved ..inheritance in python &2
*types of inheritance
1.single -involves one child class and parent class
2.multiple -involves more than one parent
3.multilevel -child class act as a parent class for another child class
4.hierarchical -more than one type of inheritance
Example:
1,2,3,4 ... see in python saved inheritence
*super function -calls a parent method directly
*method overriding - used to change functionality of parent function
Example: see in python saved inheritence
2.. Encapsulation 6:29:00
Example:

3.. Abstraction 6:30:00


Example:see in python saved .. abstract

Exception handling
## self Exception making
Example:
#self exception making
a=10
if a>5:
raise Exception("a not be more than 5,value of a is {} ".format(a))
Output:
Traceback (most recent call last):
File "C:\Users\SRI RAJAN\AppData\Local\Programs\Python\Python39\
demo----------.py", line 4, in <module>
raise Exception("a not be more than 5,value of a is {} ".format(a))
Exception: a not be more than 5,value of a is 10

## Assertion Error Exception


Example:
import sys
assert("linux" in sys.platform),"this code only run in linux"
Output:
Traceback (most recent call last):
File "C:\Users\SRI RAJAN\AppData\Local\Programs\Python\Python39\
demo----------.py", line 2, in <module>
assert("linux" in sys.platform),"this code only run in linux"
AssertionError: this code only run in linux

Example:
import sys
def linuxo():
assert("linux" in sys.platform),"only run in linux"
print('do something')
try:
linuxo()
except :
print("func not executed")
try:
linuxo()
except AssertionError as error:
print(error)
print("func not executed")

Output:
func not executed
only run in linux
func not executed

## try and except and else


Example:
try:
print(hello)
except:
print('error')

try:
print('hello')
except:
print('error')

try:
print('hello')
except:
print('error')
else:
print('the try is correct')
Output:
error
hello
hello
the try is correct
##error by try and except
Example:
try:
print(hello)
except NameError as Na:
print(Na)
Output:
name 'hello' is not defined

##finally clause
Example:
try:
print('hello')
except:
print('error')
else:
print('the try is correct')
finally:
print('print no matter right or wrong')
Output:
hello
the try is correct
print no matter right or wrong

You might also like