Python
The basics
-
if / print
- lists / dict / set
- for / while
-
def
-
import
-
class
if
if 1 == 1:
print "wow"
elif not "1" == 1:
print "so much wow"
else:
print "if all else fails trust the else"
The "Truth":
False | True |
False (== 0) | True (== 1) |
"" (empty string) | any string but "" (" ", "anything") |
0, 0.0 | any number but 0 (1, 0.1, -1, 3.14) |
[], (), {}, set() | any non-empty container ([0], (None,), ['']) |
None | almost any object that's not explicitly False |
List []
myList = [1,2,"3"]
myList.append("test")
myList.remove("test")
print myList[1] # prints 2
Dict {}
myDict = {"key": "val"}
myDict['new key'] = "new val"
del myDict['new key'] # del is global
print myDict["key"] # prints "val"
Set
mySet = set(1,2,3)
mySet.append(1)
mySet.remove(2)
print mySet[2] # prints "3"
Common
len(collection) # prints the size
for
myList = [1,2,3]
for var in myList:
print var
while
while 1==1:
print "Im crashing ur computer..."
ITERATING a dict
myDict = {"some key": "some val", 1: 2}
for key, val in myDict.items():
print key, ":", val # prints some key : some val\n1 : 2
for key in myDict.keys():
print key # prints some key\n1
for key in myDict:
print key # prints some key\n1
DICTIONARIES AREN'T sorted
The dictmyDict = {
1:3,
2:2,
3:1
}
Simple
for key, val in sorted(myDict.items()):
print key, val
"Hard"
for key, val in sorted(myDict.items(), key=lambda t: t[1]):
print key, val
for key in sorted(myDict, key=lambda key: myDict[key]):
print key, myDict[key]
Adding to dict tips
theList = [1,2,3,1,2,3,1,2,3,1,2,3,1,3,2,1,2,3,1,3,2,1]
theDict = {}
The "wrong" way:
for number in theList:
if number not in theDict:
theDict[number] = 0
theDict[number] += 1
The "right" way:
for number in theList:
theDict.setdefault(number, 0)
theDict[number] += 1
Adding to dict tips
theList = [1,2,3,1,2,3,1,2,3,1,2,3,1,3,2,1,2,3,1,3,2,1]
theDict = {}
for number in theList:
if number not in theDict:
theDict[number] = []
theDict[number].append("BO!")
The "right" list way:
for number in theList:
theDict.setdefault(number, []).append("BO!")
Python 3.X vs 2.X
Simple explanation:
print "hello world 2.X"
print("hello world 3.X")
print "one", "two" # prints "one two\n"
print("one", "two") # prints "one two\n"
print "no", "newline", # prints "no newline"
print("no", "newline", end="") # prints "no newline"
FORMATTED print
print("vv%svv" % 123) # prints "vv123vv\n"
print("%s: %s" % ("one", "two")) # prints "one: two\n"
print('%d-%0d-%5d-%05d' % (34, 34, 34, 34)) # prints "34-34- 34-00034\n"
Files
f = open('myfile.txt') # contains "1,2,3\n4,5,6"
for line in f:
first, second, third = line.strip().split(',')
print(second) # prints 2\n5
Functions
def someFunc(someParam):
return someParam + 1
Classes
class MyClass():
member = 1
def method(self, methodParam):
return methodParam + self.member
Inheritance
class MySecondClass(MyClass):
def someThing(self):
return member
Kill all getters/setters!
class myClass:
x = "text"
Need to change behavior?
class C(object):
_x = 0
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value+2000
Class methods for OVERRIDING
- object.__init__(self)
- object.__del__(self)
- object.__hash__(self)
- object.__lt__(self, other)
- object.__le__(self, other)
- object.__eq__(self, other)
- object.__ne__(self, other)
- object.__gt__(self, other)
- object.__add__(self, other)
-
object.__ge__(self, other)
-
object.__add__(self, other)
your first script
hello.py
print("hello world")
Run it
python hello.py
Using a main method
def main():
print myfunk(1)
def myfunk(n):
return n + 2
if __name__ == '__main__': main()
Importing
import filename
import filename, filename2
import method from filename
import method from filename as newName
standard libs
sys <-- used to get argv
os <-- used to get system variables and the like
re <-- regex
The WEIRD stuff
":".join([1,2,3]) # becomes "1:2:3"
elif: # why not else if???
__someFunk__() # "private" methods
Some of The good stuff
beautiful
if 44 < var < 50:
if var % 2:
return true
auto unpacking
one, two, three = [1,2,3]
oldArray = [[1,2],[3,4],[5,6]]
newArray = [x[1] for x in oldArray]
if not someTruthyVar: doSomething()
if someVar in list: doSomethingElse()
Exercises
- Create a script that takes an argument and prints it
- Count the lines in a file you send in as a argument
- Create a class and override the add method of the class
- Put the class in a separate file
- Create a function that takes unlimited
arguments (not in these notes) - Create a script that prints all the image urls in vg.no
hint:
from urllib import urlopen
html = urlopen('http://vg.no').read() - Create a script that prints the fibonacci series
- Create a script that finds the primes of a number
Python
By pylinux
Python
- 757