Python

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 16

python(youtube lecture notes):-

->print("hello"+"sajal")
output:-hellosajal
->print("hello"+ " "+"sajal")
output:-hello sajal

slicing-
word="supercalifragilisticexpialidocious"
word[0]
output:-s
word[start:end:step]
word[:5]
output:super
word[:]
output:-supercalifragilisticexpialidocious
word[5:]
output:- califragilisticexpialidocious
word[5::2]
output:- clfaiitcxildcos
word[0:5:1]
output:- super
word[-2]
output:- u
word.index("cali")
output:5
word[word.index("cali"):word.index("fragi")]
output:-cali
word[word.index("docious"):]
output:- docious
->L=[0,10,20,40]
L[::-1]
output:-[40,20,10,0]

-> list(range(10))
output:-[0,1,2,3,4,5,6,7,8,9]
-> range(10)
output:-range(0,10)
-> list(range(2,10,2))
output:- [2,4,6,8]
-> d={'navin':'samsung','rahul':'iphone','kiran':'onplus'} // its a dictionary//
->d
output:-{'navin':'samsung','rahul':'iphone','kiran':'onplus'}
->d.keys()
output:- dict_keys(['navin','rahul','kiran'])
->d['rahul']
output:-'iphone'
->d.get('kiran')
output:- 'oneplus'
->a,b=5,6
->a
output:- 5

->a=5
->b=4
->a<8 and b<5
output:- True
math functions:-
->import math
->x=math.sqrt(25)
->x
output:- 5.0
->print(math.floor(2.9))
ouput:- 2
->print(math.ceil(2.2))
output:- 3
->print(math.pow(3,2))
output:- 9.0
->import math as m
->math.sqrt(25)
ouput:- 5.0
->m.sqrt(25)
output:- 5.0

ch=input('enter a char:')
print(ch[0])
output:- enter a char:pqr
p

while loop:-
i=1
while i<=5:
print("sajal")
example: Q. print all numbers 1 to 100 skip the numbers which
divisible by 3 or 5
code:- i=1
a=1
while i<100:
if a%3==0 or a&5==0:
a=a+1
else:
print(a)
a=a+1
i=i+1
for loop:- example-
x=['navin',65,2.5]
for i in x:
print(i)
output:-navin
65
2.5
example:-
for i in range(11,21,1): //range(staring point,end
poitn ,iteration)//
print(i)
output:- values will be printed from 11 to 20
11
12
13
14
15
16 etc.
example:- for i in range(1,21)
if i%5!=0:
print(i)
output:-1
2
3
4
6
7
till 19
-> continue skip the remaining statements
example:-
for i in range(1,101):
if i%2!=0:
pass

else:
print(i)
output:-2
4
6
8
till 100
printing pattern:-

for j in range(4):
print("#",end=" ")
print()

for j in range(4):
print("#",end="")
output:-# # # #
# # # #
2. for in in range(4):
for j in range(4):
print("#",end="")

print()
output:-# # # #
# # # #
# # # #
# # # #
3.
for i in range(1,5):

for j in range(i,5):
print(j,end=" ")

print()
output:-1 2 3 4
2 3 4
3 4
4
4. str1='ABCD'
str2='PQR'
for i in range(4):
print(str1[:i+1]+str2[i:])
output:-APQR
ABQR
ABCR
ABCD
for-else:-
1. nums=[25,15,18,21,26]

for num in nums:

if num % 5 == 0:
print(num)
break
else:
print("not found")
output:- 25

arrays:- from array import *


vals=array('i',[5,8,9,4,6])
print(vals.buffer_info()) // buffer_info gives the size of the
array//
output:-(address of array,5)
-> from array import *
vals=array('i',[5,8,9,4,6])
vals.reverse()
print(vals)
ouput:- array('i',[6,4,9,8,5])

-> from array import *


vals=array('i',[5,8,9,4,6])
print(vals[0])
output:- 5

-> from array import *


