PYTHON NOTES

 (python notes) - IMPORTANT


##BASICS


print - for print

after print use this ("") to print some thing

if you want to print multi line then use (''' - like this 

                                        you can do - ''')

# - this is for comment

''' - multi line comment - '''


##DATA TYPE

THERE ARE ONLY 5 TYPES OF DATA TYPE


a = "faraz" this is know as string (basically a set of character) there no need of "zxy" u can use 'zxy'

b = 786 this is know as integer (basically a set of number)

c = 78.6 this is know as floating point number (basically a set of numbers with decimal(point))

d = true or false it is know as boolians (basically any valuse is true or false it tells us)       

e = none it is know as none (basically if there is nothing so it is none)    

if you want to use it so you can print it by the command print(a) or print(b) or print(c) or print(d)

AND

if you want to know what is the type of that data variable then - print(type(a))


RULES OF DEFINATING A VERIABEL NAMES

name contain alphabats,digit and underscore

name can only starts with underscore or alphabats

name can't be started with digit (number)

no while space is albwed to be used inside a variable name

variable names are case sensitive for example - a and A are completely different

 

##OPERATORS 

following are the common OPERATORS in python

1. ARITHMETIC OPERATORS -- +,-,*,/,etc.

2. ASSIGNMENT OPERATORS -- =,+=,-=,etc

3. COMPARISON OPERATORS -- ==,>,>=,<,!,etc

4. LOGICAL OPERATORS -- and,or,not 


 for example ARITHMETIC OPERATORS

x = 25

y = 50

z = 35

print(x+y+z)

print(25 + 35)

print(25 - 35)

print(x/y)

print(x*z)

if you want to find he reminder put (%) between the numbers


 for example ASSIGNMENT OPERATORS

x = 25

x += 10

x -= 5

x *=2

print(x)

RESULT = 60

 

 for example COMPARISON OPERATORS

x = (7<4)

print(x)

y = (9<10)

print(y)

z = (10>=12)

# this is take one value < or = if any one is there so it is true otherwise its false

print(z)

a = (7!=7)

# if we put != it means not equal

print(a)

the result will always comes in the form of true or false (boolians)


 for example LOGICAL OPERATORS

x = True

y = False

print("the vale of x and y",(x and y))

# if we use (and) so the result will be false

print("the vale of x and y",(x or y))

# if we use (or) so the result will be true

print("the vale of x and y",(not y))

# if we use (not) so first we only have to put 1(x or y)then result will be the opposite of the value we put


##TYPE CASTING

casts 1. int - integer

      2. str - string

      3. float - floating point number

      4. none - nonetype

      5. bool - boolians

 if you want to change the type cast so write it like this (basically if u change so do it in just next line)

 b = input("enter your name: ")

 b = int(b)

it is basically the changing of the type of - string to integer - but not every time

suppose

a = "350"

a = int(a)

print(a+5)

b = "54hjk"

b = int(b)

print(b+5)

#this one is wrong the cast will not change here


##TYPE FUNCTION

if we want to find the type of the FUNCTION then just -print(type(a))

and then the FUNCTION result show the type.


#STRINGS

