Python#
(P2) indicates Python 2
(P3) indicates Python 3
Running#
Create a file named "file1.py"
python3 file1.py
Data Types - all are objects#
NoneType | None (like null or nil) |
bool | False / True (also acts like 0 / 1) |
int | unlimited size (P3), 23 (0x22 hex, 0o34 octal, 0b010 binary) |
long | P2 only, 48L |
float | 3.141 |
str | “string” or ‘string’ - immutable |
characters are just strings of length 1 | |
[a,b] | list - mutable |
(a,b) | tuple - immutable |
Data Conversion#
int(x) | convert to int |
long(x) | P2 only |
str(x) | convert to str |
Misc#
Comments start with #
All variables are object references (boxed)
Identifiers start with a letter or underscore - case sensitive
All variables are dynamically typed
type(x) returns the class of x
Zero based indexing using []. Also allows negative indexing from the back (-1 = last character)
Logical operations#
In conditionals, the following are all false:
False |
None |
0 |
“” |
x is y | do x and y refer to the same object |
x is not y | |
== | compares values, works on strings |
1 < x > 10 | range check |
2 in [1, 2, 3, 4] | |
‘el’ in ‘hello there’ |
Logical operators (works like lisp!)
and |
or |
not |
Function Definition#
def fun(): line 1 line 2
Can use return x (without return, returns None)
Function names that begin with underscore are private (by convention - not enforced)
Statement grouping is indicated by space characters at the beginning of each line rather than braces, begin / end statements, etc.
All variables are local unless declared with global
Statements#
if cond1: stmt 1 elif cond2: stmt 2 else: stmt 3
while cond: stmts
for var in lst: stmt using var
try: stmts except type as var: stmts
Operators#
+= | works on all data types |
"""string""" | to embed newlines in string |
pass | is statement that does nothing (used where statements are required) |
Modules & Packages#
(Application) Module X = X.py file
Also system modules like: sys os etc.
import file1 # imports file "file1.py" import file1, file2, file3 import file1 as mymodule
or
from file1 import * # imports into the current package from file1 import (obj1, obj2, …)
Accessing objects imported via the lines starting with “import” is done:
file1.obj1Accessing objects imported via the lines starting with “from” is done:
obj1
Python searches for modules as follows:
- same directory as file with the import statement
- PYTHONPAH environment variable
- sys.path
import only loads it the first time but will not re-load a changed file
Reloading a changed file can be done with reload(file1)
Input / Output#
print(x) | prints x and newline (P3) |
x = input(“prompt”) | input string with prompt (P3) |
x = raw_input(“prompt”) | input string with prompt (P2) |
x = input() | input string without prompt (throws EOFError exception) |
Dictionary#
dict = {} dict[‘key’] = value value = dict['key'] dict.clear() len(dict) dict.get(‘key’) dict.has_key(‘key’) dict.keys() key in dict del dict['key']
Classes#
Top of hierarchy is “object”
Supports multiple-inheritance & metaclasses
class MyClass: ...
class MyClass (SuperClass1, SuperClass2, …): ...
class MyClass: cv1 = None def __init__(self): self.iv1 = None self.iv2 = None def getiv1(self): return self.iv1 def setiv1(self, val): self.iv1 = val @classmethod def getcv1(cls): return MyClass.cv1 @classmethod def setcv1(cls, val): MyClass.cv1 = val def __repr__(self): # printed representation (also str() if no return "aabb" # __str__ def __str__(self): # str() representation return "xxxxyyyy" x = MyClass() MyClass.setcv1(55) x.setiv1(33) MyClass.cv1 = 77 x.iv1 = 32 class MyClass2(MyClass): def __init__(self): super().__init__()
Virtual environments#
mkdir myProject create virtual environment cd myProject virtualenv venv source venv/bin/activate enter virtual environment deactivate exit virtual environment
ODBC#
import pyodbc conn = pyodbc.connect('DSN=XXX;UID=YYY;PWD=ZZZ;DATABASE=MyDatabase') cursor = conn.cursor() cursor.execute("SELECT * from my_table") while 1: row = cursor.fetchone() if not row: break print row.name