vals=array('i',[5,8,9,4,6])

for i in range(5):
print(vals[i])
output:- 5
8
9
4
6
-> code for copy all values of vals into newArr:-

from array import *


vals= array('i',[5,9,8,4,2])
newArr= array(vals.typecode,(a for a in vals))
for e in newArr:
print(e)
output:- 5
9
8
4
2
-> from array import *
vals= array('i',[5,9,8,4,2])
newArr= array(vals.typecode,(a for a in vals))
i=0
while i<len(newArr):
print(newArr[i])
i=i+1
output:- 5
9
8
4
2
-> from array import *
arr=array('i',[])
n=int(input("enter the length of array"))

for i in range(n):
x=int(input("enter the next value"))
arr.append(x)

print(arr)
output:-just an example
array('i',[16,5,4,5,8])
searching in array:-

-> from array import *


arr=array('i',[])
n=int(input("enter the length of array"))

for i in range(n):
x=int(input("enter the next value"))
arr.append(x)
print(arr)

val=int(input("enter the value for search"))


k=0
for e in arr:
if e==val:
print(k)
break
k=k+1
-> method 2 by using function:-
from array import *
arr=array('i',[])
n=int(input("enter the length of array"))

for i in range(n):
x=int(input("enter the next value"))
arr.append(x)
print(arr)

val=int(input("enter the value for search"))


print(arr.index(val))

numpy:- we use numpy if we need 2 d array or we want to perform some scientific


calculations with array.
-> from numpy import *
arr=array([1,2,3,4,5])
print(arr.dtype)
output:-int32
->from numpy import *
arr=array([1,2,3,4,5.0])
print(arr.dtype)
print(arr)
output:-float64
[1.0,2.0,3.0,4.0,5.0]
->from numpy import *
arr=array([1,2,3,4,5],float)
print(arr.dtype)
print(arr)
output:- float64
[1.0,2.0,3.0,4.0,5.0]
->linespace(start,stop,no of parts you want to go)
->from numpy import *
arr=linespace(0,5,6)
print(arr)
output:-[0.0,1.0,2.0,3.0,4.0,5.0]
-> arange(first element,last element,steps)
-> from numpy import *
arr=arange(1,15,2)
print(arr)
output:-[1 3 5 7 9 11 13]
-> from numpy import *
arr=logspace(1,40,5)
print(arr)
output:-[1.0000000e+01 5.6234132e+10 3.162277e+20 1.7787459e+30 1.000000e+40]
-> from numpy import *
arr=logspace(1,40,5)
print('%.2f' %arr[0])
output:- 10.00
-> from numpy import *
arr=zeroes(5)
print(arr)
output:-[0.0 0.0 0.0 0.0 0.0 ]
->from numpy import *
arr=ones(5)
print(arr)
output:-[1.0 1.0 1.0 1.0 1.0]
->from numpy import *
arr=ones(5,int)
print(arr)
output:-[1 1 1 1 1]
-> from numpy import *
arr=array([1,2,3,4,5])
arr=arr+5
print(arr)
output:-[6,7,8,9,10]
-> from numpy import *
arr=array([1,2,3,4,5])
print(min(arr))
output:- 1
copying of array with numpy:-
->from numpy import *
arr=array([2,6,8,1,3])
arr2=arr1.copy()
arr1[1]=7
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))
output:-[2 7 8 1 3 ]
[2 6 8 1 3]
117784112
11748960
-> int_array = array.array('i', [0, 1, 2, 3, 4, 5])
print(int_array[3:]) # array('i', [3, 4, 5])
print(int_array[:2]) # array('i', [0, 1])
print(int_array[1:3]) # array('i', [1, 2])
# negative index slicing
print(int_array[-2:]) # array('i', [4, 5])
print(int_array[:-2]) # array('i', [0, 1, 2, 3])
-> converting aray into list:-

int_array = array.array('i', [0, 1, 2, 3])


