On Github jangm / present-python
Created by Jan Maghuyop / @jangm
We're not talking about the SNAKE!
Python is a clear and powerful object-oriented programming language, comparable to Perl, Ruby, Scheme, or Java.
Python is an easy to learn, powerful programming language.
Ideal language for scripting and rapid application development in many areas on most platforms.
English like porgramming language, good for novices and experts.
Scientists love python because it simulates and graphs thier studies.
>>> "three " * 3 'three three three ' >>>
Is'nt it nice a string and an integer multiplied results to 3 Three's.
>>> # list modules in the library >>> help('modules') >>>
"Batteries included"
docs.python.org/3/library/me@computer: alias server = 'python3 -m http.server' me@computer: server Serving HTTP on 0.0.0.0 port 8000 ...
Web prototypes as well, because deployment is a breeze!
>>> 8 ** 2 / 3.43 + 7.34 - .4 25.598892128279882 >>> im_using_python = 'yes' 'yes' >>> if im_using_python: 'You are!' 'You are!' >>>
Evaluate and test python code real fast.
me@linux:~$ python
C:\my\path\in\windows> python
mac:~ me$ python
So python wont stop developing on one platform.
me@pc:~$ python ez_setup.py me@pc:~$ python get-pip.py me@pc:~$ echo "install webserver" me@pc:~$ echo "install database" me@pc:~$ pip install djangoWeb development using python! Web frameworks!
Write once, run all, pythomatic integration!
Python is OPEN
Not free as in free beer!
me@pc: compiler program.extension -o program.executable
C C++ Obj-C C# Java Delphi Visual Basic; Low level?
// source c #include <library> datatype function(parameter) { // statements return 0; } // compile and execute
Brackets, semicolons, datatypes, library inclusion
#!/bin/bash # setting up an application using shell script package-manager install application cd /path/to/application/config/ mkdir backup cd .. mv -frv *.config backup/ mv -frv /your/config/*.config /path/to/appl/config
Powershell, Batch files, shell script
Websites that use python.
me@pc:~/download$ ls python33-installer.msi me@pc:~/download$ python33-installer.msinext next next next next ... done ( windows )
me@pc:~$ cd python/folder me@pc:~/python/folder/$ python
Python 3.3.3 ... Type "help", "copyright", ... >>>
Nice successfully installed python!
Python 3.3.3 ... Type "help", "copyright", ... >>> import sys # include sys module >>> print(sys.version) >>> 3.3.3 (v3.3.3:c3896275c0f6 ...
We're ready to program python know.
>>> im_using_python = 1 >>> if im_using_python: ... print("Absolutely!") 'Absolutely!'
All right, everything seems to work.
me@pc:~$ echo "print('Python rocks!')" >> pyscript.py me@pc:~$ python pyscript.py Python rocks! me@pc:~$
Create a file with a py extension.
Execute it by typing "python pyscript.py" without quotes.
#!/usr/bin/python3 print("Hello, World!")
Focus on development cycle not the syntax.
a, b = 5, 1 if a < b: print("{} < {}".format(a, b)) else: print("{} ! {}".format(a, b))
# condition expression print("true" if a < b else "false")
Selecting blocks / suites in python using conditions.
a, b = 0, 1 while b < 50: print(b) a, b = a, a + b print("Finish.")
Simple While loop fibonacci sequence.
a , b = 0, 1 for a in range(a, 5): a, b = a, a + b print(b)
Simple For loop fibonacci sequence.
def isEven(n): if n % 2 == 0: print("{} is even.".format(n)) for n in range(1, 10): isEven(n)
Code reuse using functions.
def simple_generator_function(): yield 1 yield 2 for value in simple_generator_function(): print(value) our_generator = simple_generator_function() next(our_generator) next(our_generator)
A generator is a function that has a yield suite.
class dog: def bark(self): print('Arf! ' * 3) def eat(self): print('Looks for a bone!') retriever = dog() retriever.bark() retriever.eat()
Code reuse using class to make objects and methods.
class actions: def eat(self): print('Looks for food!') class dog(actions): def bark(self): print('Arf! ' * 3) doberman = dog() doberman.eat()
Object inheritance in python.
try: file = open('file.txt') except IOError as e: print("Something went wrong!: {}".format(e)) print("After error.")
Handling errors without execution halt and reporting.
#!/usr/bin/python3 def main(): print("Main function!") if __name__ == "__main__": main()
Define functions first before they are called.
#!/usr/bin/python3 def main(): print("Main function!") print("This is inside main function!") print("See this line printed first!") if __name__ == "__main__": main()
Indent 4 space is a tradition in python.
# of spaces must be consistent inside a function.
def isOdd(n): if n % 2 == 1: # remainder of 1 is odd return True else: return False def numbers(n = 1): while(True): if isOdd(n): yield n # yeild n makes it a generator n += 1 for n in numbers(): if n > 50: break print(n)
Use comments to make the code more clear.
>>> two = 2 >>> n = two >>> type(n) >>> type(two) >>> a, b = 5, 10 # parallel assignments >>> a, b = b, a # exchange values >>> tuple = (11 ,22 ,33) # tuples use parenthesis >>> tuple
Assignment operator = assigns values and creates object of type.
a, b = 5, 10 # common else if statements if a < b: print("a is < than b") elif a > b: print("a is > than b") else: print("a is = to b") # conditional expression / conditional value answer = "greater than" if a > b else "not less than" print(answer)
Cond~ execution and cond~ expression, 2 types, clear syntax.
#!/usr/bin/pyton3 def main(): function(10) function(5) def function(a): for i in range(a): print(i, end=" ") print() if __name__ == "__main__": main()
Purpose is not usability but modularity.
#!/usr/bin/python3 class car: def __init__(self, type = "Muscle") # constructor self.type = type def whatType(self): return self.type def main(): mustang = car() print(mustang.whatType()) lancer = car("Tuner") print(lancer.whatType()) if __name__ == "__main__": main()
Classes defines objects, a class instance is an object.
>>> x = 100 >>> x >>> id(x) # id of an object, address >>> type(x)
All variables is a first class object.
>>> x = 9 >>> type(x) >>> id(x) >>> x = 99 >>> id(x) >>> x = 9 >>> ide(x)
Immutable Objects: Numbers, Strings, Tuples.
Mutable Objects: Lists, Dictionaries, other objects.
>>> var = 5 # int >>> var >>> type(var) >>> var = 5.0 # float >>> 5 / 9 >>> val = round(32 / 3, 2) >>> 5 // 9 >>> 5 % 9 >>>
Float and Int are actually object constructors.
>>> word = "battery" >>> print(word) >>> word = r"show\nme\nthe\nmoney!" >>> x = 14 >>> word = "word {}".format(x) >>> print(word)
words = '''\ hello mars! hello world! hello saturn! ''' print(words)
Strings in python are enclosed in quotes, the same as others.
>>> t = (10, 20 ,30) >>> print(t, type(t)) >>> l = [11, 22, 33] >>> print(l, type(l)) >>> l.append(5) >>> l, insert(1, 99) >>> s = "string" >>> print(s, type(s)) >>> print(s[2]) # index 2 >>> print(s[2:4]) # slicing >>> for i in l: ... print(i) >>> for i in s: ... print(i)
Tuple is an immutable object, lists, strings are mutable.
>>> d = {'one': 1, 'two', 2, 'three': 3} >>> print(d) >>> for i in d: ... print(i, d[i])
>>> d = dict( ... one = 1, two = 2, three = 3 ... ) >>> d['nine'] = 9 >>> print(d, type(d))
Dictionary are mutable objects, lists that are assosciative.
>>> n = 31 # immutable >>> id(n) >>> type(n) >>> type(42) >>> id(42) >>> y = 42 >>> n = y >>> n == y >>> n is y >>> n = dict(x = 42) # type?, id?, compared to y?
Everything in python is an object. Id refers to a specific object.
>>> x, y = 1, 2 >>> x == y >>> x < y >>> x > y >>> x = True >>> id(x) >>> type(x)
True and False are objects of class Bool.
x, y = 1, 5 if a < b: # replace codition with bool values print("this is true") else: print("it is not true")
If and else keyword followed by a suite of code and executes it.
switch(variable) { case value1: printf("this is value 1"); break; case value2: printf("this is value 2"); break; case value3: printf("this is value 3"); break; default: printf("no hit") }
Python doesn't have switch condition statements, elif does the job.
c = 'two' if c == 'two': print("v is two") elif v == 'one': print("v is one") elif v == 'three': print("v is three") else: print("v is not 1, 2, 3")
Several different conditions using elif. One only gets to execute.
choices = dict( one = 'first', two = 'second', three = 'third' ) v = 'three' print(choices.get(v, 'other'))
Get method of the dictionary object. Value to find and the return value.
x, y = 1, 2 x = "this is 1" if x < b else 'x is not one' print(v)
One easy line of code, easy to read and understand. If else shorthand.
# simple fibonacci x, y = 0, 20 while x < 50: print(y, end=" ") x, y = x, x + y
Simplest loop in python. While keyword then the condition follows.
for i in range(10): print(i, end=" ") for l in "letter": # a string is an object container print(l, "", end=" ") for n in [1, 2, 3, 4, 5]: # list is an object container print(n, end=" ")
Iteration is a common thing to do in python. Some python objects are iterators.
s = "string string string" for i, l in enumerate(s): print(i, l) if l == 's': print('index {} is an i'. format(i))
Enumerating the index is a useful thing in python. Enumerate function returns index and the iterator.
str = "string string string" for l in s: if l == 'g': break # halts the loop print(l, end="") for l in s: if l == 'g': continue # skips g print(l, end="") for l in s: print(l, end="") else: # when the loop returns false print("false")
Controls that escape the entire loop, shortcut the loop, else when it returns false.
>>> 4 + 3 # addition >>> 4 * 9 # multiplication >>> 3 - 10 # subtraction >>> 7 / 54 # division >>> 15 // 2 # floor division >>> 15 % 4 # modulo >>> divmod(10, 4) # 2 results together >>> n = 10 >>> n += 1 # compound operators for incrementing >>> n //= 4 # for division
Basic arithmetic operators in python.
>>> 5 >>> 0b0101 >>> def bin(n): print('{:08b}'.format(n)) >>> bin(5) >>> x ,y = 0x55, 0xaa >>> b(x) >>> b(y)
Created a bin function that converts the parameter to an eight bit binary form.
>>> b(x | y) >>> b(x & y) >>> b(x ^ y) # exclusive or >>> b(x ^ 0) >>> b(x ^ 0xff) >>> b(x << 4) # shift to left >>> b(x >> 4) # shift to right >>> b(~ x) # one's compliment of x
or, and, shifters and one's compliment in python.
>>> 5 > 6 >>> 5 < 6 >>> 5 => 6 >>> 5 <= 6 >>> 5 == 6 >>> 5 == 5 >>> 5 != 6
Comparing two values with comparison operators returns a bool value.
>>> x, y = 4, 3 >>> id(x) >>> id(y) >>> x is not y >>> x is y >>> y = 4 >>> id(y) >>> x is y
is and is not comparison operators in python.
>>> x, y = [5], [5] >>> x == y >>> x is y >>> id(x) >>> id(y)
Comparison for immutables like lists in python.
>>> 5 == 5 >>> 7 == 5 >>> type(True) # Boolean Class >>> True and False >>> True and True >>> True or True >>> True or False >>> True & True # bitwise operator
Boolean Values in python are special True and False objects.
>>> list = [0, 2, 3, 8, 5] >>> list[::-1] # reverse the list >>> list[4] >>> list[0:3] # slice operator >>> list[0:5:3] # step, third element >>> # non inclusive to last number like c arrays >>> for i in range(0, 10): print(i) >>> list[0:5] = (5, 5, 5, 5, 5) # change >>> for i in list[0:5]: print(i)
The slice operator is a way to get items from lists, as well as change them.
import re pattern = re.compiler(r'\d\d\d') if re.search(regex, line): print(line)
import re def main(): file = open("text.txt") for line in file: if re.search("(Len|neverm)ore", line): print(line, end="") if __name__ == "__main__": main()
Searching for string patterns using re module in python.
import re def main(): file = open("text.txt") for line in file: print(re.sub("(Len|neverm)ore", "@ @ @", line), end="") if __name__ == "__main__": main()
Using sub method in re module to replace characters from matched patterns.
import re def main(): file = open("text.txt") pattern = re.compile("(Len|neverm)ore") for line in file: if re.search(pattern, line): print(pattern.sub("@ @ @", line), end="") if __name__ == "__main__": main()
Use compile method from re module to reuse regular expression.
file = open("filename") except IOError as e: print(e) else: for l in file: print(l)You may raise your own exceptions with "raise"
def main(): try: file = open('file.txt') except IOError as e: print("Error: {}".format(e)) print("After error.") if __name__ == "__main__": main()
Using try to catch the error except when error occurs.
def main(): if filename.endswith(".txt"): file = (filename) return file.readlines() else: raise ValueError("filename must end with .txt") if __name__ == "__main__": main()
We use the raise keyword and give the exception.
def main(): function() function_pass(9, 8, 1) # can be assigned, none value def function(para, paras, params): print("This is a function.", para, paras, params) def function_pass(): pass # a function that does nothing if __name__ == "__main__": main()
Functions in python are the primary unit of reusable code.
def main(): function(9, 8, 1, 9, 8, 7, 6, 5, 4) def show_arguments(a, ar, arg, *args): print("arguments: ", a, ar, arg, args) for a in args: print(a, end = " ") if __name__ == "__main__": main()
Using *args to add infinite arguments to your function. It's a tuple so its immutable.
def main(): kwargs(9, 8, 1, 2, 22, 222, one = 1, two = 2) # kwargs stands for key word arguments def kwargs(a, ar, arg, *args, **kwargs): print("arguments: ", a, ar, arg, args, kwargs['one'], kwargs['two']) for a in args: print(a, end = " ") if __name__ == "__main__": main()
Passing named arguments in python using kwargs in the function definition.
def main(): print(function1()) for n in function2(): print(n, end=" ") def function1(): return "Returned this string!" def function2(): return range(25) if __name__ == "__main__": main()
Return any object from a function using a return statement.
def main(): for n in inclusive_range(0, 25, 1): print(n, end = " ") def inclusive_range(start, stop, step): n = start while n <= stop: yield n n += step if __name__ == "__main__": main()
A generator function returns an iterator object.
class Duck: def quack(self): print("quack!") def walk(self): print("*walks like a duck*")
A class Duck which has 2 methods quack() and walk().
donald = Duck() # class instantation # results to donald object donald.quack() donald.walk()
An object is an instance of a class.
class Duck: def __init__(self, value): # constructor method self.val = value def quack(self): print("Quaack!", self.val) def walk(self): print("Walks like a duck.", self.val)
Constructors are for initializing data first before methods can be called.
class Duck: def __init__(self, **kwargs): self.vars = kwargs def set_var(self, key, val): self.vars[key] = val def get_var(self, key): return self.vars.get(key, None) def main(): donald = Duck(feet = 2) donald.set_var("color", "blue") print(donald.get_var("feet")) print(donald.get_var("color")) if __name__ == "__main__": main()
This is just one of different ways to use object data in objects.
class Animal: def talk(self): print("I have something to say!") class Duck(Animal): pass def main(): donald = Duck() donald.talk()
In OOP Inheritance is inheriting properties from a class to another class.
class Dog: def bark(self): print("Arf! Arf! Arf!") class Duck: def bark(self): print("Duck cannot bark!") def main(): donald = Duck() donald.bark()
Polymorphism is using another object in another class.
>>> "This is a string!" >>> s = "This is a string!" >>> s >>> s.upper() >>> "This is {}".format(32)
Strings are objects.
>>> s = "This is a string!" >>> s.capitalize() >>> s.upper() >>> s.lower() >>> s.swapcase >>> s >>> s.find("s") >>> id(s)
>>> s = ss >>> id(ss) >>> " strip! ".strip() >>> "strings".strip("gs") >>> s.alnum() >>> s.alpha() >>> "12345".isdigit()
>>> a, b = 1, 2 >>> print(a, b) >>> "this is {}, that is {}.".format(a, b) >>> "this is {}, that is {}." >>> id(s) >>> new = s.format(a, b) >>> id(new)
Using format to add variables on strings.
>>> s = "string strings stringss" >>> s.split() >>> s.split("i") >>> words = s.split() >>> for word in words: print(w) >>> new = ":".join(words) >>> new
Using split and join string methods.
>>> s = "this is a string" >>> new = s.center(80) >>> len(new) >>> s.lower() >>> s.center(80)
Check and read python string methods in documentation.
>>> t = 1, 2, 3, 4, 5 # tuple >>> t >>> t[0] >>> len(t) >>> min(t) >>> max(t) >>> tt = tuple(range(20)) >>> l = list(range(20)) >>> tt[3] = 19 # tuples are immutable!
Tuples are fast to implement and don't allow you to change stuff.
>>> t = tuple(range(20)) >>> type(t) >>> 10 in t >>> 50 in t >>> 50 not in t >>> for n in t: print(n) >>> t[3] >>> len(t) >>> l = list(range(10)) # methods are the same with lists >>> l.append(10) >>> l.extend(range(10)) >>> l.insert(0, 100) >>> l.pop(0) # l.pop()
Methods on tuples and lists, lists can pop, insert and extend.
>>> d = {"one": 1, "two": 2, "three": 3 } >>> type(d) >>> "one" in d >>> "four" in d >>> for key in d: print(key) >>> for key, value in d.items()L print(key, value) >>> d["three"] >>> d.get("three") # exception for items not found
Indexes are data, which means faster searching, manageable.
file = open("lines.txt", "r") # r, r+, w, a, rt, rb for line in file: print(line, end="")
Opening files and its, arguments read, write, append, read and write, text, binary modes.