Python learning quick start guide
Python is a great programming language. I am here including all the really required small information and tricks that will be used in our daily coding and debugging.
Python shell/python cmd command`
If you just want to run small code use -c
.
python -c "print('Hello!')"
> Hello!
If you want to include a module then use -m
.
python -m pdb mycode.py
This will include pdb module and run our code file.
And another helpful is -i
this will open python shell after the file execution python -i myCode.py
.
Don’t mutate the list while doing iteration.
list = ["my", "value", "good"]for i in list:
if i == "value":
list.insert(0,'newValue')
print(i)
# This will create a infinite loop#Solutionfor i in list[:]: # will create a copy of the list
if i == "value":
list.insert(0,'newValue')
print(i)
Else block for, for and while loop:
>>> for i in list:... print(i)... else:... print("Else branch for for loop")lokeshji
cat
lokeshji
dog
dog
dogElse branch for for loop>>> for i in list:... print(i)... break... else:... print("Else branch for for loop")lokeshji
Note: if we break
the loop then else block will not execute.
Comparison in python == vs is
So, to recap, let’s try and break down the difference between is and == into two short definitions:
- An is expression evaluates to True if two variables point to the same (identical) object.
==
the expression evaluates to True if the objects referred to by the variables are equal (have the same contents).
Just remember to think of twin cats (dogs should work, too) whenever you need to decide between using is and == in Python. If you do that, you’ll be fine.
To create a string in multiple lines
string = "Hello this is one lonng \
String and goes more \
and more"# Better and alternate way isstring = ("Hello this is one lonng"
"String and goes more"
"and more")
Functions
def fullData(a,fName="lokesh", *args, **kwargs):
print(a, fName, args)
print(kwargs)
Note: for the normal data type like str, tuple, list
==
will check its content and gives the True if content or reference is the same
While is
will only check identity.
For custom class and its objects ==
will return false
class TestCls:
passobj1 = TestCls()
obj2 = TestCls()obj1 == obj2
> False
Truthy and Falsy in Python
def checkIfTruthy(value):... if(value):... print(value, " is Truthy")... else:... print(value, " is Falsy")
For the above function, followings are Falsy
just like JavaScript
- None
- ‘’
- ‘ ‘ #empty string
- 0
- () #Empty tuple
- [ ] #Empty list
- {} #Empty dictionary Note: in JS empty object is truthy
Sorting in Python
sorted
is the function that you need for all the data types. e.g. string, tuple, list
and more iterable.
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order and the
a reverse flag can be set to request the result in descending order.
Regular Expression
import re
re
the module has what we need from the python
import rematch = re.search(patt, string);value = if match: return match.group(); else:
some important modules
There are some important modules that will be needed for development.
- os
- sys #stderr, stdin, stdout, version
- commands # used to run shell commands and get the output, `commands.getstatusoutput(‘ls -l’)`
- shutil # shell commands like cp, mv, mkdir etc…
import os
import sys
import commandsdef list(dir)
cmd = 'ls -l '+dir
(status, output) = commands.getstatusoutput(cmd)
if status:
sys.stderr.write("There is and error"+output)
sys.exit(1) print(output)def main():
list(sys.argv[1])if __name__ == '__main__':
main()
argparse module
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y
if args.quiet:
print(answer)
elif args.verbose:
print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
print("{}^{} == {}".format(args.x, args.y, answer))
output
$ python3 prog.py --help
usage: prog.py [-h] [-v | -q] x y
calculate X to the power of Y
positional arguments:
x the base
y the exponent
optional arguments:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet
For more follow the link.
Dict keys :
anything which is immutable
can be a key to the dict.
myDict = { 'age': 22,
frozenset({3,4}: ...,
otherDict: ...,
__func__: ...,
clsObj: ...}
But immutable can’t be a key e.g.
- set,
- list
can’t be key to the dictionary.
Tricks:
1. chr , ord
chr(95)
> A
ord(A)
> 95
will convert character to integer and vise-Versa
2. create a copy of the list
newArr = arr*1; # this will create new array.
3. check if keyword
import keywordif keyword.iskeyword('elif'):
print("elif is keyword")#print all keywords
print(keyword.kwlist)
4. Print without newline in Python 3.x
#python 2.x
print("without new line "),#python 3.x
print("without new line", end=" ")print(2,3,3,4,4, sep="--", end=" ")
print("on same line")#
> 2--3--3--4--4 on same line
5. print formatting
Python program showing how to use string modulo operator(%) to print fancier output
# print integer and float value
print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))# print integer value
print("Total students : % 3d, Boys : % 2d" %(240, 120))# print octal value
print("% 7.3o"% (25))# print exponential value
print("% 10.3E"% (356.08977))#### fromatting # Python program showing
# use of format() method# using format() method
print('I love {} for "{}!"'.format('Geeks', 'Geeks'))# using format() method and refering
# a position of the object
print('{0} and {1}'.format('Geeks', 'Portal'))print('{1} and {0}'.format('Geeks', 'Portal'))# Python program showing
# a use of format() method# combining positional and keyword arguments
print('Number one portal is {0}, {1}, and {other}.'
.format('Geeks', 'For', other ='Geeks'))# using format() method with number
print("Geeks :{0:2d}, Portal :{1:8.2f}".
format(12, 00.546))# Changing positional argument
print("Second argument: {1:3d}, first one: {0:7.2f}".
format(47.42, 11))print("Geeks: {a:5d}, Portal: {p:8.2f}".
format(a = 453, p = 59.058))# Python program to
# show format () is
# used in dictionarytab = {'geeks': 4127, 'for': 4098, 'geek': 8637678}# using format() in dictionary
print('Geeks: {0[geeks]:d}; For: {0[for]:d}; '
'Geeks: {0[geek]:d}'.format(tab))data = dict(fun ="GeeksForGeeks", adj ="Portal")# using format() in dictionary
print("I love {fun} computer {adj}".format(**data))
print("I love {fun} cumputer {adj}".format_map(data))
6. Reload module
use imp
module to do this.
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
7. isinstance, issubclass, methods
8. method resolution operator mro.
# Mro is used in case of multiple inheritance.
class X: pass
class Y: pass
class Z: passclass A(X,Y): pass
class B(Y,Z): passclass M(B,A,Z): pass# Output:
# [<class ‘__main__.M’>, <class ‘__main__.B’>,
# <class ‘__main__.A’>, <class ‘__main__.X’>,
# <class ‘__main__.Y’>, <class ‘__main__.Z’>,
# <class ‘object’>]print(M.mro())
Variable scoping in python
Python has a variable scoping
pe at function level, not block level. Python has 3 types of scoping globlal,
local
and nonlocal
.
below is the snippet to test all the scoping
x = "global"
def outer():
x = "local"
for i in range(4):
blockVar = 'Function scope'
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
print("variables are function scoped not block", blockVar)
print("Before calling inner:", x)
inner()
print("outer func after calling inner:", x)outer()print("Global x is safe",x)print("---------- end ---------- \n\n")# ---- output
variables are function scoped not block Function scope
Before calling inner: local
inner: nonlocal
outer func after calling inner: nonlocal
Global x is safe global
---------- end ----------
Assert coding style in python
we can use builin
function assert
in python to create a better-styled code. It will be checking for the conditions that we want to avoid
def join_data(l1, l2):
# we want to check if the lists given have data or not
# before making any changes assert len(l1) > 0 , "List one is empty"
#... do the logictry:
join_data([],[22])
expect AssertionError as ae:
print(ae)
else:
# Called on success
finally:
# Called everytime
Copy objects in python
use import copy
it has copy and deepcopy
and names suggest what they do actually.
Pandas data access
We create data frames using pandas
in python. Creating is simple, we are assuming we have load a file using pandas read_csv
function.
Note: we accessing only the column data using square barckets[]
. Note using this we will get the data as series
not the data frame.
To get the data frame we need to use bouble brackets
[[ <col_label> ]]
. To get country
country_df = brics[['country']]
More examples to access the data
In [1]: import pandas as pd
... cars = pd.read_csv('cars.csv', index_col = 0)In [2]: cars
Out[2]:
cars_per_cap country drives_right
US 809 United States True
AUS 731 Australia False
JAP 588 Japan False
IN 18 India False
RU 200 Russia True
MOR 70 Morocco True
EG 45 Egypt TrueIn [3]: #Get the values based on the columnsIn [4]: cars['country']
Out[4]:
US United States
AUS Australia
JAP Japan
IN India
RU Russia
MOR Morocco
EG Egypt
Name: country, dtype: objectIn [5]: # Note type is series type (key based series)In [6]: # to get dataFrame use [[]]In [7]: cars[['country']]
Out[7]:
country
US United States
AUS Australia
JAP Japan
IN India
RU Russia
MOR Morocco
EG EgyptIn [8]: cars[['country', 'cars_per_cap']]
Out[8]:
country cars_per_cap
US United States 809
AUS Australia 731
JAP Japan 588
IN India 18
RU Russia 200
MOR Morocco 70
EG Egypt 45In [9]: cars[1:2]
Out[9]:
cars_per_cap country drives_right
AUS 731 Australia FalseIn [10]: us = cars[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
us = cars[0]
File "<stdin>", line 2685, in __getitem__
return self._getitem_column(key)In [11]: us = cars[0:]In [12]: us #it is all the rows
Out[12]:
cars_per_cap country drives_right
US 809 United States True
AUS 731 Australia False
JAP 588 Japan False
IN 18 India False
RU 200 Russia True
MOR 70 Morocco True
EG 45 Egypt TrueIn [13]: us = cars[0:1]In [14]: us
Out[14]:
cars_per_cap country drives_right
US 809 United States TrueIn [15]: type(us)
Out[15]: pandas.core.frame.DataFrameIn [16]: # Note: using [], [[]] we can get data either by rows or columnsIn [17]: # for better hold data by rows and columns use loc and ilocIn [18]: cars.loc[['US', 'IN'],['country', 'cars_per_cap']]
Out[18]:
country cars_per_cap
US United States 809
IN India 18In [19]: # Note iloc is used for index access instead of keysIn [20]: cars.iloc[[0:2],[1,0]]
File "<stdin>", line 1
cars.iloc[[0:2],[1,0]]
^
SyntaxError: invalid syntaxIn [21]: cars.iloc[[0,2],[1,0]]
Out[21]:
country cars_per_cap
US United States 809
JAP Japan 588In [22]:
Note: dataframe
is tabular data whileSeries
is a one-dimensional labeled array capable of holding any data type (integers, strings, floating-point numbers, Python objects, etc.) The axis labels are collectively referred to as the index.
For filtering we use series
data e.g.
drives_right_data = cars[cars['drives_right']]In [22]: cars[cars['drives_right']]
Out[22]:
cars_per_cap country drives_right
US 809 United States True
RU 200 Russia True
MOR 70 Morocco True
EG 45 Egypt TrueIn [23]: cars[cars['cars_per_cap'] > 100]
Out[23]:
cars_per_cap country drives_right
US 809 United States True
AUS 731 Australia False
JAP 588 Japan False
RU 200 Russia TrueIn [24]: cars[cars['cars_per_cap'] > 500]
Out[24]:
cars_per_cap country drives_right
US 809 United States True
AUS 731 Australia False
JAP 588 Japan False
Learning resources
- https://realpython.com/ It has real-world usage and python tutorials.
- https://www.programiz.com/python-programming/ This has interpreter integrated to the website, that makes it fun to learn.
- https://www.geeksforgeeks.org/check-string-valid-keyword-python/ this has interview related questions and tutorials.
- https://pandas.pydata.org/pandas-docs/stable/getting_started/dsintro.html Data structures for that are used by the pandas.