and share this material (you can teach someone using this) this is just the beginning you need much more practice than this to become a python jedi we only start the changing when we provoke the changes and this is a change provoker fuck off and let's go ahead
part of syntax • interpreted and high-level • there are two main versions: 2.7 (ascii) and 3+ (utf-8) • does not have native concurrency • programming paradigms: functional / imperative / procedural / oop • created by guido van rossum in 1991 • automagic: dynamic types • easy like a piece of cake • how to learn: get the fundamentals / try it out / again / again / pick up an open source project / change it and pull request more: https://www.python.org/about/gettingstarted/ conventions on this doc: $ command line indicator # comment pho- an acronym prefix for python hands on lines of code
a native pkg manager: pip / pip3 • you should use pip / pip3 to install some library or dependency • python also supports environment virtualization to sandboxing deps: virtualenv / pipenv debian/ubuntu $ sudo apt-get install python-setuptools python-dev; sudo easy_install pip; sudo pip install –-upgrade virtualenv centos $ sudo yum install –y epel-release; sudo yum makecache; sudo yum install python-setuptools python-pip; sudo pip install –-upgrade virtualenv python $ pip3 install virtualenv --user creating a new environment: $ cd; mkdir –p python/training; cd python/training; virtualenv deps using on your environment: $ source deps/bin/activate check it out: $ whereis pip install a library: $ pip install flask important tip: pip is for python2 and pip3 is for python3 tip: take a look at conda (machine learning package manager)
4 b = 2 c = [2,3,4] d = "Some stupid string" print("sum: %d. sub: %d. div: %.2f. mul: %d. mod: %d. exp: %d" % ((a+b),(a-b),(a/b),(a*b),(a%b),(a**b))) print("a>b: ", a>b) print("a<b: ", a<b) print("a==b: ", a==b) print("a!=b: ", a!=b) if b in c: print("Yeah! There is %d in %s" % (b, c)) else: print(":/") x = 10 if a in c else 5 print(x) print("Some" in d)
modes: # [r] = readonly. offset root level # [w] = write. overwritten if file already exists. # [a] = append mode. continues writing after the last char. creates if file does not exist # # [b] = use this option with the others above to open in binary mode. eg: # [wb] = write in binary mode # import os fp = open("app.log", mode = "w") print("name: ", fp.name) print("state is closed: ", fp.closed) print("opening mode: ", fp.mode) fp.close() fp1 = open("app2.log", mode = "a", encoding = "utf-8") fp1.write("just a text inside the file.") fp1.close() with open("app3.log", mode = "w+") as fp3: fp3.write("elegant way to open. auto close the file after this block") print("state is closed: ", fp3.closed) if os.path.isfile("app3.log"): os.remove("app3.log")
# an error interrupts the execution of the program. related to syntax print("This is a python program" $ vi pho-exception.py #!/usr/bin/env python3 a = "foo bar" try: print(a[40]) except IndexError: print("this is an index detected error") except SyntaxError: print("should it be a syntax error?") else: print("i'm dumb. could not detect the error") $ vi pho-raising.py #!/usr/bin/env python3 try: a = int(input("Please, type a number greater than zero: ")) if a <= 0: raise ValueError("i said a fucking positive") except ValueError as msg: print(msg) take a look: https://docs.python.org/3.6/library/exceptions.html
['orange', 'watermelon', 'papaya'] profile = {'name': 'Thiago', 'age': 34} for x in range(0,10): print("Couting numbers: %d") for item in fruits: print(item) for key, item in profile.items(): print("key: %s. item: %s" % (key, item)) count = 0 while count < 5: print(count) count += 1 for x in range(1,100,2): if x % 27 == 0: break
$ touch sound/effects/__init__.py $ vi sound/effects/echo.py #!/usr/bin/env python3 def single(): print("echo!") def double(): print("echo!" * 2) if __name__ == "__main__": single() $ vi sound-effects.py #!/usr/bin/env python3 import sound.effects.echo sound.effects.echo.single() $ vi sound-effects2.py #!/usr/bin/env python3 from sound.effects import echo echo.single() echo.double() Pay attention to packages collision, eg: mkdir math; touch math/__init__.py If you import this module, you are conflicting that with original math module. Take a look: https://docs.python.org/3/py-modindex.html
b): print("A: %d. B: %d" % (a,b)) return(a+b) def sum2(a=0, b=0): print("A: %d. B: %d" % (a,b)) return(a+b) def myfunc(arg1, *mytuple): print("I know this arg: %s" % str(arg1)) for x in mytuple: print("This is new for me: %s" % str(x)) def myfunc2(arg1, **mydict): print("I know this arg: %s" % str(arg1)) for key,value in mydict.items(): print("This is new key [%s] and value [%s]" % (key,value)) print(sum1(1,2)) print(sum2(2)) myfunc(10, 20, 30, 40, 50) print(myfunc2(10, **{'course': 'python', 'grade': 1.5})) # print(sum1(a=1)) Try to comment out the last line to check the results
import functools # just a lambda example f = lambda x, y: x+ y f(1,1) # map function with lambda celsius = [39.5, 33.2, 39.5] farenheit = map(lambda x: 9.0/5 * x + 32, celsius) print(farenheit) print(list(farenheit)) # filter function with lambda numbers = [1, 3, 4, 5, 6] just_even = filter(lambda x: x%2 == 0, numbers) # reducing function with lambda result = functools.reduce(lambda x,y: x+y, numbers) print(result) Guido's preferred method is List Comprehensions, he hates lambda and specifically reduce. Lambda's is for the Lisp(ers).
Animal: """ This is a tipical class doc """ total = 0 def sound(self): print('generic sound') class Dog(Animal): def sound(self): print('au au') class Chihuahua(Dog): def sound(self): print('au') animal = Animal() animal.total = 10 print(animal.total) animal.sound() dog = Dog() dog.sound() print(Dog.__bases__) chihuahua = Chihuahua() chihuahua.skin() this is not an oop class, please read more in: http://bit.ly/2D5EXnd
python3 # class Person: def __init__(self, name, surname): self.name = name self.surname = surname person = Person(name='thiago', surname='ribeiro') print(person.name.title()) $ vi pho-classes2.py #!/usr/bin/env python3 # class Person: def __init__(self, name, surname): self.name = name self.surname = surname class Employee(Person): def __init__(self, code, age, *args, **kwargs): self.code = code super().__init__(*args, **kwargs) employee1 = Employee(code=123, name='thiago', surname='ribeiro', age=34) # kwargs are mixed employee2 = Employee(123, 34, 'thiago', 'ribeiro') #args has an order print(employee1.name.title()) print(employee2.name.title()) try to comment the super() function to figure out what happens
pdb from datetime import date pdb.set_trace() class Person: def __init__(self, name, surname, birth): self.name = name self.surname = surname self.birth = date(int(birth[0:4]), int(birth[5:7]), int(birth[8:])) def age(self): age = date.today().year - self.birth.year fyp = date.today().month < self.birth.month and date.today().day < self.birth.day if fyp: age = age - 1 return age person = Person('thiago', 'ribeiro', '1983-02-09') print(person.age()) take a look to iterate with pdb: https://docs.python.org/3/library/pdb.html
cProfile from datetime import date pr = cProfile.Profile() pr.enable() class Person: def __init__(self, name, surname, birth): self.name = name self.surname = surname self.birth = date(int(birth[0:4]), int(birth[5:7]), int(birth[8:])) def age(self): age = date.today().year - self.birth.year fyp = date.today().month < self.birth.month and date.today().day < self.birth.day if fyp: age = age - 1 return age people = [] for x in range(1,1001): person = Person('thiago', 'ribeiro', '1983-02-09') people.append(person) pr.disable() pr.print_stats() take a look at documentation: https://docs.python.org/3/library/profile.html
unittest from person import Person class PersonTest(unittest.TestCase): def setUp(self): self.person = Person(name='thiago', surname='ribeiro', birth='1983-05-09') def test_name_is_capitalized(self): self.assertEqual(self.person.name(), 'Thiago') def tearDown(self): print('end of testing') if __name__ == "__main__": unittest.main() take a look at documentation: https://docs.python.org/3/library/unittest.html
should read starting at 1 until 8 start reading by pep8 – style guide for python code complete list of peps and other documents: https://www.python.org/dev/peps/ validating your code $ pip3 install pep8 $ pep8 <yourfile>.py
server (just for samples) • django • mvt and dry concepts (good for cruds) • bottle • micro web framework (thin, thin, thin) • flask • micro web framework based on werkzeug and jinja2 (many modules) • tornado • scalable and non-blocking web server application (async operations) • cyclone • implements tornado api as a twisted protocol (like tornado, but easier)
http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever() take a look at documentation: https://docs.python.org/3/library/http.server.html
know rest apis are created over HTTP protocol once you create a new api you should consider some versioning like git you should maintain the http methods to run the actions you need let's build some api to handle our customers. consider the customers api structure method uri description GET /v1/customers list all customers GET /v1/customer/[customer_id] retry a specific customer POST /v1/customer add a new customer PUT /v1/customer/[customer_id] update an existent customer PATCH /v1/customer/[customer_id] same as above DELETE /v1/customer/[customer_id] remove an existent customer preparing $ mkdir customers; cd customers $ touch config.py customer.py setup.py models.py if you need some documentation to your api, take a look: https://swagger.io/
chmod +x customer.py $ ./customer.py & handling the api $ curl –v http://localhost:5000/ $ curl –H "Content-Type: application/json" –X POST –d'{"name":"Thiago", "surname":"Ribeiro", "birth":"1983-05-09"}' \ http://localhost:5000/customer $ curl –v http://localhost:5000/customer/1 homework • implement the function to calculate the customer age • implement the method GET to list all customers • consider using pagination: https://blog.fossasia.org/paginated-apis-in-flask/ • implement the methods to update and delete customers