if you want to use the single quotes(') on string so u need to use it like this

b = "thunder'blood"

print(b)

OR

a = 'thunder"blood'

print(a)


if you want to add STRINGS then do it like this

message = "good moring "

name = "Ayan" 

print(message+name)


strip function in string

it basically remove the space from yoor input

example-

this = ("        i am ayan        ")

print(this) ---           i am ayan        

print(this.strip()) --- i am ayan



 #STRING SLICING 

this basically the character's(a to z or 0 to 9) number which started from zero.

for example 

a = "faraz"

print(a[0]) ------- f

print(a[4]) ------- z

you can't change the character of string

a[3] = "d" -------- don't work

   the another thing is if you - print(a[0:6]) the complete 'faraz' will be printed

 it means the index count is less then 1 from actual count

 same as upper

   if we - print(a[1:4]) then it will print 'araz' from faraz  

 A = faraz then its length is 5, basically number of character is length

 faraz have length 5 and slicing (0,1,2,3,4) and in negative slicing which start from back(-5,-4,-3,-2,-1)

 negative value is for seeing the last character slicing

if we wana put all at ones then - 

a = faraz

print(a[:])

it means it takes first value as a menimum value if we don't put any value and vise-versa

example

a = faraz

print(a[:4]) --- fara

print(a[1:]) --- araz


 #SLICING WITH SKIPPING value

a = "thunder"

print(a[0:7:2])

then the result will be - tudr

it means it has skipped on value from thunder 


 #STRING FUNCTION

faraz = "i am lightning and the thunder"

print(len(faraz))

result is 30

it means it basically tell the length of the string 

print(faraz.endswith("thunder"))

result is true

it means if we write the story - endswith - that word so it give true or false 

it means it basically give the value in boolians(true or false)


print(faraz.count("a")) ----- 2

this will help us to count that specific word or character


print(faraz.find("and"))

this will help us to find the position of that specific word or character on the string


print(faraz.replace("lightning","ayan")) -- first one is going to replace and secound one will be added

this will help us to replace a word or character 


 #ESCAPE SEQUENCE CHARACTER

sequence of character after backslash'\' -- this one is escape sequence character 


escape sequence character comparises of more than one character but represent one character when

used within the string

example -- \n - for new line

           \t - for tab

           \' - singlequole

           \\ - backslash 

           etc

EXAMPLE

a = "faraz is gamer \nand a developer in cs"

print(a)

if we put '\n' so it will shift words to next line


a = "faraz is gamer \tand a developer in cs"

print(a)

if we put '\t' so it will make a tab between words

IMPORTANT - '\t' only works with '\n'

a = "faraz is gamer \\and a developer in cs"

print(a)

if we put '\\' so it will only put 'one \' in the line

same happens to "\'"


##LIST AND TUPLES

python lists are containers to store a set of values of any type

  EXAMPLE

friends = ["shazil","akku bhaiya","talib","azlan","rihan","ashick","vivek",8,true]

          ([]) can stor values like string,integer,boolians and floating point numbers. as show's in example.

IMPORTANT - here index also started from zero same as slicing.  

  EXAMPLE

if you want to replace any value from list so you can do it like this

a = [1,2,3,4,5]

a[0] = 5

print(a) --- [5,2,3,4,5]


 #LIST SLICING

friends = ["shazil","akku bhaiya","talib","azlan","rihan","ashick","vivek",8] 

print(friends[0:5])

the result will be the -- shazil,akku bhaiya,talib,azlan,rihan

it means it is similar to string slicing i.e it will print starting 4 valuse


 #LIST METHODS

 METHODS ARE ---


Python List - index()

returns the index of the element in the list


Python List - insert()

insert an element to the list (you can use it only one time)

l1 = [1,2,3,5,6,4,15,11,21,7]

l1.insert(0,511) -- [511, 1, 2, 3, 5, 6, 4, 15, 11, 21, 7]

li.insert(4,511) -- [1, 2, 3, 5, 511, 6, 4, 15, 11, 21, 7]

print(l1)


Python List - pop()

Removes element at the given index (it basically pop out the that slice of the list)

l1 = [1,2,3,5,6,4,15,11,21,7]

l1.pop(3)

print(l1) -- [1, 2, 3, 6, 4, 15, 11, 21, 7]


Python List - remove()

Removes item from the list (it basically remove that specific number or character from the list)

l1 = [1,2,3,5,6,4,15,11,21,7]

l1.remove(15)

print(l1) -- [1, 2, 3, 5, 6, 4, 11, 21, 7]


Python List - reverse()

reverses the list

example--

l1 = [1,2,3,5,6,4,15,11,21,7]

l1.reverse()

print(l1) -- [7, 21, 11, 15, 4, 6, 5, 3, 2, 1]


Python List - sort()

sorts elements of a list (basically put all the elements in increasing order in list)

example--

l1 = [1,2,3,5,6,4,15,11,21,7]

l1.sort()

print(l1) -- [1, 2, 3, 4, 5, 6, 7, 11, 15, 21]


Python List - append()

Add a single element to the end of the list (we can use it multiple times if we want to put elements to List)

example--

l1 = [1,2,3,5,6,4,15,11,21,7]

l1.append(45)

print(l1) -- [1, 2, 3, 5, 6, 4, 15, 11, 21, 7, 45]


Python List - clear()

Removes all Items from the List


Python List - copy()

returns a shallow copy of the list


Python List - count()

returns count of the element in the list


Python List - extend()

adds iterable elements to the end of the list


NEVER PUT ANY METHODS IN (=) from

example

l1 = [1,2,3,5,6,4,15,11,21,7]

list_sorted = l1.sort()

print(l1) -- none


 #TUPLES

t = (1,2,3,4,5)

print(t)

this is how tuple is printed the difference between tuple and list is, list is change able and tuple is not.

and list write like this (a = [] and tuple like this a = ())

tuple is immuteable (non change able)

t = (1,2,3,4,5)

t[0] = 34 --- error


list is mutable (change able)

t = [1,2,3,4,5]

t[0] = 2 ---- [1,2,2,4,5]


if you want to put single element in tuple

right way -- t1 = (1,)

wrong way -- t1 = (1) 


if u want to make empty tuple --- t1 = ()


 #TUPLE METHODS

t = (1,2,3,4,5,3,3,3)

print(t.count(3)) --- 4

as showen it only count the value which we insert in - () 


t = (1,2,3,4,5,3,3,3)

print(t.index(2)) --- 1

as showen it only tells that the index of the vale we insert in ()


## DICTIONARY AND SETS

dictionary is a collection of key-value pairs

example

key -"bio"

value -"study of living things"


syntex -- 

mydictionary = {

                          "bio": "study of living things",

                          "physics": "study of nature",

                          "chemistry": "study of chemicals"

}

print(mydictionary['physics']) ---- study of nature

print(mydictionary['chemistry']) ---- study of chemicals

this is how we can make a dictionary.


QUITE ADVANCE DICTIONARY


mydictionary = {

                          "bio": "study of living things",

                          "physics": "study of nature",

                          "chemistry": "study of chemicals",

                          "numbers": [1,3,4,5,6,7],

                          1 : 2,

                          "anotherdictionary": {'thunder' : 'faraz',

                                                'lightning' : 'the stricke of electricity from sky clouds'}

}

print(mydictionary['1']) -- we can put a integer as a key and as a value

print(mydictionary['numbers']) -- it also contain integers (numbers) 

print(mydictionary['anotherdictionary'] -- we can put dictionary inside a dictionary

print(mydictionary['anotherdictionary']['thunder']) -- and we can use it like this this is similar to dictionary


 #PROPERTS OF THE DICTIONARY

1. it is unordered(there is no order in list)

2. it is mutable(change able)

example

mydictionary = {

                        "marks" : [12,13,14,15,16,17],

                        "marks2": [1,2,3,4,5,6,7,8]

}

mydictionary['marks2'] = [22,24,25]

print(mydictionary['marks2']) ---- [22, 24, 25]


3. it is indexed (basically by giving we can get valuse)

4. cannot contain duplicate key


 #METHODS OF DICTIONARY

mydictionary = {

                          "bio": "study of living things",

                          "physics": "study of nature",

                          "numbers": [1,3,4,5,6,7]

}

print(mydictionary.keys()) --- dict_keys(['bio', 'physics', 'numbers'])

it tells us about all the keys in a dictionary


print(mydictionary.values()) --- dict_values(['study of living things', 'study of nature', [1, 3, 4, 5, 6, 7], 2])

it tells you about all the values of the dictionary


print(mydictionary.items()) --- dict_items([('bio', 'study of living things'), ('physics', 'study of nature')

basically it tells us about every single keys and values in dictionary

and it is in the form of tuples not in list. otherwise every keys and values are in list in dictionary


UpdateDictionary = {

         "faraz": "gamer",

         "ayan": "faraz"

}

mydictionary.update(UpdateDictionary)

print(mydictionary) -- {'bio': 'study of living things', 'physics': 'study of natue', 'numbers': [1, 3, 4, 5, 6, 7], 1: 2, 'faraz': 'gamer', 'ayan': 'faraz'}

by using update method we can add the new keys and values pairs to dictionary

it also can update the existing value


print(mydictionary.get("bio")) - if you use it so can have same result as down one (right way becouse this keys is present in dictionary)

print(mydictionary["bio"]) -  if you use it so can have same result as up one      (right way becouse this keys is present in dictionary)      

print(mydictionary.get("bio2")) - it don't give error becouse this methods help us to prevent from getting error (wrong way becouse this keys is not present in dictionary to not get any error you can use it if you don't know how to continue)

print(mydictionary["bio2"]) - it give erroe becouse this keys is not present in dictionary           (wrong way becouse this keys is not present in dictionary)


we can know the type of the dictionary by typing - print(type(mydictionary)) - <class 'dict'>

                                                   print(type(mydictionary.keys())) - <class 'dict_keys'>


 #EMPTY DICTIONARY

basically the dictionary which is empty that is called EMPTY DICTIONARY

we can put any values in it

example

dic = {}


##SETS IN PYTHON

set is a collection of a particual category 

example

birds = {"crow","pecock","sparrow","kingfisher"}

this is the example of the set

sets ignore repeating values

birds = {"crow","pecock","sparrow","kingfisher","crow"}

print(birds)

it will ignore last one "crow" and print -- {"crow","pecock","sparrow","kingfisher}

example

a = {"ayan",6,"faraz",6}

print(type(a)) -- <class 'set'>

print(a) -- {'ayan', 6, 'faraz'}


you can not put list and dictionary becouse list and dictionary are not hash able in a set but we can put tuple in a sets


IMPORTANT: this syntex will create an empty dictionary and not an empty set 

a = {}

print(type(a)) --- <class 'dict'>


if you want to make an empty set use blow syntex

b = set() 

print(type(b)) --- <class 'set'>


 #PROPERTS OF SETS

1. sets are unordered --- element's order doesn't matter

2. sets are unindexed --- cannot access element by index

3. there is no way to change items in sets

4. sets cannot contain duplicate value


##SET METHODS

c = set()

c.add(3)

c.add(4)

c.add(6) 

print(c) -- {3, 4, 6}

this is the method by which we can add the value in empty sets


a = {"ayan",6,"faraz",6}

print(len(a)) -- 3

you can count the length of the sets by (len)

here set only considered one 6 that is why result is -- 3


a = {"ayan",6,"faraz",6}

a.remove('faraz')

print(a) -- {'ayan', 6}

this method will remove that content from set 


a = {"ayan",6,"faraz",6}

a.clear()

print(a) --- set()

this method will clear the set make the set empty set


a = {2,3,4,5,6,7,8,9}

print(a.union({11,44,66,1})) : returns a new set with all index from both sets --> {1, 2, 3, 4, 5, 6, 7, 8, 9, 66, 11, 44}


a = {2,3,4,5,6,7,8,9}

print(a.intersection({2,3})) : returns a set which contain only item in both sets --> {2, 3}

but if we put a number out from set(a) then it will give --- set() an empty set


##CONDITIONAL EXPRESSIONS

examples

 sometime we want to play games if we have free time(sunday) 

 sometime we go on a hiking if our parents allows


all these are decisions which depends on a conditions being met

in python programming too, we must be able to execute instrucions on a condition(s) being act 

this is what conditionals are for!


 #IF, ELIF AND ELSE IN PYTHON

if, else and elif statement are a multiway decisions taken by our program due to certain conditions in our code 

example

a = 45

if(a>3):

    print("the value of a greater then 3")

elif(a<66):

    print("the value of a is smaller then 66")    

elif(a>43):

    print("the value of a greater the 43")

else:

    print("the value is not greater than 3 or 7") 

result --- the value of a greater then 3


this complete code is called (if - elif - else leader)

and there will here only one will will exicute. it can be - if , elif , else  

you can put multiples elif between - if and elif.

you have to leave 4 space gape as i have given for indentation(to show next line is inside if or elif)


becouse the value of (if) is true, it stop in (if) but if it is false then it will take next value

example

a = 45

if(a>46):

    print("the value of a greater then 46")

elif(a<66):

    print("the value of a is smaller then 66")    

elif(a>43):

    print("the value of a greater the 43")

else:

    print("the value is not greater than 3 or 7") 

result --- the value of a smaller then 66


 #RELATIONAL OPERATORS

relational operators are used to evalute conditions inside the if statement. some example of relational operators are:

     ==  ----- equal (if we want to make it equal we have to put (==))

     >=  ----- greater then/equals to

     <=  ----- smaller then/equals to

     etc

 #LOGICAL OPERATORS

in python LOGICAL operators, operate on candition statement.

example.

and --- true if both operators are true otherwise false

example

age = int(input("enter your age"))

if(age>22 and age<60):

    print("you can works with us")

else:

    print("you cannot work with us")

or --- true if at least one  operators is true otherwise false

not --- invert's true to false and false to true

is --- is the value is same then it will give yes(true)

in --- if that value is present in the list or anywhere else so it will give yes(true) otherwise no(false)



## IMPORTANT

1. there can be any number of elif statement

2. last else is executed only if all the condition inside elifs fail.

3. if you want to leave any line for now and come back to write again so just type (- pass -)

example

if(s<999999999):

    pass

else:

    pass

it will not give us error


##LOOPS IN PYTHON

sometimes we want to repeats a set of statement in our program for instance : print 1 to 1000


loops make it easy for a programmer to tell the computer, which set of instructions to repeats and how !

if the loop is never ending loop so it is called infinit loop

 #types of loops in python

primarily there are two types of loops in python 

1. while loop -- it will continously exicuteing if the conditions are true, if anywhere condition is false then the loops is break and program stop running

                  if the condition is false then loop will not run

example

i = 0

while i<10:

    print("thunder"+str( i ) )

    i = i+1

result --thunder0

         thunder1

         thunder2

         thunder3

         thunder4

         thunder5

         thunder6

         thunder7

         thunder8

         thunder9

2. for loop -- this loop is used to itrate though a sequence like list, tuple or string[itrables]

this is for loops looks like :

l = [1,2,3,4,7,8]

for item in l:

    print(item)  -- 1

                    2

                    3

                    4

                    7

                    8

##RANGE FUNCTION IN PYTHON

the range function in python is used to generate a sequence of numbers

we can also specify the start,stop and step-size as follows: 

range (start,stop,step-size)

step-size = if we want to give a gape so we can do it with the help of step-size

example:

for i in range(2,8,2):

    print(i) -- 2

                4

                6

how to use a for loop :

for i in range(8):

    print(i) -- 0

                1

                2

                3

                4

                5

                6

                7

it will not print 8, if we put any number in range value


if we do like this in range we can start from any number

for i in range(2,8):

    print(i) -- 2

                3

                4

                5

                6

                7                

##FOR LOOP WITH ELSE

an optional else can be used with a for loop if the code is to be exicuterd when when the loop exicuter

example:

for i in range(10):

    print(i) 

else:

    print("when the statement is become false then ELSE will be exicuted")for i in range(10):

result -- 0

          1

          2

          3

          4

          5

          6

          7

          8

          9

          when the statement is false then ELSE will be exicuted

#THE BREAK STATEMENT 

'break' is used to come out of the loop when encountered it instructs the program in - exit the loop now

basically it break the loop in any part where we want to stop it

example:

for i in range(10):

    print(i)

    if i == 5:

        break -- 0

                 1

                 2

                 3

                 4

                 5

#CONTINUE STATEMENT

continue is used to stop the current itration of the loop and continue with the next one it instructs the program to "skip the itration

example:

for i in range(10):

    if i == 5:

        continue

    print(i) -- 0

                1

                2

                3

                4

                6

                7

                8

                9

basically it skip that specific value as showen in example


#PASS

we can use the pass statement in loops same as if,elif and else leader

example:

i = 5

while i>0:

    pass

print("i am ayan")

remove - nothing


##FUNCTION AND RECURSIONS

a fuction is a group of statement performing a specific task 

when a program get bigger in size and its somplexcity grows , it gets difficult for a programmer to keep track on which piece of code is doing what!

a function can be reused by the programmer in a given program any number of times

example and syntex of a function:

def function():

    print("hello")

    

    #example


def percent(marks):

    p = ((marks[0] + marks[1] + marks[2] + marks[3])/400)*100

    return p

marks1 = [90,80,85,95]

percentage1 = percent(marks1)


marks2 = [80,60,70,76]

percentage2 = percent(marks2)

print(percentage1, percentage2) -- 87.5 71.5


                 or 


def percent(marks):

    return ((marks[0] + marks[1] + marks[2] + marks[3])/400)*100

    

marks1 = [90,80,85,95]

percentage1 = percent(marks1)


marks2 = [80,60,70,76]

percentage2 = percent(marks2)

print(percentage1, percentage2) -- 87.5 71.5


basically if we write program one time then we use it many times as we want.


#FUNCTION CALL

whenever we want to call a function we put the name of the function folloed by parinthesis as followed

fun1()  -------->this is called function call

#FUNCTION DEFINATION

the part containing the exact set of instructions which are executed during the function call


##TYPES OF FUNCTION IN PYTHON

there are two type of function in python

1. built in functions -------------> already present in python

example 

sum(), len(), print(), range(),etc

2. user defined functions ---------> defined by the user

example

the function1() we defined is an example of of user defined function


#DEFAULT PERAMETER VALUE

we can have a value as default argument in a function

if we specify name= "stranger" in the line containery def, this value is used when no argument is passed

example

def greetings(name=" thunder "):

    print("good day" + name)


greetings(" ayan ")

greetings() ----- good day ayan 

                  good day thunder


##RECURSIONS

recursion is a function which call itself

it is used to directly use a mathematical formula as a function.

example

factorial(n) = n*factorial(n-1)

this function can be defined as follows:


def factorial(n):

    if n == 0 or n == 1:

        return

    else:

        return n*factorial (n-1) 

this work as follows:

       factorial(4)

       4*factorial(3)

       4*3*factorial(2)

       4*3*2*factorial(1)

       4*3*2*1 (factorial returned)


the programmer need to be extrenely careful while working with recursion to ensure that the function doesn't infinitily keep calling itself.

recursion is sometimes the most directl way to code an alogorithem.


##FILE I/0

the random access memory(RAM) is volatile and its contents are lost once a progarm terminated. in order to prisist the data forever , we use files

a file is data storer in a storage device a python program can talk to the file by reading content from it and writing content to it


#TYPES OF FILES

there are basically two type of files:

1. text file (.txt,.c,.py,etc)

2. binary file (.jpg,.dat,etc)

python has a lot of function for reading , updating and deleting files.


#OPENING A FILE

python has an open() function for opening file. it takes 2 parameters : filename and mode.

example

f = open('file experiment for python.txt','r')            # r = read , w = write and by default it is .r.

data = f.read()

print(data)

f.close              # you must have to close the file. 

we can also specify the number of character in read() function: f.read(2)

example

f = open('file experiment for python.txt','r') 

data = f.read(5)         #basically can put value in () and the that will give me an out come from file of the value we put there. 

print(data)

f.close --------- writi   


#OTHER METHOD TO READ THE FILE

we can also use f.readline() function to read the full line at a time

example

f = open('file experiment for python.txt','r') 

#read first line

data = f.readline()

print(data)

#read secound line

data = f.readline()

print(data)

#read third line

data = f.readline()

print(data)

f.close  ------ writing something random for doing some 


                experiment in python I/O


                more lines


#MODES OF OPENING A FILE

r -- open for reading a file

w -- open for writing a file

a -- open for appending a file  -- 'appending' - in python append means to add something to end of the file

+ -- open for updating a file 


'rb' will open for read in binary mode

'rt' will open for read in text mode


#WRITE FILE IN PYTHON

in order to write a file, we first open it in write or append mode after we use the python's f.write() method to write to teh file!

example

f = open('file experiment for python.txt','w')

f.write("please write this to the file")

f.close   # if you don't make another file for this it will make it by its own and if you use on already existing file so it will erase all the data and write new one data on existing file.

  result - please write this to the file              # this has been writen in that file

 

Now, this time try to add some text on the end of it by using append

example

f = open('file experiment for python.txt','a')

f.write(" something cool")

f.close -------- please write this to the file something cool

# we can run it again and again and it will print it again and again

 

#WITH STATEMENT 

the best way to open and close the file automatically is the with statement.


with open('file experiment for python.txt', 'r') as f:

    a = f.read()

print(a)

# you don't need to write f.close() as it is done automatically and you can use it as write function also.


###OBJECT ORIENTED PROGRAMMING (oops)


solving the problem by creating objects is one of the most popular approaches in programming. this is called object oriented programming

this concept focuses on using reuseability codes.

                    implement DRY principle.           #DRY - don't repeat yourself

it makes our codes easier to use and code looks good and organized.


#CLASS

a class is a blueprint for creating object.

EXAMPLE


[combine info to 

 create a valid  -----> BLANK FORM -> filled by student -> APPLICATION OF THE STUDENT  

 application] 


[combine info to 

 create a valid  -----> CLASS -> object instantiation -> OBJECT

 object]



the syntex of the object looks like this:

class employee :                              [class is writen in pascal case]

      #methods & variables


#DIFFERENCE BETWEEN PASCAL AND CAMEL CASE 

PascalCase 

EmployeeName --> PascalCase                # first letter is capital in pascal case


camelCase

isNumeric, isFloatOrInt --> camelCase           # first letter is small in camel case


#OBJECT

an object is an instantiation of the class. when class is defined, a template (info) is defined.

memory is allocated only after object instantiation.


objects of a given class can invoke the methods available to it without revealing the implacementation details to the user. --> abstraction and encapsulation


abstraction - the user don't need to bother about emplimentation details but if he want he can see.

example - we have camera in our phone so camera have click button so we just have to tap on it to take a photo without knowing what is the logic work behind it.


encapsulation - it is basically, to putting the value of same category in a particular class

example - a player controler, by the help of controler we can move our player so all the objects of controler in class are helping to do it.   


example of object

class RailwayForm:

    fromType = "RailwayForm"

    def printData(self):

        print(f"name is { self.name}")

        print(f"train is { self.train}")

harrysapplication = RailwayForm()

harrysapplication.name = "ayan"

harrysapplication.train = "rajdhani express"

harrysapplication.printData()  --- name is ayan

                                   train is rajdhani express


#MODELLING A PROBLEM IN OOPs 

we identify the following in our problem

Noun --> Class --> Employee

Adjective --> Attributes --> name,age,salary

Verbs --> Methods --> getsalery(),increment()


#CLASS ATTRIBUTES 

an Attributes that belongs to the class rather than a particular object.

example 

class Employee:

    compony = "google"            ---------> [specific to each class]

ayan = Employee()                 ---------> object instantiation

ayan.compony 

Employee.compony = "youtube"       ---------> changing class Attributes 

print(ayan.compony)


#INSTANCE ATTRIBUTES

an Attributes that belong to the instance(object) assuming the class from the previous example:

ayan.name = "ayan"

ayan.salary = "100k"             ----------> adding instance Attributes


NOTE : instance Attributes takes preferance over class Attributes during assigment & retrivel.


ayan.Attributes1 --> 1. is Attributes1 is in object?

                     2. is Attributes1 present in class?

example

class Employee:                     # class not always started from Employee class can start from any number

    company = "google"

    salary = 70000


thunder = Employee()

ayan = Employee()

   # creationg instance attributes salary for both the objects

thunder.salary = 66000

ayan.salary = 70000

print(ayan.salary)

print(thunder.salary) 

   # if we not write a instance attributes so the salary will be printed for both the employees is 70000 it means the program first takes instance attributes.


##'SELF' PARAMETER

self refers to the instance to the class. it is automatically passed with a function call form an object.

harry.getsalary()    -------> here self is harry

                     -------> equivalent to employee.getsalary(harry)         


example

class employee:

    company = "google"

    def getsalary(self):

        print("salary is 100k")

harry = employee()

harry.getsalary() ----------> salary is 100k


              another method to do same program


class employee:

    company = "google"

    def getsalary(self):

        print(f"salary for this employee working in {self.compony} is {self.salary}")

harry = employee()

harry.salary = 100000

harry.getsalary() ----------> salary for this employee working in google is 100000


self is basically belongs to the object we are using for example - ayan , thunder , harry , etc


#STATIC METHOD

sometimes we need a function that doesn't use the self parameters we can define a static method like this:


example


class Employee:

    company = "google"

    def getSalary(self, signature):

        print(f"Salary for this Employee working in {self.company} is {self.salary}\n{signature}")

                                                                  # here front slsah is used (\n) and the value os signature we have to give on harry.getsalary()

    @staticmethod                     # to use staticmethod we need to use it like this @staticmethod

    def greating():

        print("good moarning, sir")

        # now if we use self so staticmethod will give use error 

harry = Employee()

harry.salary = 100000

harry.getSalary("thanks")

harry.greating()  -------- Salary for this Employee working in google is 100000

                           thanks

                           good moarning, sir

# you can use staticmethod unlimited times


### CONSTRUCTOR


__init__() constructor 

__init__() is a special method which is first run as soon as object is created.

__init__() method is also know as constructor.


it takes self argument and can also take further argument.

example


class Employee:

    company = "google"

    def getSalary(self, signature):

        print(f"Salary for this Employee working in {self.company} is {self.salary}\n{signature}")

# the code for constructor is started from here

    def __init__(self, name, salary, subunit):

        self.name = name

        self.salary = salary

        self.subunit = subunit

        print("Employer is created")

    def getdetails(self):

        print(f"the salary of the employeer is {self.salary} and name is {self.name} and subunit is {self.subunit}")

    @staticmethod

    def greating():

        print("good moarning, sir")

ayan = Employee("ayan", 100000, "web")

ayan = Employee() --- this throws an error (TypeError: __init__() missing 3 required positional arguments: 'name', 'salary', and 'subunit')

ayan.getdetails() -------- Employer is created

                           the salary of the employeer is 100000 and name is ayan and subunit is web


# addition example


class calculator:

    def something(self):

        print("your number is ")

    def __init__(self, num):

        self.num = num

    def square(self):

        print(f"the value of {self.num} square is {self.num **2}")   #if we use these **2 you can see the square of that specific number

    def cube(self):   

        print(f"the value of {self.num} cube is {self.num **3}")    #and if we increase the value of that number so it will multiply it as many time we want according to that number

    def underroot(self):

        print(f"the value of {self.num} under root is {self.num **0.5}") #we can find the under root by use **0.5 of any number

a = calculator(2)

a.square() 

b = calculator(2)

b.cube()

c = calculator(16)

c.underroot()

result -- the value of 2 square is 4

          the value of 2 cube is 8

          the value of 16 under root is 4.0


## INHERITANCE AND MORE ON OOPs


Inheritance is a way of creating a new class from an existing class.


example


class Employee:

    company = "amazon"


    def showDetails(self):

        print("this is employer's details")

class programmer(Employee):

    language = "python"

    def getLanguage(self):

        print(f"the language is {self.language}")

def showDetails(self):

    print("this is employer's details")


a = Employee()

a.showDetails()

print(a.company)

p = programmer()

p.getLanguage()

p.showDetails()    # in inheritance the same function or attribute can be in inheritace class so, it will run differently

result -------->> this is employer's details

                  amazon

                  the language is python

                  this is employer's details


we can use the methods and attributes of employee in programmer object.

also, we can overwrite or add new attributes and methods in programming class.


#TYPES OF INHERITANCE

1. single inheritace

2. multiple inheritace

3. multi level inheritace


#1. SINGE INHERITANCE

single inheritance occurs when child class inherit only a single parent class.

               base ----> drived

                

example


class Employee:

    company = "amazon"


    def showDetails(self):

        print("this is employer's details")

class programmer(Employee):

    language = "python"

    def getLanguage(self):

        print(f"the language is {self.language}")

def showDetails(self):

    print("this is employer's details")


a = Employee()

a.showDetails()

print(a.company)

p = programmer()

p.getLanguage()

p.showDetails()    # this is single inheritance


#2. MULTI INHERITANCE

multiple inheritance occours when the child class inherit from more than one class.

              parent1 ----> parent2 ----> child


example


class employee:

    company = "microsoft"


class freelancer:

    working = "fiverr"

    level = 2

    def getinfo(self):

        self.level = self.level + 1

        self.blood = "thunder"

class programmer(employee, freelancer):   # the class we write first get the more power then the other one.

    name = "faraz"                        # example- in this line i have write employee first so employee get more power then the freelancer 

                                          # so if they write same function or object then employee class object will writen , freelancer object not writen.


a = programmer()

a.getinfo()

print(a.blood)

print(a.level)

print(a.name)

print(a.working)

print(a.company)


this is the example of multiple inheritance basically - basically a inheritance which have parent1 and parent2 inheritace is called multiple inheritace.


# MULTI LEVEL INHERITANCE

when a child become a parent for another child class is called multi level inheritace 

                        parent ---> child1 ---> child2


example


class person:

    country = "india"

    def takebreak(self):

        print("i am taking a break for sometime")


class employee(person):

    company = "vivo"

    def getsalary(self):

        print(f"the salary is {self.salary}")

    def takebreak(self):

        print("i am employee so i am luckily taking break")

class programmer(employee):

    company = "fiverr"

    def getsalary(self):

        print(f"no salary to programmer")

p = person()

p.takebreak()

e = employee()

print(e.company)

print(e.country)

pr = programmer()

pr.takebreak()

print(pr.company)

print(pr.country)

result -------- i am taking a break for sometime

                vivo

                india

                i am employee so i am luckily taking break

                fiverr

                india                


this is the example of multI LEVEL inheritance basically - basically a inheritance which have grant parent to parent inheritance and parnet to child is called multi level inheritace.


# SUPER() METHOD

super methods is used to access the method of a super class in drived class.


example 


class person:

    country = "india"

    def takebreak(self):

        print("i am taking a break for sometime")


class employee(person):

    company = "vivo"

    def getsalary(self):

        print(f"the salary is {self.salary}")

    def takebreak(self):

        super().takebreak()

        print("i am employee so i am luckily taking break")


class programmer(employee):

    company = "fiverr"

    def getsalary(self):

        print(f"no salary to programmer")

    def takebreak(self):

        super().takebreak()

        print("i am taking a long break")

p = person()


e = employee()

e.takebreak()

pr = programmer()

pr.takebreak()

result --- i am taking a break for sometime

           i am employee so i am luckily taking break

           i am taking a break for sometime

           i am employee so i am luckily taking break

           i am taking a long break           


basically it run's the its own class (takebreak) and upper class (takebreak)s as shown in example so this is called super class method 




syntex 


 super().__init__()  #this one is for using constructor with super class method 

normal one.-- super().anyfunction()


example


class person:

    country = "india"

    

    def __init__(Self):

        print("initalizing person...\n")

    

    def takebreak(self):

        print("i am taking a break for sometime")


class employee(person):

    company = "vivo"


    def __init__(Self):

        super().__init__()

        print("initalizing employee...\n")

    

    def getsalary(self):

        print(f"the salary is {self.salary}")

    

    def takebreak(self):

        super().takebreak()

        print("i am employee so i am luckily taking break")


class programmer(employee):

    company = "fiverr"

    

    def __init__(Self):

        super().__init__()

        print("initalizing programmer...\n")


    def getsalary(self):

        print(f"no salary to programmer")

    

    def takebreak(self):

        super().takebreak()

        print("i am taking a long break")

p = person()


e = employee()


pr = programmer()

result -initalizing person...


        initalizing person...

        

        initalizing employee...

        

        initalizing person...

        

        initalizing employee...

        

        initalizing programmer...


# CLASS METHOD


a class method is a method which bound to the class and not the opjects of class.

@classmethod decorator is used to create a classmethod


syntex to create the classmethod


@classmethod

def (cls,p1,p2,p3):

   

example


class employee:

    company = "facebook"

    salary = 100

    location = "delhi"

 

    @classmethod        #this thing is called decurator

    def changesalary(cls,sal):

        cls.salary = sal


    # another method

    

    #def changesalary(self,sel):

    #    self.__class__.salary = sel


e = employee()

e.changesalary(455)

print(e.salary)

print(employee.salary)

result -- 100

          455

          455


# @PROPERTY DECORATOR 

consist the following class


example



class employee:

    company = "google"

    salary = 70000

    bonus = 20000


    @property

    def totalsalary(self):

        return self.salary + self.bonus

    @totalsalary.setter

    def totalsalary(self, val):

        self.totalbonus = val - self.salary


a = employee()

print(a.totalsalary)

a.totalsalary = 90000

print(a.salary)

print(a.totalbonus)

result --- 90000

           70000

           20000


if e = employee() is an object of class employee

we can print(e.name) to print hte ename/call name() function

basically it is used to add or subtract the value in the class.

this is a setter value.


@ GETTER AND SETTER 

the method name with @property decorator is called getter method.

we can define a function + @name.setter decorator like below.

 

  @name.setter

  def name(self, value):

      self.ename = value

      #this one is setter 


  class employee:

     @property

     def name(self):

         return self.ename

         #this one is getter


## OPERATORS OVERLOADING IN PYTHON

operators in python can be overloaded using dunder(double underscore) method.

these methods are called when a given operator is used on the objects.


example 


class number:

    def __init__(self, num):

        self.num = num


    def __add__(self, num2):

        print("lets add")

        return self.num + num2.num

    def __mul__(self, num2):

        print("lets multiply")

        return self.num * num2.num

    def __sub__(self, num2):

        print("lets subtract")

        return self.num - num2.num

    def __truediv__(self, num2):

        print("lets divide")

        return self.num / num2.num


n1 = number(4)

n2 = number(6)

sum = n1 + n2

print(sum)

mul = n1 * n2

print(mul)

sub = n1 - n2

print(sub)

truediv = n1 / n2

print(truediv)

result  -----  lets add

               10

               lets multiply

               24

               lets subtract

               -2

               lets divide

               0.6666666666666666


operators in python can be overloaded using the following method.


1. p1 __add__(self, p2) ---- for adding

2. p1 __sub__(self, p2) ---- for subtracting

3. p1 __mul__(self, p2) ---- for multiply

4. p1 __truediv__(self, p2) ---- for deviding


# SOME OTHER OPERATORS

 

1. __str__(self)

2. __len__(self)


example


class number:

    def __init__(self, num):

        self.num = num

     

    def __str__(self):

        return f"decimal number : {self.num}"

    

    def __len__(self):

        return 1


n = number(input("please enter your number :"))

print(n)

print(len(n))

result -- please enter your number :6

          decimal number : 6

          1


########################## ADVANCE PYTHON ##########################


## EXCEPTION HANDLING IN PYTHON

There are many built-in exception which are raised in python when something goes wrong.

exceptions in python can be handled using a try statement. the code that handles exception is written in the except clause.


syntex--


key:

   #code         ----------> code which might throw exception

except exception as e:

    print(f"anything {e}")


when the exceptionis handled, the code flow contains without program interruption.

we can also specify the exception to catch like below:


while(True):

    print("press q to quite :")

    a = input("please enter a number :")

    if a == "q":

        break

    try:

        a = int(a)

        if a>6:

            print("you entered a number greater than 6")

    except Exception as e:

        print(f"your input resulute an error : {e}")


print("thanks for playing this game")


## HANDLING DIFFERENCE EXCEPTION


try:

    a = int(input("Enter a number :"))

    c = 1/a

    print(c)


except ValueError as e:

    print(f"please enter a valid value : {e}")


except ZeroDivisionError as e:

    print("make sure that you are not dividing by 0v")


print("thanks for using the code")

result --- Enter a number :th

                           please enter a valid value : invalid literal for int() with base 10: 'th'

                           thanks for using the code


## RAISING EXCEPTION

we can raise custom exception using the raise keyword in python.


example


def increment(num):

    try:

        return int(num) + 1

    except:

        raise ValueError("this is not good to put string into interger")

a = increment('9778hjhj')

print(a)

result -- a = increment('9778hjhj')

          raise ValueError("this is not good to put string into interger")

          ValueError: this is not good to put string into interger


# TRY WITH ELSE CLOUSE

sometime we used to run a piece of code when try was succesful.


try:

    i = int(input("Enter a number : "))

    c = i/2

except Exception as e:

    print(e)

else:

    print('we were successful')

result -- Enter a number : 6

          we were successful

         

            or when we use some strings 

         

          Enter a number : g65

          invalid literal for int() with base 10: 'g65'

          

## TRY WITH FINALLY

python offer a finally clouse which ensures execution of a piece of code irrespective of the exception.


try:

    i = int(input("Enter a number : "))

    c = i/2

    print(c)

except Exception as e:

    print(e)

finally:

    print("finally we were are done")

print("thanks for using the codes")


basically you can use it if you want to run the program after using (except exception)-> any error occours then also finally works


## if __name__ == '__main__' IN PYTHON


__main__ evoluates to the name of the module in python from where the program is run.

if the module is being run directly from the command line, the __name__ is set to string "__main__"

thus this behaviour is used to check whether the module is run directly or imported to another file.


its examples are in file_main.py and file_main2.py


## GLOBAL KEYWORD

global keyword is used to modify the variable outside of the current scope.


example 


a = 54 #global variable

def fun1():

    global a

    print(f"print statement 1 : {a}")

    a = 8 #local variable if global keyword is not used

    print(f"print statement 2 : {a}")

fun1()

print(f"print statement 3 : {a}")

result -- print statement 1 : 54

          print statement 2 : 8

          print statement 3 : 8


##ENUMERATE FUNCTION IN PYTHON

the enumerate function adds counter to an itrable and returns it.


example


list1 = [3,52.3,False,6.3,"harry"]


#index = 0

#for item in list1:

#     print(item, index)

#     index +=1


for index, item in enumerate(list1):

    print(item, index)


result -- 3 0

          52.3 1

          False 2

          6.3 3

          harry 4


## LIST COMPREHENSIONS

list comprehension is an elegant way to create list based in existing lists.


example


list1 = [1,2,7,9,11,22]

list2 = []

for item in list1:

    if item%2==0:

        list2.append(item)

print(list2)


#shortcut to write the same

list2 = [i for i in list1 if i%2==0]

print(list2) 

result -- [2, 22]

          [2, 22]

this one is list comprehension and we also can do set comprehension and dictionary comprehension.


example


# set comprehension


t = [1,2,34,45,6,7,88,9,9,1,2,34,45,7]

s = {i for i in t}

print(s)

result -- {1, 2, 34, 6, 7, 9, 45, 88}


########################## ADVANCE PYTHON PART 2 ##########################


### VIRTUAL ENVIRONMENT

an virtual environment is same as the system interpretor but is isolated from the other python environmrnt on the system.


## INSTALLATION

to use virtual environment, we write


       pip istall virtualenv  ---> install the package.


we can a new environment using:


        virtualenv myprojectenv  ---> creates a new venv.


the next step after create the virtual environment is to activate it.

we can now use this virtual environment as a seprate python insatallation.


## PIP FREEZE COMMAND 

pip freeze return all the package installed in a given python environment along with the versions.


command is ---- pip freeze > requirments.txt


with the help of this command you can make a new forlder with requirments.txt name and it have all the package installed in a given python environment along with the versions.

and you have write this command on terminal.

we can share this file to other users and they can recreate the same environment using the given below command :


command is ---- pip install -r requeriments.txt


# LAMBDA FUNCTION


functions created using a expression using lambda keyword


syntex:

              lambda argument : expressions--------------> can be used as a normal function


example: 


square = lambda x : x*x

square(6)

print(square)   -------> return 36


sum = lambda a, b, c : a + b + c

sum(1,2,3) 

print(sum)      -------> return 6


         or


func = lambda a: a+5

sum = lambda a, b, c : a + b + c

square = lambda x: x*x


x = 4

print(func(x))

print(square(x))

print(sum(x,1,2))

result --- 9

           16

           7


# JOIN METHOD(STRINGS)


create a string form iterable objects.


l = [" camera","laptop","phone","ipad","hard disk","nvidia graphic 3060 card"]

sentence = "\n ".join(l)

print(type(sentence))

print(sentence)

result -- <class 'str'>

           camera

           laptop

           phone

           ipad

           hard disk

           nvidia graphic 3060 card


it join that particual word which we put in sentence and join it.


# FORMAT METHOD


the same thing you can do with (f"") f string this is just for knowledge.

see in the example


example:


name = "ayan"

blog = "mythundercoding"

a = "this is {} and his blog is {}".format(name,blog)

b = "this is {1} and his blog is {0}".format(name,blog)

print(a, b)

result -- this is ayan and his blog is mythundercoding 

          this is mythundercoding and his blog is ayan


# MAP, FILLER & REDUCE


1. map- applies a function to all the item in an input_list


example


def square(num):

    return num*num


l = [1,2,4,3]

# method 1

l2 =[]

for item in l:

    l2.append(square(item))

print(l2)

#method 2

print(list(map(square,l)))


2. filter- create a list of item for which the function returns true.


example


def greter_than_5(num):

    if num > 5:

        return True

    else:

        return False

g10 = lambda num:num>10

print(list(filter(g10,l)))

l = [1,2,3,4,5,6,7,8,9]

print(list(filter(greter_than_5,l)))


3. reduce- applies a rolling computation to sequenctial pairs of elements.


example


from functools import reduce


sum = lambda a,b: a+b 


l = [1,2,3,4,5]

val = reduce(sum,l)

print(val)


if the function computes sum of two numbers and the list is:

l = [1,2,3,4,5]

so it first as 1+2 ----->3

then 3+3  ----->6

then 6+4 ----->10

then 10+5 ----->15

thats how the value is 15. it means it add value one by one.



Comments

Popular posts from this blog

ReactJs Notes

NextJS Notes

HTML NOTES