My Python Notes
My Python Notes
My Python Notes
Basic modes:
Script
Interactive
Interactive Mode
To access the interactive shell:
$ python -i
To quit, type:
o Quit(), or
o Exit(), or
o Ctrl + D
Applications need specific Python packages and modules. A standard Python installation won't satisfy all
requirements. Virtual environment is for this purpose. For ex: application1 uses virtual environment 1
(python version 2, ...), application2 uses virtual environment 2 (python version 3, ...)
Creating a venv:
PEP 8: https://www.python.org/dev/peps/pep-0008/
Variable
Points:
No need to declare a variable (undefined var) before using it (ex: x = 7). However, to print a
variable (ex: print(x)), this var has to be defined.
A var can point to different data type at different times
Variable assignment:
o Multiple assignments on the same line
Local & Global Scope (3,67)
o Global statement (3,70): read the note on (3,75) cause very important
Checking the data type of an object:
o Print(type(x))
Data types: …
Number
o Float
Define a float number?
Boolean (3, 32)
String
List
Tuple (coursin of List) (3,96)
o https://docs.python.org/2/tutorial/datastructures.html
Set
o https://docs.python.org/2/tutorial/datastructures.html
o Set comprehensions (similar to “list comprehensions)
Dictionary (similar to an “associative array”)
o https://docs.python.org/2/tutorial/datastructures.html
Sequence Types: str, unicode, list, tuple, bytearray, buffer, xrange
o https://docs.python.org/2/library/stdtypes.html#typesseq
Scope
module scope
local scope
Data Types
String
Quotes
Use any of the below to open and close a string
single quotes
double quotes
triple single quotes
triple double quotes
To include double quotes inside a string, enclose them with single quotes and vice versa. Or we can also
use escape character ( \ )
Concatenation
+ (glue) and * (repeat: associated with loop) operators
“one” + “two”
Others
About string:
Immutable
Quotes
Escape characters (3,124)
Raw strings (3,125)
Special characters
Indexing: positive vs negative index
Slicing (substring)
Length
Formatting
Unicode strings
List
About a list:
Create a list
“+” operator
append() method
Remove item(s):
List methods:
Slicing
o Slices assignment
Length
Nesting lists
Can be used as a stack or a queue
o https://docs.python.org/2/tutorial/datastructures.html
Methods of a list objects:
o https://docs.python.org/2/tutorial/datastructures.html
3 useful built-in functions to use with list:
o Filter()
o Map()
o Reduce()
Concise ways to create a list (term: list comprehensions)
o https://docs.python.org/2/tutorial/datastructures.html
o Tags: bracket, expression, for clause
o Nested list comprehensions
Tuple
About tuple:
Create a tuple:
>>> mytup[0]
>>> mytup (display the whole tuple)
o Output: ('a', 1, 18.2)
[Unordered] Dictionary
About dictionary:
Create a dictionary
>>> mydic['apples']
Dictionary methods:
Ordered Dictionary
About Ordered Dictionary
Operators
Comparison operators
(3, 33)
https://docs.python.org/2/tutorial/datastructures.html
Boolean operators
(3,35)
Modules
https://docs.python.org/2/tutorial/modules.html
import, reuse
private & global symbol table
Standard modules
Packages vs Modules
A package is a collection (directory) of Python modules, while a module is a single Python file. It contains
an additional __init__.py file to distinguish a package from a directory that happens to contain a bunch
of Python scripts
Importing modules
(3, 57)
2 different syntaxes:
import os
o Use dot-syntax to access its functionality
os.path.abspath()
from os.path import abspath
o Pull in only the functionality we need
o Can call the function directly (no need the prefix)
abspath()
o Using the full name is recommended for a more readable code
Input/Output
Input
Ex:
Output
Displaying output
https://docs.python.org/2/tutorial/inputoutput.html
expression statements
print statement
write() method of file objects
Print command:
Print 3
Print “hello”
Print (“hello”)
print ("hello" + "\n") * 3
o print “hello\n” 3 times on the output (no need to use control flow statements like while,
for, or …)
Concatenation:
o A string and a number
Print(“your age is: “), age
Print “your age is: “, age
Print “your age is: “, str(age)
Print(“your age is:”, age)
o The function “print” joins parameters together with a space separator between them
Keyword arguments (3,65): end, sep
Use triple-quotes (either doubles or singles): """...""" or '''...'''. End of lines are automatically
included in the string, but it’s possible to prevent this by adding a \ at the end of the line.
A trailing comma avoids the newline after the output. Compare the followings:
First:
o ... a, b = 0, 1
o >>> while b < 10:
o ... print b
o ... a, b = b, a+b
Second:
o >>> a, b = 0, 1
o >>> while b < 1000:
o ... print b,
o ... a, b = b, a+b
Formatting output
2 ways:
o
% operator (old way of doing)
Reading & Writing files
File Objects
Flow Control
Tools:
While
For
If
Others:
Break statement
Continue statement
Else clause
Pass statement
Range() function
Looping techniques
https://docs.python.org/2/tutorial/datastructures.html
Some useful functions:
o Enumerate()
o Zip()
o Reversed()
o Sorted()
o Iteritems()
Conditions
Used in while or if or …
https://docs.python.org/2/tutorial/datastructures.html
elif ...:
else:
For (iterative loop)
For syntax:
"statements"
For illustration on how to use "for" for each data type, see the corresponding data type section
while "expression":
"statements"
Functions
(3, 61)
Some points:
return result
Classes
https://docs.python.org/2/tutorial/classes.html
Main points:
__init__():
o Called automatically every time the class is being used
Properties
o Can be modified
o Can be deleted (“del” keyword)
Methods:
o Are functions that belong to the object
The word “self”
o Is a reference to the current instance of the class.
o Can be named anything (doesn’t have to be named “self”), but it has to be the first
parameter of any function
An object can be deleted with the “del” keyword
Create an empty class with the pass statement
Rest API
Also check the title “Lib/urllib”
Library
Lib/json
Conversion table:
Json.loads
Json.dumps
Dumps stands for “dump string”
Translate a Python value into a string of JSON-formatted data
Lib/xml/dom/minidom
Many Python approaches to parse an XML payload:
MiniDom
ElementTree
Python/cpython/Lib/urllib
(also check the title “Rest API”)
req = Request(url)
req.add_header('User-Agent', 'Mozilla/5.0')
urllib3/urllib3/src/urllib3
psf/requests
https://github.com/psf/requests
https://docs.python.org/2/tutorial/errors.html
Regular Expression
(3,150)
If your script called a main() function, which in turn called a create_fortune_cookie_message() function,
which raised or generated an error... Your "call stack" would be:
REFERENCES
1. https://www.tutorialspoint.com/python/
2. https://docs.python.org/2/tutorial/
5. https://docs.python.org/3/contents.html