| Sr. No. | Topic Name |
|---|---|
| 1. | Types of data |
| 2. | Expressions and variables |
| 3. | String, Tuple, List, Dictionary, Set |
| 4. | Loops |
| 5. | Conditional Statements |
| 6. | Functions and scope |
| 7. | Objects and Classes and Dunder Methods |
| 8. | __name__ == __main__ |
| 9. | *args and **kwargs |
| 10. | Try, Except, Else and Finally (Exception handling) |
| 11. | Virtual Enviroment |
| 12. | Iterators, Iterables and Generators |
| 13. | List, Set, Generator and Dictionary Comprehension |
| 14. | Map, Reduce, Filter and Join |
| 15. | Bisect Module |
| 16. | Lambda Function |
| 17. | Enumerate |
| 18. | Formatting of string |
| 19. | ! Property, Decorators, Settters and Getters |
Everything in Python is an Object
Data Types :-
int : Integer Number ;
float : Decimal Number ;
str : String (Collection of characters) ;
bool : True or False value
Typecasting is supported in python. Example: int(2.1) = 2.
boolean = True
Integer = 2
Float = 2.0
String = 'This is String'
print(boolean, Integer, Float, String )
# Typecasting
print('Float To Integer :' ,int(2.1))
print('Float to Integer: ',float(2))
# type() is used to print the class/data-type of variable
print(type(5))
# int('A') will not be typecastedExpression: Statement consists of operators and operands to perform certain operation.
Variables: Used to store data in programming language.
String: Sequence of characters that is denoted under "" or ''. Example: "Name". Immutable(can't change the value of string but can overwrite it) , Ordered Sequence. Stride => [start:stop:jump]
Some Examples of String Methods are :-
- .upper( ) : Convert to uppercase.
- .replace('old_subset','new_subset') : replace the subset of string.
- .find('subset') : returns -1 if not present.
List: Iterable object, ordered sequence, mutable object and denoted by [ ].Example: [1,3,4,2].
Some Examples of List methods are :-
- .extend( )
- .sort()
- .split("delimiter")
del object name can delete any object in python.
Tuple: Immutable, ordered object and denoted by ( ). Example: (1,2,3).
Set: Unordered object, contains unique value and is represented by { }. Example: {1,2,3}.
- .add('')
- .remove('')
- .union(set_name)
Dictionary: Contains keys and values, acts as hash map, keys have to be immutable and unique and values can be mutable. Example: {'a':1,'b':2}
- .keys()
- .values()
- .items()
name in dictionary name will lookup for name in keys
There are three types of loop in python.
- For
- While
Relational Operators : >=, <=, ==, ===, !=; Logical Operators: AND, OR, NOT; Arithmetic Operators: +, - ,/, %, //
if (condition 1):
block of statements
elif (condition 2):
block of statements
else:
block of statementsFunction: Block of statement that have to execute agian and again. Syntax :-
def function_name(parameters):
block of statements
return valueScope: Variables that is used in particular block of statements. if variable is not declared in function then it store the global value of that variable.
Class: Blueprint of Object, and Object: Instance of Class.
Every object has :-
- a type.
- an internal data representation Blueprint.
- set of procedures for interacting with objects Methods.
_A class or types Methods are function that every instance of that class or type provides.
Syntax :-
class_name__dict__ is used to show all the variables and methods in class_name class.
class ClassName: # Parent classes can be multiple or none according to the need.
# Class variable - variable that is used by only this class.
variable_name = value
# Constructor
def __init__(self, instanceVariables):
self.instanceVariable = instanceVariable
# Class Methods - method used by class only.
@classmethod
def class_method_name(cls, value): # used to change value of class variable
cls.variable_name = value
# Static methods - when there is no use of class or instance method
@staticmethod
def static_method_name(parameters):
block of statements
# Inheritance
class ClassName(ParentClass):
def __init__(self,parameters_1, parameters_2):
# if parameters_1 is present in parent class then we can inherit that class.
super().__init__(parameters_1):
self.parameters_2 = parameters_2
# Same methods name can be used to overwrite methods of parent class. First class searches method in present class and after that it searches methods in parent class.
# Magic / Dunder Methods : used for method override and represented "__methodname__".
__add__ : To override addition. Example: (A + B)
__repr__: To cahnge representation of object. Example: repr(object_name)
__str__: To overwrite repr() method. Example: str(object_name)
It is best to use name == 'main' in python coding to run particular section of code from particular package and modules. name is global variable
if __name__ == '__main__':
main()
def main():
block of statements *args: To take number of variables as an argument. Multiple one value pass. type(*args) = tuple
**kwargs: To take two values each time. Multiple Two Value pass. type(**kwargs) = dictionary
We can change names of args and kwargs but not notation.
Exception: only interrupts certain part of program.
Error: interrupts whole executable program.
try, except is used to handle exceptions in python.
Syntax :-
# Exception handling for multiple exceptions
try:
error statement
except error_name as e:
block of statements
except error_name as e:
block of statements
.
.
.
finally: # This will run every time
block of statements
# Exception handling with else
try:
statement
except Exception as e:
print(e)
else:
print("if except block doesn't execute")
finally:
print('This will always execute')To use certain packages in certain project.
All commands here are for windows cmd/powershell.
To install virtualenv :-
pip install virtualenvTo create and activate virtual env :-
virtualenv virtualenv_name
virtualenv_name/scripts/activateTo deactivate virtual env :-
deactivateTo create requirements.txt file to hold all required package name :-
pip freeze>requirements.txtTo create virtual env which have preinstalled system packages :-
virtualenv --system-site-package virtualenv_nameTo delete virtual env :-
del virtualenv_nameTo install packages that are in requirements.txt :-
pip install -r requirements.txt- Iterator : operator used for iteration.
- Iterable : object that can be iterated.
- Iteration: process of iterating elements.
- Generator: takes time but doesn't consume much memory, very useful to create iterable object.
iter()is used to create iterable object.
Python code :-
# Generator
def gernerator_name(parameters):
for i in range(200):
yield i
print(gen(1000))
obj_1 = gen(1000)
obj_1.next() # To yield next item of generator object
List Comprehension
list_object = [ ]
[function for parameters in list_object if condition] Dictionary Comprehension
dict_1 = { }
{function for parameters in list_object if condition}Set Comprehension
set_1 = set()
{function for parameters in list_object if condition} Generator Comprehension
gen = (function for parameters in list_object if condition)
for item in gen:
print(item)- Map: return map object , map each element of sequence to the given function.Syntax: map (function_to_apply, list_of_inputs)
- Reduce: return list object, reduce the number of elements in sequence by applying function to each element of the sequence.Syntax: First import : from functools import reduce then reduce(function_name, list)
- Filter: return filter object, contains elements if the condition is true. We have to typecast the result.Syntax: filter(function_name, list_of_inputs)
- Join: Join each elements in list with some symbol.Syntax: 'symbol'.join(list_of_inputs)
Doesn't sort so sorted list is required. It is used to insert number in the list such that the after insertion list remains sorted. Uses Binary Search.
Syntax:-
import bisect
bisect.bisect(list_of_number, value_to_be_inserted) # tells ehere to insert number
bisect.insort(list_of_number, value_to_be_inserted) # inserts the numberOne Line function also known as anonymous function and generally used when we want to use function onlhy one time.
Syntax:-
variable_name = lambda parameters : statementTo convert to the number. Syntax :-
list1 = [ 'a','b','c' ]
for i,item in enumerate(list_1):
print(i,'->',item) used to format the template for string in python. Example :-
name = 'Algorithm To Live By'
categ = 'non-fiction'
template = 'This is {} book and category of this book is {}'.format(name,categ)
template = 'This is {1} book and category of this book is {0}'.format(name,categ)- Change branch to Python_OOPS_Example
- Open Python_OOPS.py