- Introduction
- Online Playgrounds
- Important Links/Resources
- IDE/Editor
- Built-in Functions
- Variables
- Data Types
- Operators
- Math Functions
- Comments
- Escape Sequences
- Formatted Strings
- Strings
- List
- Dictionaries
- Tuple
- Sets
- Falsy Values
- Conditional Logic
- Looping
- Important Keywords
- Important Functions
- Functions
- Walrus Operator
- Scope
- Object Oriented Programming
- Lambda Expressions
- Comprehensions
- Higher Order Functions
- Decorators
- Error Handling
- Generators
- Modules/Packages
- Built-in Modules/Packages
- pip
- pdb
- File I/O
- Regular Expressions
Python is mostly interpreted language. We normally use cpython - Python Implementation in C Language. Python is just a documentation. There are various implementation of Python such as:
- Jython - Java Implementation
- IronPython
- VSCode
- Sublime Text 3
- Spyder
- PyCharm CE
- Jupyter
- print() / print(, )
- input(<help_text>)
- type(<variable/entity>)
- float()
- bool()
- int()
- str()
- bin()
- min()
- max()
- not()
- sum(<operands...>)
- is
- help()
- __doc__
- Variables are written in snake_case in Python.
<variable_name> =
<variable_name>
Data Type | Values | Example |
---|---|---|
int | -in-0-+in | 1, 2, 3 |
float | -in-0-+in | 1.5, 2.75, 3.0 |
bool | True/False | True, False |
str | - | "", '', f'', r'' |
set | - | {1, 2, 3} |
list | - | [1, 2, 3] |
tuple | - | (1,2) |
dict | - | {"a":1, "b":2} |
None | None | - |
Class | - | - |
Specialized Data Types | - | - |
complex | - | - |
Operator | Summary |
---|---|
+ | addition |
- | subtraction |
* | multiplication |
/ | division |
** | power of |
// | integer division |
% | modulus |
Operator | Summary |
---|---|
and | and |
or | or |
not | not |
> / >= | ge / gte |
< / <= | le / lte |
== | equality |
!= | non-equality |
- round()
- abs()
- floor()
- ceil()
# this is a comment in python
"""
this is a comment in python
"""
Escape Sequence | Description |
---|---|
" | Escape quotes |
' | Escape quotes |
\n | new line |
\t | tab |
name="Sandip Bhambre"
f"This is a formatted string {name}"
name="Sandip Bhambre"
"This is a formatted string {}".format(name)
- Strings are immutable
- Strings start at index 0
- start-value | stop-value | step-value
- start-value defaults to zero
- stop-value defaults to string length
- step-value defaults to 1
name="Sandip Bhambre"
name(0:6) # Sandip
- To reverse a string we can simple use
name="Sandip Bhambre"
name(::-1) # erbmahB pidnaS
len(string)
string.upper()
string.lower()
string.capitalize()
string.find(substring)
string.replace(substring, replace_value)
- Lists are mutable
- start-value | stop-value | step-value
- start-value defaults to zero
- stop-value defaults to string length
- step-value defaults to 1
todo_list=[1 2, 3]
to_list(0) # 1
[].insert(index, element)
[].append(element)
[].extend(list)
[].remove(element)
[].clear()
[].pop() / [].pop(index)
len(list)
range(start, stop, step)
[].copy()
[].count(element)
[].index(element)
[].reverse()
[].sort()
[][::-1]
element in list
my_list=[1, 2, 3, 4, 5]
x, y, z = my_list # x=1, y=2, z=3
x, y, z* = my_list # x=1, y=2, z=[3, 4, 5]
- Key-Value pair
- Key can be int, float, str, bool
my_dict = {
"a":1,
"b":2,
"c":3,
}
my_dict['a'] # 1
{}.get(value, fallback)
{}.pop(key)
{}.popitem()
{}.copy()
{}.clear()
{}.items()
{}.values()
{}.keys()
key in dict
update(dict)
my_tuple(1, 2, 3)
().count(element)
().index(element)
len(tuple)
- Unordered collection of unique values
my_set={1, 2, 3, 4, 5}
{}.add(element)
set(list)
list(set)
element in set
len(set)
{}.copy()
{}.clear()
{}.discard(element)
{}.union(set) / set1 | set2
{}.intersection(set) | set1 & set2
{}.difference(set)
{}.difference_update(set)
{}.isdisjoint(set)
{}.issubset(set)
{}.issuperset(set)
- False
- "" / ''
- 0
- None
- []
- {}
- ()
- set()
- range(0)
if condition:
code
elif condition:
code
else:
code
code if condition else code
for element in list/dictionary/set:
code
# or
for key, value in dictionary.items():
code
# or
for key, value in enumerate(list/range/string):
code
while condition:
code
# or
while condition:
code
else:
code
- break
- continue
- pass
- return
- zip function merges multiple iterators and returns tuples
- reduce is part of Python standard library
- we need to import it from functools
- map(function, iterable)
- filter(function, iterable)
- reduce(function, iterable, default_accumulator_value)
- zip(iterables)
def function_name(parameters):
code
function_name(arguments)
- Functions usually have positional arguments where position of arguments is matters.
- Functions ocasionally can have keyword arguments in which arguments are written as
function_name(parameter_name=argument_value)
- Functions also can have default parameters
def function_name(parameter=default_value):
code
-
Function can support infinite number of arguments using *args, **kwargs
- *args returns tuple
- **kwargs returns dictionary
-
Function parameters are prioritize as
- parameters
- *args
- default parameters
- **kwargs
-
global keyword is used to access global variables inside functions
-
nonlocal(Python3) can be used to access global variables inside functions
def function_name(parameter=default_value):
'''
information related to function
'''
code
- Assigns value to a variable as part of larger expression.
- Python supports function scope
- Python scope is prioritize as
- local
- local parent
- global
- built in
- self is current object pointer
- dir(object_name) returns methods and attributes of an object
class ClassName():
def __init__(self, parameters):
self.parameter = parameter
def method(self, parameters):
code
object_name = ClassName(arguments)
object_name.attribute
object_name.method(arguments)
- can vbe defined outside of constructor
- same value for all objects
class_obj_attr = value
ClassName.class_obj_attr
object_name.class_obj_attr
- cls is class pointer which can be used to create objects
@classmethod
def class_method_name(cls, parameters):
code
ClassName.class_method_name(arguments)
object_name.class_method_name(arguments)
@staticmethod
def static_method_name(parameters):
code
ClassName.static_method_name(arguments)
- Python doesn't have a concept of Access Modifiers
- As a python programmer, we agree on method or attribute name started with underscore(_) are considered private
class ClassName():
code
class ClassName2(ClassName):
code
isinstance(object_name, ClassName)
isinstance(ClassName1, ClassName2)
super().__init__(arguments)
- In case of inheritance, if the classes have same method names then which method gets executed is figure out by MRO
- ClassName.mro()
- Are anonymous functions and created to be used only once
lambda parameters: code
- Comprehensions allows us to create list/dictionary/sets based on some conditions
# List Comprehensions
list_name = [ output for item in iterable if condition ]
# Set Comprehensions
set_name = { output for item in iterable if condition }
# Dictionary Comprehensions
dictionary_name = { key:value for key, value in iterable if condition }
dictionary_name = { key:value for key, value in dictionary.items() if condition }
- A function is a higher order function if
- it returns a function
- and/or accepts a function as a parameter
- Decorators are used to supercharge functions
- They wrap another function to change or enhance it
# definition
def decorator_function(input_function):
def wrapper_function(parameters):
input_function(arguments)
return wrapper_function
# or
def decorator_function(input_function):
def wrapper_function(*args, **kwargs):
input_function(*args, **kwargs)
return wrapper_function
# access
@decorator_function
def input_function(parameters):
code
# or
decorator_function(input_function)
- Exception
- IndexError
- KeyError
- TypeError
- UnicodeError
- SyntaxError
- NameError
- ValueError
- ZeroDivisionError
- FloatingPointError
- ImportError
- ModuleNotFoundError
- FileExistsError
- FileNotFoundError
- InterruptedError
- PermissionError
- EOFError
- RuntimeError
- TimeoutError
try:
code
except ExceptionName:
# or
except ExceptionName as variable:
# or
except:
code
else:
code
finally:
code
raise Exception(message)
- Allows us to generate sequence of values over time
- yield keyword is used to pause execution
- next(gen_func) is used to resume execution
def gen_func(parameters):
code
- Modules are simple files which we can import to extend the functionality of a project
- Packages are directories
- Packages are used to group similar modules
- Every package must have an __init__.py file
# Modules import
import module_name
import module_name as new_name
from module_name import function_name
from module_name import *
# Packages import
import packege_name.module_name
from packege_name import module_name
from packege_name.module_name import function_name
from packege_name.module_name import *
- math
- os
- random
- sys
- collections
- datetime
- time
- array
- pdb
- pathlib
- re
pip3 -V
pip3 install package-name
pip3 install package-name==version-number
pip3 list
pip3 install –upgrade package-name
pip3 uninstall package-name
import pdb
pdb.set_trace()
file_obj = open(file_path)
file_obj.read()
file_obj.readline()
file_obj.readlines()
file_obj.seek(char-index)
file_obj.close()
with open(file_path) as file_obj:
<code-block>
open(file_path, mode)
# mode r, r+, a
file_obj.write(text)
re.search(pattern,string,flags)
regex_object = re.compile(pattern)
regex_object.find(string)
regex_object.findall(string)
regex_object.fullmatch(string)
regex_object.match(string, start, end)
r”string” raw string
Symbol | Meaning |
---|---|
\s | whitespace |
\S | non whitespace |
\d | digit |
\D | non digit |
\w | word character |
\W | non word character |