Python
Index
- Index
- Python Object Types
- Python Data Types In Details
- Python Statements And Syntax
- Python While and For Loops
- Iterators & Comprehension
- Documentation
- Functions
- Scopes
- Function Arguments
- Lambda Functions
- Generator Functions and Expressions
- Decorators
- Module Files
- mod1.py
- Interactive session
- mod1.py
- mod2.py
- Interactive session
- ./dir1/dir2/mod.py
- Interactive Session - Python Object Oriented Programming
- Python Keywords and Symbols
- Tricks
Python Object Types
Python Data Types
| Object Type | Example |
|---|---|
| Numbers | 1.23, 123, 3+4j |
| Strings | “hello, world” |
| Lists | [1, ‘hello’, [‘I’, ‘am’, ‘list’, ‘in’, ‘a’, ‘list’], 4.5] |
| Dictionary | {“key”:”value”, ‘foo’:0, ‘bar’:’drink’} |
| Tuples | (4, ‘hello’, 3.14) |
| Others | set, types, booleans, none |
Numbers, Strings, Tupples are immutable. Means they can’t be changed after creation
Lists and Dictionaries are mutable
Strings
Example: ‘hello, world’, “I am me” etc
len() function gives the length of the string.
1 | str = "Hello, World" |
Individual character can be indexed from a string. Index can be negative. Negative index will return chars backword.
1 | print str[0] |
Slicing
Extract a section of a string in one step. str[m:n] will produce ‘str[m]str[n-1]’. Default value of m is 0 and n is the length of the string.
1 | print str[7:10] # Slice from 7 to 10(non-inclusive) |
General format of slicing is x[i:j:k]. Where k is the step size from i upto j.
k can be negative, in that case slice will occur from i upto j in reverse order. Default value of k is 1.
1 | "12345678"[1:6:2] # From index 1 upto index 6 and step size 2 |
Strings can be concatenated using + sign and repeated using * sign.
1 | foo = "I am little bunny foo foo" |
Every operation we have performed on string can be performed other sequence objects like lists and tupples
Some methods
1 | string = "foo bar" |
ord() function returns ASCII value of a character.
1 | ord('A') |
chr() function converts ASCII value to character.
1 | chr(65) |
\0 or null terminator doesn’t end python strings
1 | s = 'A\0B\0C' |
Multiline strings can be specified using three “ or ‘.
1 | str = """ |
Lists
List object is sequence object. They are mutable.
1 | list = [1, 2.3, 'foo'] # Creating list object |
Type specific operations
- Can hold different types of object
- No fixed size
- Mutable.
1 | list = [1, 'foo'] |
As list is a mutable object there are methods that can change a list object in place.
1 | list = ['heaven', 'and', 'hell'] |
Lists can be nested.
1 | matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
List Comprehensions
List comprehension is a way to build a new list running an expression on each item in a sequence, once at a time.
1 | matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
Dictionary
Dictionaries are used to store value in a key value pair.
- Mutable
- Values are stored in a key value pair
- Stores any type of objects
- Can be nested
1 | band = {'name':'Bangla', 'albums':2} # Creation |
Type Specific Methods:
1 | dic = {'c':1, 'a':2, 'b':3} |
Iterating over a Dictionary:
1 | dic = {'c':1, 'a':2, 'b':3} |
Tuples
Python tuples are list like sequence object. But they are immutable.
1 | T = (1, 2, 3, 4) |
Sets
Collection of unique elements. Supports usual mathematical set operations.
1 | x = set('hello') |
Python Data Types In Details
Numbers
Numeric Display Formats
repr() display numbers as in code. str() Convert numbers into string. oct() converts decimal into octal hex() converts decimal into hexadecimal int(string, base) - converts strings into numbers. float() - Coverts strings into floating point number. bin() - Converts integer to binary
Decimal Object
Fixed precision representation of numbers.
1 | 0.1 + 0.2 - 0.3 |
Strings
Different Forms:
- Single Quotes: ‘he said, “hello”‘
- Double Quotes: “Robin’s book”
- Block of strings: “””string block”””, ‘’’String Block’’’
- Raw strings: r’\thello, world\n’. Take each characters leterally, omits escape
sequences. e.g. r”C:\new\values”. But raw string won’t work for a string ended
with backslash. r”…"; This is invalid. - Byte Strings: b’spam’ (Python 3)
- Unicode strings: u’\u0986\u09AE\u09BE\u09B0’ (in 2.6 only)
In python 3 there are three string types. str is used for unicode text(ASCII and others). bytes is used
for bynary data. bytearray is mutable variant of bytes.
1 | print 'he said, "hello"' # Python 2.6 |
Character Code Conversions
ord('char') convert char into ints ASCII value.chr(value) convert from ASCII to character.eval(str) - convert a string into python executable code.
1 | list = [1, 2, 3] |
String Formating
String Formating Expression
1 | print("%s:%d\t%s:%d" % ("Alice", 40, "Bob", 50)) |
| Type Code | Meaning |
|---|---|
| %s | String |
| %r | Raw string |
| %c | Character |
| %d | Integer |
| %i | Integer |
| %u | Unsigned Integer |
| %o | Octal |
| %x | Hexadecima(lower) |
| %X | Hexadecimal(Upper) |
| %e | Floating point Exponent |
| %E | e, but uppercase |
| %f | Floating point decimal |
| %g | e or f |
| %G | E or f |
| %% | literal % |
General conversion code structure: %[(name)][flags][width][.precision]typecode
Dictionary base string formating: “%(name)s has %(value)d taka” % {‘name’:’ashik’, ‘value’:50}
String Formating Method Calls
1 | 'Distance between {0} and {1} is {2} km'.format('Dhaka', 'Khulna', 279.6) |
String Methods
string.replace('old', 'new') - replce old substring with new substring from string and return new string.
1 | str = "hello, world" |
string.find('substring') - Find the index of the first occurance of the substring from string.
1 | str = 'hello, world' |
list(string) - convert string into list.
1 | str |
string.join(list) - join list items with string.
1 | ''.join(L) # Join list item of L with empty string |
string.split(delimiters) - split string into a list according to specified delimiters. Default delimiter is whitespaces if nothing specified.
1 | str = 'Sing me song you are a singer' |
string.rstrip() - remove whitespaces from the end of the string.string.upper() - Convert all characters into uppercase.string.endswith(substring) - Check if the string ends with specified substring.
Lists
Some basic operations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18len([1, 2, 3]) # Length
3
>>>
[1, 2, 3] + [4, 5, 6] # Concatenation
[1, 2, 3, 4, 5, 6]
>>>
[1, 2] * 3 # Repetition
[1, 2, 1, 2, 1, 2]
>>>
2 in [1, 2, 3] # Membership Check
True
>>>
for i in [1, 2, 3]: # Iteration
print i
1
2
3Indexing, Slicing, Nesting
1
2
3
4
5
6
7
8
9list = [1, 2, 3]
list[0] # Indexing
1
>>>
list[1:3] # Slicing
[2, 3]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Nesting
matrix[0][0]
1Mutability
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20list = [1, 'foo', 2, 'bar']
list[3] = 'baz' # Changing in place using indexing
list
[1, 'foo', 2, 'baz']
list[1:3] = [2, 3] # Changing in place using slicing
list
[1, 2, 3, 'baz']
>>>
del list[0] # Delete one item from list
list
[2, 3, 'baz']
>>>
del list[1:] # Delete a section from list
list
[2]
>>>
list = [1, 2, 3, 4]
list[1:3] = [] # Another way of deleting a section
list
[1, 4]
List Methods
list.append(item)- To append item at the end of the list.list.extend(argList)- Append multiple items at the end of the list at once.list.insert(index, item)- To insert item at index index of the list.list.pop([index])- Remove item from list at index index. If index isn’t specified default is the last item.list.remove(item)- Remove first occurence of the item from the list.list.sort()- Sort List.list.reverse()- Reverse sort the list.
1 | mList = [1, 2] |
Dictionaries
Creation:
1
2
3
4
5
6dic = {'foo':0, 'bar':1, 'baz':2}
dic
{'baz': 2, 'foo': 0, 'bar': 1} # Notice Order Scambled
>>>
dic['foo'] # Fetching value using key
0Some basic operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20dic
{'baz': 2, 'foo': 0, 'bar': 1}
len(dic) # Length
3
>>>
'foo' in dic # Key membership check
True
dic.has_key('bar') # Key membership check
True
dic.keys() # Gives a list of all keys
['baz', 'foo', 'bar']
>>>
dic
{'goo': 3, 'foo': 5, 'bar': 1}
for key in dic.keys(): # Iterating
print dic[key]
3
5
1Mutability
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15dic
{'baz': 2, 'foo': 0, 'bar': 1}
dic['goo'] = 3 # Adding new entry
dic
{'baz': 2, 'goo': 3, 'foo': 0, 'bar': 1}
>>>
>>>
dic['foo'] = 5 # Changing existing entry
dic
{'baz': 2, 'goo': 3, 'foo': 5, 'bar': 1}
>>>
>>>
del dic['baz'] # Deleting an entry
dic
{'goo': 3, 'foo': 5, 'bar': 1}Some methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23dic
{'goo': 3, 'foo': 5, 'bar': 1}
dic.keys() # Returns a list of all keys
['goo', 'foo', 'bar']
>>>
dic.values() # Returns a list of all values
[3, 5, 1]
>>>
dic.items() # Returns a list of tupples of
[('goo', 3), ('foo', 5), ('bar', 1)] # key/value pair
>>>
dic.get('foo') # Fetching
5
>>>
dic2 = {'zoo':10, 'loo':40}
dic.update(dic2) # Exteding multiple items
dic
{'goo': 3, 'bar': 1, 'foo': 5, 'loo': 40, 'zoo': 10}
>>>
dic.pop('zoo') # Deliting item
10
dic
{'goo': 3, 'bar': 1, 'foo': 5, 'loo': 40}
Tuples
Almost all properties are same as list, except tupples are immutable.
1 | t = (0, 1, 2) # Creation |
File
open(path, mode, buffering) function opens a file and returns a file object which can be used to read and write files.
Open modes:
| Mode | Effect |
|---|---|
| r | open file in read mode. Default, if nothing specified. |
| w | Open file in write mode. |
| a | Open file in append mode |
Methods
file.write(str)- write a string to a file.1
2
3outf = open('myfile', 'w') # Creates a file object
outf.write('hello, world\n')
outf.close()file.read()- Reads whole file.1
2
3
4
5
6
7
8fin = open('myfile') # Default read mode
print fin.read()
hello, world!
I am foo.
I am bar.
>>>file.readline()- Returns a line from a file including \n.
1 | fin.seek(0) |
file.readlines()- Returns a list of all lines from a file.
1 | fin = open('myfile') |
file.truncate(bytes)- File will be truncated to specified bytes. All previous data will be lost. Specified byte space will be zero filled.
Some important file operations
- Check if a file/path exists
1 | from os.path import exists |
Python Pickles
Tool to store python object in a file directly with no to-or-from string conversion.
1 | # Storing Object |
Python Shelve
Packed Binary
Boolean Values In Python
Boolean values are two constant objects True and False.
- Non zero numbers are true.
- Non empty objects are true.
Example:
1 | bool(0) |
Python Statements And Syntax
Notes about python statements and syntax
Python statements are ended by new lines. No semicolon is needed.
1
2a = 40 # Statement
x = a + 10 # Another StatementSemicolons can be used to use multiple statements in a single line.
1
a = 40; b = 60; print(a + b)
Brackets (first, second or third) are used to span single statement in multiple
lines.1
2
3
4
5x = (a + b +
c + d)
list = [1, 2, 3,
4, 5, 6]Also
\can be used to span single statement in multiple lines.1
2x = a + b + \
c + dIn python colons are used for compound statements (Statements which have nested
blocks)1
2if x > y:
print("%d is larger" % x)Nested blocks are nested using indentations. Curly braces are not needed.
1
2
3if x > y:
a = x
b = yFor single line block statement can be placed right after colon.
1
if x > y: print(x)
Assignment Statement
- Assignments create object references.
- Names are created when first assigned.
- Names must be assigned before being referenced.
Different types of assignment statement:
1 | spam = 'hello, world' # Basic form |
In case of multiple assignment all the variables point to the same object(same piece of memory)
1 | spam = ham = [1, 2, 3] # spam & ham are pointing to same object |
Concatenation VS In-place assignment:
In case of concatenation must create a new object, copy it in the object on the
left, then copy it on the right. So it is slower. On the other hand in case of
in-place assignment new item is just added at the end of the memory block.
1 | L = [1, 2] |
1 | L = [1, 2] |
Python variable naming convension
Names that begin with single underscore(
_X) are not imported by from module
import * statementNames that begin with two leading and trailing underscore(
__X__) are system
defined and have special meaning to interpreter.Names that begin with two leading underscore(
__X) are localized to enclosing
classesClass names usually starts with uppercase letters.
Module names starts with lowercase letters.
Print Statement
Printing to stdout
see: Python String data type in details
A fun \r(carriage return trick):
1 | while True: |
Printing To A File
Using file argument of the print() function:
1 | print("hello, world", file = open("hello.txt", "w")) |
Using sys.stdout:
1 | import sys |
Taking Inputs
Taking inputs from stdin
Pyhton takes inputs as a string from stdin. In python 3 input("prompt") function is used to take input. In python 2.x raw_input("prompt") is used.
1 | name = input("Enter your name: ") |
Commandline Arguments
1 | from sys inport argv |
Python If Statement
Structure:
1 | if <test1>: |
No switch case in python. Work around with if:
1 | choice = 'gam' |
Dictionary based work around (Less typing!):
1 | choice = 'jam' |
Logical Operators in Python
and operator:
1 | if X and Y: # True if X and Y both True |
Return Value: and didn’t return True or False. Returns first object which is
false(zero or empty) from left to right. If expression is true returns right most
object.
1 | 1 and 2 |
or operator:
1 | if X or Y: # True if X or Y is True |
Return value: or didn’t return True or False. Returns first object which is true
(non-zero / non-empty) from left to right.
1 | 2 or 3 |
not operator:
1 | if not X: # Invert logic |
Return value: Returns True or False
Range:
if 0 <= x <= 10:
DO SOMETHING
1 | rn = 1500 |
if/else Ternary Expression
Consider following code:
1 | if X: |
Ternary Expression:
1 | A = Y if X else Z |
1 | count = 5 |
Python While and For Loops
Python While Loop
While loop’s general format
1 | while <test1>: |
pass: Do nothing. Just an empty statement place holder.
Python For Loop
For loop’s general format
1 | for <target> in <object>/<sequence>: |
- Any sequence works in for loop
1 | for i in [1, 2, 3]: |
Tupple assignment / Sequence Unpacking in for loop
1 | for (a, b) in [(1, 2), (3, 4)]: |
Some sequence unpacking example
1 | for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]: |
Using for loop for iterating through dictionary
1 | dict = {1: 'a', 2: 'b', 3: 'c'} |
Range
range(FROM, UPTO, STEP) - Create a list of numbers FROM to UPTO in python 2.0. In python 3.0 it’s an iterator.
Example:
1 | # Python 2.0 |
Range items can be negative numbers and can be in reverse order.
1 | list(range(8, 0, -1)) |
Range can be used as a iterator in for loops.
1 | X = "abcdefgh" |
Zip
zip(seq1, seq2, ...) takes one or more sequence as argument and creates a list of Tuples from them. zip creates an iterable object. Which can be converted to list or other sequence object.
1 | l = [1, 2, 3] |
zip() truncates if the size of the sequences mismatches.
1 | l = [1, 3, 5, 7] |
zip() can be used to iterate through multiple sequence in for loop.
1 | for x, y, z in zip(l, m, n): |
zip() can be used to construct a dictionary from key and value lists.
1 | key = ["spam", "ham", "egg"] |
Map
Python 2.0: In python 2.0 map() gives similar functionality like zip().
1 | # Python 2.0 |
Python 3.0: In python 3.0 map takes a function and one or more sequence arguments and collects the results of calling the function.
1 | list(map(ord, "spam")) |
Enumerate
enumerate() is used to find the index and value of a sequence. It creates a generator object which is iterable.
1 | # Normal Way |
Iterators & Comprehension
An object is called iterable if it’s a sequence or an object that produce one result at a time.
Any object that supports iteration has __next__() method. It raises StopIteration exception
at the end of the series of results.
File Iterator
1 | # Manual method |
List Comprehension
General Structure: [expression for target1 in iterable1 if condition1 for target2 in iterable 2 if condition2 ...]
List Comprehension:
1 | L = [1, 2, 3] |
Filtering:
1 | L = [x for x in range(0, 11) if x % 2 == 0] |
Evaluating and Filtering:
1 | [x ** 2 for x in range(0, 11) if x % 2 == 0] |
Nested Loops:
1 | [x + y for x in [0, 1, 2] for y in [100, 99, 98]] |
Work with Matrices:
1 | M = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] |
Dictionary and Set comprehension
1 | {key: value for key, value in list(zip("abc", [1, 2, 3]))} |
Documentation
dir() Funtion
Python dir() lists all the methods of an object.
1 | dir(list) |
Docstrings
Docstrings are used for documenting python module, class, class methods,
functions etc. Docstrings are placed as the first statement of the
module, class, methods, functions.
From PEP 257
A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the
__doc__special attribute of that object.
All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the
__init__constructor) should also have docstrings. A package may be documented in the module docstring of the__init__.pyfile in the package directory.
Example:
1 | def add(x, y): |
PyDoc and help()
Python help() function gives the documentation of an object that are
created by docstrings
Functions
Example:
1 | def sum(x, y): |
Function Attributes
Default Argumets:
1 | def func(a, b): |
Custom Argumets:
1 | func.cusarg = 1 |
Function Annotations
1 | def func(a: 'spam' = 0, b: (1, 10) = 1, c: float = 2) -> int: |
Scopes
global keyword
Cross File Changes
Enclosing Functions
1 | x = 10 |
1 | # Supposed to make a list of functions |
Forward Reference
1 | def func1(): |
Factory Functions
1 | def maker(x): |
nonlocal Statement
1 | def tester(state): |
Function Arguments
Avoiding Mutable Argument Changes
1 | L = [1, 2] |
Special Argument Matching Modes
Different types of function call
1 | def func(a, b, c, d): |
Different way of function arguments
1 | ###################################################################### |
Argumet order: func(normal, *tupple, keyword only, **dictionary)
Lambda Functions
General form: lambda arg1, arg2, ...: expression
1 | x = lambda a = 1, b = 2, c = 3: a + b + c |
lambda is an expression not a statement. So it can be used where def can’t. Like inside a list or dictionary.
1 | L = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4] |
Generator Functions and Expressions
1 | def genSeq(N): |
Send:
1 | def gen(n): |
1 | G = (x ** 2 for x in range(10)) |
- Both generator function and expression are their own iterators. So they can have only one active iterator. I multiple iterator is assign, they all will point to same iteration point.
1 | G = (x ** 2 for x in range(10)) |
Decorators
Decorators are used to change any callable objects behaviour like
function or class etc. There are two type of decorators. Function decorator
and class decorator. One is work for function and another is work for
classes. But both work in same way.
Consider this senario where a function func_decorator is changing other
functions behaviour. This function takes other functions as argument and
change is behaviour using a wrapper function. Then this wrapper function is
assigned to the original function to change original functions behaviour.
1 | #!/usr/bin/env python3 |
Output:
1 | Befor using func_decorator: |
We can find the same behaviour by using python decorator:
1 | #!/usr/bin/env python3 |
Output:
1 | Function foo does: |
Module Files
- Module files run only once after the first import
mod1.py
1 | print("hello") |
Interactive session
1 | import mod1 |
- If two module contains same name and both are imported via from. Then namespace will be resolved with the latest from.
mod1.py
1 | def func(): |
mod2.py
1 | def func(): |
Interactive session
1 | from mod1 import func |
- Import module mod which in ./dir1/dir2 location.
./dir1/dir2/mod.py
1 | print("./dir1/dir2/mod.py imported") |
Interactive Session
1 | import dir1.dir2.mod |
Python Object Oriented Programming
OOP Basics
Basic Class Syntax
1 | #!/bin/python |
Constructor
In class a special method __init__() works as a constructor.
1 | #!/bin/python |
Destructor
A special method __del__ works as a destructor.
1 | class Point: |
Output:
1 | Created (2.000000, 3.000000) |
Encapsulation
var- Public variable. Can be accessed from outside of the class._var- Protected variable. Can be accessed from outside of the class
but it should be accessed only from the sub class.__var- Private variable. Can be accessed only within the class.
Getter and Setter Using Property
1 | #!/usr/bin/env python3 |
Static Methods
Static methods can be called by both the class
and an instance of the class.
Problem with normal method:
1 | #!/usr/bin/env python3 |
And in this case:
1 | #!/usr/bin/env python3 |
To solve this problem static method can be used:
1 | #!/usr/bin/env python3 |
Class Methods
Like static methods class methods are not bound to specific instance.
But take a class as the first argument.
1 | #!/usr/bin/env python3 |
Inheritance Syntax and Example
1 | class C1: |
Example:
1 | #!/usr/bin/env python3 |
Using class like C/C++ Structure
1 | #!/bin/python |
Output:
1 | Name | 0 | Sex |
Operator Overloading and Magic Methods
There are special methods in python with double underscore
at the begining and end like __add__ which can be used
for operator overloading. Following example shows
overloading __str__ method, which will be called when
printing the object or str(object):
1 | #!/bin/python |
Output:
1 | [Person: Bob Smith, Kernel Developer, 10000] |
Here is another example overloading __add__() method
and __str__() method:
1 | #!/usr/bin/env python3 |
A list of python magic methods can be found
here
For each binary overloading methods, there is a
reverse method. Like for __add__() method there
is a __radd__() method to handle situation like:
1 | #!/usr/bin/env python3 |
Output:
1 | 55 BDT |
This problem can be solved using reverse method. Python first
search the overloaded method within the class, then the
corresponding reverse method in the class. Then search the
method in the parent class.
1 | #!/usr/bin/env python3 |
Output:
1 | 55 BDT |
Slots
Normally we can create class attributes dynamically outside of the class.
1 | #!/usr/bin/env python3 |
Slots are used to prevent this dynamic attribute creation.
1 | #!/usr/bin/env python3 |
Output:
1 | Traceback (most recent call last): |
A Class Example
Python Keywords and Symbols
At a Glance
[]- Make a list.{}- Make a dictionary.()- Make a Touple.if- if blockelse- else blockwhile- While loopin- Membership check- ‘not’ - Logical not
- ‘and’ - Logical and
- ‘or’ - Logical or
Tricks
List All Attributes of an Object
dir() function returns a list of all the attributes of an objetc.
1 | s = "I am a string" |
details of an object’s methods or attributes can be found using help() function.
>>> help(s.join)
Help on built-in function join:
join(...)
S.join(iterable) -> string
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.