Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Prep

The document covers various Python programming concepts including decorators, access modifiers, mutable and immutable objects, escape sequences, string formatting, and data structures like lists, tuples, dictionaries, and sets. It also discusses functions, keyword arguments, lambda functions, OOP principles, exception handling, and magic methods. Overall, it serves as a comprehensive guide to Python programming fundamentals and best practices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Prep

The document covers various Python programming concepts including decorators, access modifiers, mutable and immutable objects, escape sequences, string formatting, and data structures like lists, tuples, dictionaries, and sets. It also discusses functions, keyword arguments, lambda functions, OOP principles, exception handling, and magic methods. Overall, it serves as a comprehensive guide to Python programming fundamentals and best practices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Not understand

Decorators : @function inside the fuction


Method Resolution Order

Access Modifier
_ _ variableName : private –Class properties and methods with private access
modifier can only be accessed within the class where they are defined and cannot
be accessed outside the class. In Python private properties and methods are
declared by adding a prefix with two underscores(‘__’) before their declaration.

_ variableName : protected –Class properties and methods with protected access


modifier can be accessed within the class and from the class that inherits the
protected class. In python, protected members and methods are declared using
single underscore(‘_’) as prefix before their names.

One is public : By default the member variables and methods are public which
means they can be accessed from anywhere outside or inside the class. No public
keyword is required to make the class or methods and properties public.Here is an
example of Public access modifier

Mutable and Immutable


Immutable Objects are of in-built datatypes like int, float, bool, string,
Unicode, and tuple.
With Mutable Datatypes : If you change the value of any particular variable then
all the variable who referring to it get change

Using copy() method we can avoid the issue facing with Mutable object
With copy() method new ID get assing to the variable if we change one variable
thenit will not affect any other one

Escape Sequence (To avoid its special meaning we write ‘/’ 2 times)

\n : print next line


\t : print tab
\u: for unicode
\b : ASCII backspaces
\a : for bell sound depricated
\f : ASCII formfeed (FF) deprecated (will take us to next page of the program)
\r : Carriage Return : Will remove the string and get ‘|’ will be on 1st position
\v : vertical tab : \n + \t deprecated
\ooo : for Octal values \3digit in binary
\xhh : for Hexa \x + “2 hexa digits”
\uxxxx : 16 bit hexa decimal value
\Uxxxxxx : for 32 bit for unicode
String
It store char of string in form of 8 bit

If you want the string to print exact what we have written then you should write
this in triple quote

Or To print the 3 line of string in only one line then you can use / after ending of
each line
Both will print same output We can use r to print it as raw string

Value get replace with the charater

String

o/p=P

o/p=e In reverse order indexing start from -1,-2,-3 etc

You can do this as well

You can use not in operator like following


day="Sunday"
print("A" not in day)
print("A" not in "A")

String Replacement Field

You can not add interger to string


So we have to convert it first

String interpolation

Need only one % or you can write multiple % for individual variable

Formatting of String
There is not need write anything inside {} if we don’t want to format it

{0:2} //It uses 2 character space and 1st value with right align default one
{1:3} //It uses 3 character space and 2nd value with right align

{0:<2} //It uses 2 character space and 1st value with leftalign
{1:<3} //It uses 3 character space and 2nd value with left align

{0:^2} //It uses 2 character space and 1st value with middle align
{1:^3} //It uses 3 character space and 2nd value with middle align

FString in Python
We can add any variable instead of 22/7

in and not in Python

casefold() method is used to convert string ino lowercase

You can update the program using not in operator as well


Slicing In Python

Step Slicing in Python


Backward Slicing
Precision in Python
Default precision after decimal in python is 15
#Ctrl +d //to copy and paste last line

{0:100} Fill with at least 100 character


< used for left align
0 used here to print 0 on left side only valid for 0
If we use just f then after decimal there is 6 digits after decimal

3.14 //only 2 decimal value should get print


3.14285714 // only 6 decimal value should get print
Tatal 100 character with 2 decimal value
Value can get filled with 0 as well

Precision having more importance than filled with


So it print 3.142857 //not 3 character

Total 100 character and 70 decimal value as python is able to calculate upto 51
digit so remaining 70-51=19 digits are filled with 0

Slicing
Loops
For loops