print(int_array.tolist()) # [0, 1, 2, 3]
-> dictionaries:-
-> my_dict={'dave':'001','ava':'002','joe':'003'}
print(my_dict)
type(my_dict)
output:-{'dave':'001','ava':'002','joe':'003'}
dict
->new_dict=dict()
print(new_dict)
type(new_dict)
-> new_dict=dict(dave='001',ava='002')
print(new_dict)
output:- {'dave': '001','ava':'002'}
-> nested dictionaries:-
->emp_details={'employee':{'dave':{'ID':'001','salary':'2000','designation':'team
lead'},'Ava':{'ID':'002','salary':'1000','designation':'associate'}}}
print(emp_details)
matrix from numpy:-
->from numpy import *
arr1=array([
[1,2,3]
[4,5,6]
])
print(arr1.shape)
output:-(2,3)
->from numpy import *
arr1=array([
[1,2,3]
[4,5,6]
])
arr2=arr1.flatten()
print(arr2)
output:- [1 2 3 4 5 6]
->reshape(rows,columns)- convert 1d array into 3d array
->from numpy import *
arr1=array([
[1,2,3,6,2,9]
[4,5,6,7,5,3]
])
arr2=arr1.flatten()
arr3=arr2.reshape(3,4)
print(arr3)
->Functions:-
-> def greet():
print("hello")
print("good morning")
greet()
output:-hello
good morning
->def greet():
print("hello")
print("good morning")
def add(x,y):
c=x+y
return c
greet()
result=add(5,4)
print(result)
output:-hello
good morning
9
-> def add_sub(x,y):
c=x+y
d=x-y
return c,d
result1,result2=add_sub(5,4)
print(result1,result2)

Functions arguments in python:-


example:-
def update(lst):

print(id(lst))
lst[1]=25
print(id(lst))
print("x",lst)
lst=[10,20,30]
print(id(lst))
update(lst)
print("lst",lst)
output:- 18171304
18171304
18171304
x [10,25,30]
lst [10,25,30]
example:-
def person(name,age)
print(name)
print(age)

person('sajal',21)
output:- sajal
21
example:-
def person(name,age=18)
print(name)
print(age)

person('sajal',21)
output:- sajal
21
example of arguments:-
def sum(*b)
c=0
for i in b:
c=c+i
print(c)
sum(5,6,34,78)
output:-123
keyword variable length:-
example:-
def person(name,*data)
print(name)
print(data)
person('sajal',21,'jaipur',8547569)
output:-sajal
[21,'jaipur',8547569]
example of multiple double arguments:-
def person(name,**data)
print(name)
print(data)
person('sajal',age=21,city='jaipur',mob=8547569)
output:-sajal
['age':21,'city':'jaipur','mob':8547569]
example:-
def person(name,**data)
print(name)
for i,j in data.items():
print(i,j)
person('sajal',age=21,city='jaipur',mob=8547569)
output:-sajal
age 21
city jaipur
mob 8547569
pass list to a function:-
example:-
def count(lst):

even=0
odd=0
for i in lst:
if i%2==0
even+=1
else:
odd+=1

return even,odd
lst=[20,25,14,19,16,24,28,47,26]
even,odd=count(lst)
print("Even : {} and odd : {}".format(even,odd))

output:-even: 6 and odd: 3

fabonacci series:-
def fib(n):
a=0
b=1

print(a)
print(b)

for i in range(2,n):
c=a+b
a=b
b=c
print(c)
fib(5)
output:-0 1 1 2 3
recursion:- function calling function itself
factorial
def fact(n):
if n==0:
return 1
return n * fact(n-1)
result=fact(5)
print(result)
output:-120
code for square of number:-
def square(a):
return a*a
result=square(5)
print(result)

lambda function:-
f=lambda a,b : a+b
result=f(5,6)
print(result)
output:-11

example:-even numbers from the list


def is_even(n):
return n%2==0
nums=[3,2,6,8,4,6,2,9]
evens=list(filter(is_even,nums))
print(evens)

output:-[2,6,8,4,6,2]

example:-
nums=[3,2,6,8,4,6,2,9]
evens=list(filter(lambda n: n%2==0,nums))
print(evens)
output:-[2,6,8,4,6,2]

example:-

nums=[3,2,6,8,4,6,2,9]
evens=list(filter(lambda n: n%2==0,nums))
doubles=list(map(lambda n : n*2,evens))
print(doubles)
output:-[4,12,16,8,12,4]

-> taking input of array from user:


from array import *
arr=array('i',[])
n=int(input("enter the length of array:"))
for i in range(n):
x=int(input("enter the values"))
arr.append(x)
print(arr)

->searching in python:-
def search(list,n):
i=0

while i<len(list):
if list[i]==n:
return true
i=i+1
return false
list=[5,8,4,6,9,2]
n=9
if search(list,n):
print("found")
else:
print("not found")

->
pos=-1
def search(list,n):
i=0

while i<len(list):
if list[i]==n:
globals()['pos']=i
return true
i=i+1
return false
list=[5,8,4,6,9,2]
n=9
if search(list,n):
print("found")
else:
print("not found")

->dictionaries:-
def relation_to_luke(name):
dict = {
'Darth Vader' : 'father',
'Leia' : 'sister',
'Han' : 'brother in law',
'R2D2' : 'droid'
}
return 'Luke, I am your ' + dict[name] + '.'
method 2:-
def relation_to_luke(name):
family_relations = {'Darth Vader': 'father',
'Leia': 'sister',
'Han':'brother in law',
'R2D2':'droid'}
return 'Luke, I am your {0}.'.format(family_relations[name])
method:-
def relation_to_luke(name):
if name == "Darth Vader":
return "Luke, I am your father."
if name == "Leia":
return "Luke, I am your sister."
if name == "Han":
return "Luke, I am your brother in law."
if name == "R2D2":
return "Luke, I am your droid."
Q.Create a function that takes in a current mood and return a sentence in the
following format: "Today, I am feeling {mood}".
However, if no argument is passed, return "Today, I am feeling neutral".
code:-
def mood_today(mood='neutral'):
return "Today, I am feeling {}".format(mood)

class oops:-
example:-
class Calculator:
num=100

def getData(self):
print("i am now exceuting as method in class")

obj=Calculator() #sytax to create onjects in python


obj.getData()
print(obj.num)
output:-
i am now exceuting as method in class
100

->
class Calculator:
num=100 #class variable

def__init__(self): #this is a method and this is a constructor class


print("i am called automaion") #self is passes as a argument for obj

def getData(self): #this is a method


print("i am now exceuting as method in class")

obj=Calculator() #sytax to create onjects in python


obj.getData()
print(obj.num)
output:-

i am called automaion
i am now exceuting as method in class
100
note:- the number of arguments in obj=calculator() that should be equal in
constructor class
example:

class Calculator:
num=100 #class variable

def__init__(self,a,b): #this is a method and this is a constructor


class
self.firstnumber=a #firstnumber and secondnumber are instance
variables
self.secondnumber=b #instance variables keep on changing for every object
creation
but class variable does not change.

print("i am called automaion")

def getData(self): #this is a method


print("i am now exceuting as method in class")

def Summation(self):
return self.firstnumber+self.secondnumber + calculator.num (or self.num) #
dont call varibales by their names only
obj=Calculator(2,3) #sytax to create onjects in python
obj.getData()
print(obj.Summation())

obj1=Calculator(4,5)
obj1,getData()
print(obj1.Summation())

output:-

i am now exceuting as method in class


105
i am called automaion
i am now exceuting as method in class
109

notes:-
# self keyword is mandatory for calliing variables names into method
#instance and class variabls have whole different purpose
#constructor name should be __init___
#new keyword is not required when you create object

Inheritance-> accquiring properties and pair of class.

=>How to import from first file to second file


->
from firstfilename import Calculator

class childimp1(Calculator) # childimp1 is just a class

num2=200

def __init__(self):
Calculator.__init__(self,2,10)
def getCompleteData(self):
return self.num2+self.num+self.Summation()
obj=childimp1()
print(obj.getCompleteData())

ouput->
105
i am called automatically
I am not executing as method in class
109
I am called automation
412

->python requests:-
GET request:-it is a request used to request the data from the server.
code:-
import requests
r=requests.get("URL") # we will have a response object r#

->printing of negatvie numbers in a list


numbers=[1,2,3,4,5,6,7,8,9,10]
def negative_list(l):
negative=[]
for i in l:
negative.append(-i)
return negative
print(negative_list(numbers))

output:-[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

->DECORATORS:- enhance the functionablity of other functions

def decorator_function(any_function):
def wrapper_function():
print("this is awesome function")
any_function()
return wrapper_function

@decorator_function
def func1():
print("this is function1")
func1()

@decorator_function
def func2():
print("this is function2")
func2()

output:-
this is awesome function
this is function1
this is awesome function
this is function2

->*args this is used to make flexible functions


example:-
def total(a,b):
return a+b
total(2,4,4,6)

output:-it will print error beause of arguments


for compensate this error we use *args operator

def all_total(*args): #here *args is called as a parameter#


total=0
for num in args: #function calling is called as argument#
total +=num
return total
print(all_total(1,2,4,5,6,))
print(type(args))

output:-18
<class tuple>

->def to_power(num,*args):
if args:
return [i**num for i in args]
else:
return "you did nt pass any argument"
nums=[1,2,3]
print(to_power(2,*nums))

output:-[1,4,9]

->def to_power(num,*args):
if args:
return [i**num for i in args]
else:
return "you did nt pass any argument"
nums=[1,2,3]
print(to_power(3,*[2,3]))
output:-[8,27]

->**kwargs arguments:- it gather the information and tae them as a dictionary


def func(**kwargs):
print(kwargs)
func(first_name='sajal',last_name='agarwal')
output:-{'first_name':'sajal','last_name':'agarwal'}

->def func(**kwargs):
for k,v in kwargs.items():
print(f"{k} : {v}")
func(first_name='sajal',last_name='agarwal')
output:-
first_name=sajal
last_name=agarwal

->creating a class:-
class Person:
def __init__(self,first_name,last_name,age)
#instance variable
print("init method called") #this only for check what is happening
self.person_first_name=first_name
self.last_name=last_name
self.age=age
p1=Person('sajal','agarwal',19)
p2=Person('rohit','jain',24)
print(p1.person_first_name)
print(p2.person_first_name)

output:-
init method called
init method called
sajal
rohit

->class Laptop:
def__init__(self,brand,model_name,price):
self.brand=brand
self.name=model_name
self.price=price
self.laptop_name=brand+''+model_name
def apply_discount(self,num)
off_price=(num/100)*self.price
return self.price-off_price
laptop1=Laptop('hp','au114tx',63000)
print(laptop1.laptop_name)
print(laptop1.apply_discount(10))

output:-hp au114tx
56700.0

->instance methods:-
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}"

def is_above_18(self):
return self.age>18
p1=Person('sajal','agarwal',24)
print(p1.full_name())
print(p1.is_above_18())

output:-sajal agarwal
True

->class Circle:
pi=3.14
def__init__(self,radius):
self.radius=radius
def calc_circumference(self):
return 2*Circle.pi*self.radius
c=Circle(4)
c1=Circle(5)
print(c.cal_circumference())
output:-25.12

->
class Laptop:
discout_percent=10
def__init__(self,brand,model_name,price):
self.brand=brand
self.name=model_name
self.price=price
self.laptop_name=brand+''+model_name
def apply_discount(self,num)
off_price=(laptop.discount_percent/100)*self.price
return self.price-off_price

laptop1=Laptop('hp','au114tx',63000)

print(laptop1.apply_discount())

output:-56700.00

You might also like