Python
Python
Python
->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]
if num % 5 == 0:
print(num)
break
else:
print("not found")
output:- 25
for i in range(5):
print(vals[i])
output:- 5
8
9
4
6
-> code for copy all values of vals into newArr:-
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:-
for i in range(n):
x=int(input("enter the next value"))
arr.append(x)
print(arr)
for i in range(n):
x=int(input("enter the next value"))
arr.append(x)
print(arr)
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))
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
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]
->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")
->
class Calculator:
num=100 #class variable
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 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:-
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
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#
output:-[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
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
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]
->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