The Python Language
Use Django ORM outside django - for normal python DB projects
More to read about python -- tuts
Introduction
Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces. python code written in .py
file.
~/python_exercises/script.py
#! /usr/bin/env python
def add_function(a,b):
c = a + b
print 'Ans is: ', c
if __name__=="__main__":
add_function(2,3)
Running simple python script
$ cd python_exercises
$ python script.py
Ans is: 5
$
Variables and Functions
age = 23 # intege variable
name = 'john' # string varaible
height = 5.10 # float variable
hobbies = {'coding', 'travelling', 'reading'} # set variable
address = { 'address_line': 'Unitech Signature Tower-II, Tower-B'.
'locality': 'Sector-15',
'city': 'Gurgaon',
'state': 'Haryana'
} # dict variable
mlist = [1,2,3,4,5] # list variable
mtuple = (1,2,3,4,5) # tuple variable
isValid = True # bool variable
In python functions are declared using def
keyword. Arguments to the function are passed inside ()
brackets. Multiple arguments are separated using ,
. Default values can be provided for each argument using =
assignment operator shown below.
###########################
# defining functions
# empty function body
def print_square(x):
pass
# function that returns nothing
def print_square(x):
print x * x
# function with defauld arguments
def add_numbers(a=1, b=2):
print a + b
# function with return value
def add_numbers_ret(a, b):
return a + b
###########################
# calling a function
add_numbers_ret(3, 7) # 10
TODOs keyword args **kargs, and *args
Nested functions and decorators
video: Nested functions decorators
Theory for the video: nested function and decorators
Variables types can be found using type()
function
In [1]:
###########################
type(2) # ....................... int
type('5') # ....................... str
type(u'5') # ....................... unicode
type(r'5') # ....................... str
type(3.2) # ....................... float
type([1,2,3]) # .................... list
type({1,2,3}) # .................... set
type((1,2,3)) # .................... tuple
type({'name': 'john', 'age': 35}) # dict
type(None) # ....................... NoneType
type(True) # ....................... bool
def foo(x):
print x
type(foo) # ....................... function
###########################
# check if variable is of particular type
type(2) == int # True
type([2,3,'abc']) == list # True
OR
isinstance(2,int) # True
isinstance([2,3],list) # True
Assigning values to multiple variables
name, age, height = 'john', 23, 5.10
Importing Packages, Modules, Functions
In python a module is a file that contains a collection of related functions.
A package is a collection of modules. Package is generally a folder which contains many *.py
module files and some metadata/ configuration files. eg. __init__.py
In [1]:
###########################
# Different import syntax
from package import module
from package.module import function
from module import function
from module import *
from package import *
from package.module import function as f
Import Example
Create your own modules and packages...
In [1]:
###########################
import math
dir(math)
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh',
'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
help(math.sin)
deg = 60
red = (deg/180.0)* math.pi
print math.sin(red)
###########################
print math.sqrt(9)
3.0
###########################
Here math is a module (a simple math.py file) which contains may mathematics related functions
Importing with from
In [1]:
###########################
from math import *
deg = 60
red = (deg/180.0)* pi
print sin(red)
###########################
print sqrt(9)
3.0
###########################
Importing with form allows us to omit repetitive use of module name
math.pi becomes pi
,math.sin(red) becomes sin(red)
,math.sqrt(9) becomes sqrt(9)
Python data-types
Python Dictionaries dict
phonebook = {
'john' : 9876543210,
'alex' : 9638527410,
'peter' : 9517534810
}
blank_phonebook = {}
blank_phonebook['john'] = 9876543210
blank_phonebook['alex'] = 9638527410
blank_phonebook['peter'] = 9517534810
print blank_phonebook['john'] # 9876543210
# Iterating over dictionaries
for name, number in blank_phonebook.iteritems():
print "Phone number of %s is %d" % (name, number)
# Iterating dict in django template
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
# Removing a value
del phonebook['john']
OR
phonebook.pop('john')
# create dict from two lists - list of keys and list of values
dict(zip(['name', 'age'], ['john', 25])) # {'age': 25, 'name': 'john'}
# get all keys of dict
phonebook.keys() # ['peter', 'john', 'alex']
# get all values of dict
phonebook.values() # [9517534810, 9876543210, 9638527410]
# update dict
phonebook.update({'a': 'abc'}) # {'a': 'abc', 'alex': 9638527410, 'john': 9876543210, 'peter': 9517534810}
# converting string to dict
import json
s = '{"about":"Ideas for development","category":"Community", "id":"123", "name":"Original Ideas"}'
data_dict = json.loads(s)
# converting dict to string
s = json.dumps(data_dict)
# remove all items from dict
phonebook.clear() # inplace operation
phonebook.clear phonebook.has_key phonebook.itervalues phonebook.setdefault phonebook.viewkeys
phonebook.copy phonebook.items phonebook.keys phonebook.update phonebook.viewvalues
phonebook.fromkeys phonebook.iteritems phonebook.pop phonebook.values
phonebook.get phonebook.iterkeys phonebook.popitem phonebook.viewitems
Python Sets set
s.add s.intersection s.remove
s.clear s.intersection_update s.symmetric_difference
s.copy s.isdisjoint s.symmetric_difference_update
s.difference s.issubset s.union
s.difference_update s.issuperset s.update
s.discard s.pop
Python Tuple tuple
t.count t.index
Python Strings str
# assign string to variable
name, st, num_str = 'oLa', 'this Is a cAr', 'abcdefgh'
type(name) # str
# escaping special characters with \
print 'what\'s your name?'
# string concatnation
print "Hi there " + "Ola " + name
# string interpolation - python 2.7+ only
'Result is : {} {} {}'.format('a', 'b', 'c') # 'Result is : a b c'
'Result is : {2} {1} {0}'.format('a', 5, 'c') # 'Result is : c 5 a'
# common string functions
name.upper() # OLA : all caps letters
name.lower() # ola : all lower case letters
name.capitalize() # Ola : Only the first letter of sentence is capital
name.isupper() # False
name.islower() # True
st.title() # This Is A Car : first letter of each word is capital
name.strip() # remove white spaces before and after the string ' abc ' becomes 'abc'
name.lstrip() # remove white spaces before string i.e. ' abc ' becomes 'abc '
name.rstrip() # remove white spaces after string i.e. ' abc ' becomes ' abc'
len(name) # 3 : length of string
st.split(" ") # ['this', 'Is', 'a', 'cAr'] returns list by splitting on space
num_str.index('d') # 3 : index of provided argument in string
num_str.startswith('bc') # False
num_str.startswith('abc') # True
num_str.endswith('gh') # True
# substring check using 'in' operator
sub_string, string = 'smi', 'jogn smith'
sub_string in string # True
# string to int, float conversion
type('5') # str
type(int('5')) # int
type(float('5')) # float
# multiline string ''' or """
multi_str = '''multi
line
string'''
# No implicit conversion between int and string during concatnation - int to str conversion
a, b = 1945, "freedom "
print b + a
TypeError: cannot concatenate 'str' and 'int' objects
print b + str(a) # freedom 1945
print b + repr(a) # freedom 1945 : representation method of object -- defines string representation of the object
# str slicing
a='0123456789'
a[0] # '0' : character at 0th index
a[2] # '2' : character at 2nd index
a[-1] # '9' : character at last index
a[-3] # '7' : character at third last inde
a[2:] # '23456789' : from character at index 2 to end
a[:7] # '0123456' : from start to character at index 6(7-1)
a[2:7] # '23456' : from character at index 2 to index 6 (7-1)
a[2:-3] # '23456' : from character at index 2 to index -4 (-3-1)
a[:] # '0123456789' : complete string
a[::1] # '0123456789' : get every element starting at index 0
a[::2] # '02468' : get every second element starting at index 0
a[::-1] # '9876543210' : reverse the string
# string comparision
name == 'john'
name in ["John", "Rick"]
#command line user input
print "please write your name:"
name = raw_input()
print name
Python Lists list
a=[]
len(a) # 0
a = [1, 2.5, 'three', 1, 2.5, 10] # single list can have different datatype elements
a, b = [54,2,68,120,1,45], [9, 99, 999]
c = a + b # [120, 54, 2, 1, 9, 99, 999] concatnating two lists
a.sort() # [1, 2, 45, 54, 68, 120] inplace sorting
a.reverse() # [120, 68, 54, 45, 2, 1] inplace reverce
a.append(100) # [120, 68, 54, 45, 2, 1, 100]
a.remove(68) # [120, 54, 45, 2, 1, 100] remove specific value from list (68) else raises ValueError
a.pop() # [120, 54, 45, 2, 1] removes last element from list and returns it
a.pop(2) # [120, 54, 2, 1] removes element at index 2 from list and returns it (45)
c.count(999) # 1 returns number of occourances of provided element in a list
c.index(999) # 6 returns index of provided element else raises ValueError
c.insert(3,"new") # [120, 54, 2, 'new', 1, 9, 99, 999] inserted new element at index 3
a, b = [1, 2, 3], ['one', 'two']
a.append(b) # [1, 2, 3, ['one', 'two']] list inside another list
a = [1,2,4,1,2,5,7,8]
set(a) # {1, 2, 4, 5, 7, 8} converting list into set -- duplicate elements are removed
## create dict from two lists - keys list and values list
dict(zip(['name', 'age'], ['john', 25])) # {'age': 25, 'name': 'john'}
# all the rules of slicing that are there in str are equally applicable on lists
a = [0,1,2,4,1,2,5,7,8,9]
a[-1] # 9 : last element of the list
a[2:5] # [2,3,4] : all works same as strings not mentioning everything here
# Python Integer - Float int
float
abs(-10) # 10
abs(-10.2) # 10.2
round(1.234) # 1.0
round(1.2345,2) # 1.23
pow(2,3) # 8
squared = 7 ** 2 # 49
cubed = 2 ** 3 # 8
import math
math.floor(32.8) # 32.0
math.ceil(13.1) # 14.0
math.sqrt(4) #2.0
# int int vs int float division
2/5 # 0
5/2 # 2
2.0/5 # 0.4
2/5.0 # 0.4
2.0/5.0 # 0.4
10.0/3 # 3.3333333333333335
# int int vs int float mod
5 % 2 # 1
9 % 2 # 1
5.0 % 2 # 1.0
# get both division and mod results at a time
divmod(5.0, 3) # (1.0, 2.0)
divmod(5, 3) # (1, 2)
Loops - Control Flow
for
while
: continue
break
if else
: >
<
==
is
!=
not
<=
>=
in
try except
for loop - over list
# for loop
for i in range(10): # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
if i == 3:
continue
# print value of i from 0 to 7 except 3
print i
if i == 7:
break
#######################
# use of range function
range(10): # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1, 10): # [1, 2, 3, 4, 5, 6, 7, 8, 9]
range(5, 10) # [5, 6, 7, 8, 9]
for loop - over dict
# iterate for over dictionaries
phonebook = {
"John" : 9876543210,
"alex" : 9638527410,
"peter" : 9517534810
}
for name, number in phonebook.iteritems():
print "Phone number of %s is %d" % (name, number)
Single line for loops - AKA - List Comprehensions
# EXAMPLE 1. Single line for loop
my_list = [20, 2, 50]
def list_doubler(lst):
doubled = []
for num in lst:
doubled.append(num*2)
return doubled
## above code can be reduced to following
def list_doubler(lst):
doubled = [num * 2 for num in lst]
return doubled
my_doubled_list = list_doubler(my_list)
OR
# EXAMPLE 2. Single line for loop with condition
def long_words(lst):
words = []
for word in lst:
if len(word) > 5:
words.append(word)
return words
def long_words(lst):
return [word for word in lst if len(word) > 5]
long_words(['go', 'Django', 'Python', 'c'])
while loop
#######################
# while loop
count = 0
while True:
print count
count += 1
if count >= 5:
break
#######################
while else and for else loops
# while else and for else loops
count=0
while(count<5):
print count
count +=1
else:
print "count value reached %d" %(count)
# Prints out 1,2,3,4
for i in range(1, 10):
if(i % 5 == 0):
break
print i
else:
print "this is not printed because for loop is terminated because of break but not due to fail in condition"
#######################
if elif else - control flow
# if else
if A>B and C<D and D==E:
pass
elif A>=B or C<=D:
pass
elif not A:
pass
elif name in ["John", "Rick"]:
pass
else:
pass
#######################
TODOs
while
for else
iterator
generator
try except
Classes and Objects
class MyClass:
variable = "blah"
def function(self):
print "This is a message inside the class."
myobject = MyClass()
print myobjectx.variable
myobjecty.variable = "yackity"
myobjectx.function()
Generators
Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.
When an iteration over a set of item starts using the for statement, the generator is run. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.
Here is a simple example of a generator function which returns 7 random integers
import random
def lottery():
# returns 6 numbers between 1 and 40
for i in xrange(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1,15)
for random_number in lottery():
print "And the next number is... {}".format(random_number)
Example also demonstrates how to use ramdom function in python
Code Introspection
Code introspection is the ability to examine classes, functions and keywords to know what they are, what they do and what they know.
Python provides several functions and utilities for code introspection.
help()
dir()
hasattr()
id()
type()
repr()
callable()
issubclass()
isinstance()
__doc__
__name__