print(sum([int(val) for val in value])) #will print the sum of all the digits in the string
Else in Loop
If whole for loop get executed then else get executed
If whole loop is not completed and occurred any interruption only break not
contine then else loop will not get executed

Built In Function
Enumerate() Function in Python (To get index and value it same time in
the form of tuple)
List in Python

All slicing concept will work same as lasts


Deletion in List

After every deletion the index value gets changed and the new index is assign
to the variable

Here we have removed all the value greater than 400 and lesser than 200

Iteration Over the list

It takes O(N^2) so using enumerate function is useful


Sorting the List
extend() function to merge the two list

Removing item from the list


list_reference.remove(value) //if value not present it raise ValueError
Appending to the List
list_reference.append(value) //value get added at last of the string
list_reference= list_reference+ [“New Value”]

list1=list2=list3=list4=grocery #is possible because operator precedence is


from right to left

Nested List and Style Guide


Tuple
Tuple is immutable so we can not change its value and represent using ( )
We can not add the new value to tuple
Memory saver and faster execution
Integraty of data should be protected
Any sequency type can be unpacked like list , string,etc

We can create tuple with single string with comma , should be there at last
Dictionary in Python

Dictionary is collection of items which is unordered, changeable and indexed.


keys() return keys
values() return values
items() return keys and values
We can change the values of keys and modify the dictionary

Key can be in String or int as well anything else as well

You can create the Dict using dict constructor but keys should be string and
values can be anything like int or string
len(dict2) #2
To copy you can use copy() method or dict(dict_reference) method
Ex. newdict1=dict(dict2)
Nested Dictionary

formkeys() method is used to assing tuple to keys of the dict


get(key) #will return the value of corresponding key
dictReference.keys() returns the keys in form of list
Sets in Python

len(setReference) #return size of the set


setReference.remove(“Pak”) #If not present raise error
setReference.discard(“Pak”) #If not present did not raise any error
setReference.pop() #Any one get removed in random order
setReference.clear() #clear the set
del setReference # deleted the set
Advance Method
Functions

After completion of function we should have 2 blank line of code

Keyword Arguments
Value are getting passed w.r.t. Value by reference/and in python we dont have
pass by pointer So list[0] value get changed to 0

As we are assigning new value i.e. new memory therefore list can not change its
value

Packed positional Argument *arg (It packed into tuple)


Packed Keyworded Argument **kwargs (it store in dict with key as variable name and
value as key value)
So the sequence of argument should be
Required arguments , optional argument, and then default argument then keyworded
argument

To change the value of default argument we have to pass it with variable name otherwise
is take it as part of optional argument

The variable argument which is not part of argument in function then it should pass at
last and it store as dictionary

Lambda Functions or Syntactical Sugar

Sorting based on value as lamba function is returning the value


Decorators

OOPs

__init__ (self) is act as constructor

Class Variable
We can access class variable using class name but in python we can access same variable
using object, if we change the value using object reference then it act as instance variable for
that particular object

Global Variable (It declared outside the class)

split() method
Join method (Only work with String)
sort() vs sorted()
sort() It modify the existing String
sorted() It sort and returned the String Sorting based on the ASCII value

You can reverse it by passing reverse=True


casefold is for B ,a sorting is B,a because of ASCII value of B=66 and a is 77
If you want to sort by length of the string the pass key=len(str)
If not work with this use function

sorted() It sort and returned the String Sorting based on the ASCII value to avoid this you can
use key=str.casfold as following similarly you can use this for sorted() function as well

reversed() function
reversed function is returning index value as 0,1,2 but value is in reverse order

Exception Handling
Finally block will always execute the code irrespective of the return statement in try block
After execution of finally block it will return value form try block

If the try and finally block having the return statement then it will ignore the return statement
from the try block and execute the return statement from the finally block

Function inside the Function and nonlocal keyword


Comprehension
Dunder or Magic Methods

_ _ init_ _ ( ) Method are special method which influence the value of variable
Its also called as Dunder Method / Instance Method

_ _init_ _ (self) : cree


_ _del_ _ (self) : to del
_ _add_ _ (self,other) : to add
_ _str_ _ (self) : return string object
_ _ repr _ _(self) : return the string representation of variable
_ _eq _ _(self,other) : for comparison

And many others dunder we have

We don’t have overloading we can only override this methods

You might also like