Skip to content

Basics

Common Methods and Description

Method Description
type(obj) Returns class type of argument
id(obj) Retuens unique id associated with object
dir(class / module) Returns all methods available
sys.path List of locations where python looks for modules to import
abc.__doc__ Print class or method documentation
def function():
"""documentation"""
Documentation about method to show in __doc__ method
map(lambda t: t*2, mylist) Map each item of mylist to lambda function
FALSE,
None,
0,
" ", ( ), [ ], { }
All evelutes to false
len(iterable) Returns length of iterable object
def function(*args, **kwargs):                
print(args)
print(kwargs)

function('math', 'art', name='dev', age=20)

args = positional arguments => ('math', 'art')
kwargs = keyword arguments =>
python -m http.server
# localhost:8000

python -m http.server 7800
# localhost:7800
Run a local test server
python -m pydoc -p 1234
# localhost:1234
Open python documentation on local server
import timeit
timeit.timeit(my_func())
Measure execution time
__bool__():
return False

__len__():
return 0
Only cases when object is considered false if its defines any of these methods, else its always considered true

HWW (How, What, Why)

How else works with for loop?

you may know about "break" keyword.. let say in a loop through a list of numbers, you want to check if it has 5 or not if you find 5, then there is no need to be in the loop, you break it with "break" keyword,

for ex:

x = [3, 4, 5, 6, 7, 8]
for i in x:
if i == 5:
    print("found 5")
    break
else:
print("aligarh")
Output: \"found 5\"

else statement with for look will work if no "break" happens in the loop like in above code "break" will happen, so "aligarh" will not be printed

but in below code "break" will not happen, because there is no 5 in the list, so else statement will run too

x = [3, 4, 6, 7, 8]
for i in x:
if i == 5:
    print("found 5")
    break
else:
print("aligarh")
Output: \"aligarh\"