Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python - Language Basics for Programmers

Python - Language Basics for Programmers

From zero to something. Getting started with Python for someone that already knows a programming language.

Matteo Bertozzi

February 11, 2017
Tweet

More Decks by Matteo Bertozzi

Other Decks in Technology

Transcript

  1. Python is… …byte-code interpreted my_ fi le.py #!/usr/bin/env python print(‘Hello

    Python!’) $ python my_file.py Generate the byte-code Execute the byte-code $ chmod +x my_ fi le.py $ ./my_ fi le.py top to bottom “line-by-line" execution You may see fi les ending with .pyc those are cached byte-code fi les >>> def foo(a, b): ... c = 0x20 ... return a * c + b ... >>> import dis >>> dis.dis(foo) 2 0 LOAD_CONST 1 (32) 3 STORE_FAST 2 (c) 3 6 LOAD_FAST 0 (a) 9 LOAD_FAST 2 (c) 12 BINARY_MULTIPLY 13 LOAD_FAST 1 (b) 16 BINARY_ADD 17 RETURN_VALUE cython
  2. $ python Python 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC

    4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> >>> a = 10 >>> print('Hello %d' % a) Hello 10 >>> >>> hex(255) ‘0xff' >>> 0xff 255 >>> bin(255) ‘0b11111111’ >>> 0b1010 10 >>> Installed by default on Linux & Mac Interactive shell …at least the 2.x version Basic Stuff >>> a = 10 >>> b = 20.5 >>> c = "hello" >>> d = 'hello' >>> e = [1, 2, 3, 4] # list >>> f = (10, 'hello', 'foo') # tuple >>> g = {'k1': 10, 'k2': 'bar'} # dict >>> h = set(['k1', 'k2', ‘k3’]) # set >>> print('hello %d' % 10) hello 10 >>> print('hello %d %.2f' % (10, 20.5)) hello 10 20.50 >>> print('hello %d %.2f %s' % (10, 20.5, 'foo')) hello 10 20.50 foo >>> print('%s %s' % (h, g)) set(['k3', 'k2', 'k1']) {'k2': 'bar', 'k1': 10} Quick conversion to bin, hex, oct and back
  3. if/else if a == 10: print('a is equal to 10')

    else: print('a is not equal to 10') if penLocation == 'table': print('the pen is on the table’) elif penLocation == 'floor’: print('the pen is on the floor') elif penLocation == ‘bag’: print(‘the pan is in the bag yoo’) else: print('I have no idea where the pen is') if a in (10, 20, 30, 40): print(‘a is in the cool range’) data = {‘k1’: 20, ‘k2’: 30} if a not in data: print(‘the key %s is not in the dict’ % a) keys = set([‘k1’, ‘k2’, ‘k3’} if a in data: print(‘the key %s is in the set’ % a) if/elif/else if in/not in a == 10 a != b a > 5 a <= 7 a == ‘foo’ a != ‘foo’ a < ‘foo’ a >= ‘foo’ a == 10 and b == 20 or c == 30 …there are no parenthesis, it’s all indentation based
  4. for loop for i in range(20): print(‘%d’ % i) x

    = [i for i in range(20)] list comprehension x = [i * 2 for i in range(20)] x = [i * 2 for i in range(20) if i % 2 == 0] my_list = [‘a’, ‘b’, ‘c’] for value in my_list: print(‘%s’ % value) my_list = [‘a’, ‘b’, ‘c’] for i, value in enumerate(my_list): print(‘%s at index %d’ % (value, i)) my_dict = {‘k1’: 10, ‘k2’: 20} for key in my_dict: print(‘%s -> %s’ % (key, my_dict[key)) my_dict = {‘k1’: 10, ‘k2’: 20} for key, value in my_dict.items(): print(‘%s -> %s’ % (key, value) i = 0 while i < 20: print(‘%d’ % i) i += 1 for i in range(10, 20, 2): print(‘%d’ % i) Dict comprehension x = {i: i * 20 for i in range(20)} my_list_of_tuples = [(‘a’, 10, ‘foo’), (‘b’, 20, ‘bar)] for a, b, c in my_list_of_tuples: print(‘%s %d %s’ % (a, b, c)) i = 10 while i < 20: print(‘%d’ % i) i += 2
  5. Functions def my_func(): print(‘Hey!’) my_func() def my_func(a, b): print(‘Hey %s

    %d!’ % (a, b)) my_func(‘foo’, 10) def my_func(*args): print(args) my_func(10, ’foo’, 20) def my_func(**kwargs): print(kwargs) print(kwargs.get(‘x’)) my_func(a=20,x=30) Classes class MyClass(object): def __init__(self, x): self.x = x def foo(self): print(‘foo %d’ % self.x) def bar(self, y): print(‘bar %d %d’ % (self.x, y)) def __repr__(self): return ‘MyClass(%d)’ % self.x obj = MyClass(10) obj.foo() obj.bar(20) print obj #!/usr/bin/env python print(‘hey’) def foo(): print(‘foo’) foo() if __name__ == ‘__main__’: print(‘main... kinda’) $ python my_test.py MyTest.py
  6. Modules & Functions modules are just “python fi les” (normal

    code) import random x = random.randint(1, 10) print(x) /my_dir/ /my_dir/__init__.py /my_dir/foo.py /my_dir/my_test.py from random import choice x = choice([10, 20, 30]) print(x) #!/usr/bin/env python def bar(): return ‘foo bar!’ if __name__ == ‘__main__’: print(‘foo module’) foo.py #!/usr/bin/env python import foo def my_func(): print(foo.bar()) if __name__ == ‘__main__’: my_func() my_test.py $ export PYTHONPATH=$PYTHONPATH:/my_dir $ python /my_dir/foo.py $ python /my_dir/my_test.py import sys argv = sys.argv get cmdline args …check also the argparse module
  7. You can just write out “data” HTTP Server on the

    fl y $ cd myWebDir $ python -m SimpleHTTPServer Serving HTTP on 0.0.0.0 port 8000 .. http://localhost:8000/myFile Simple REST Server from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer import json class JsonHttpHandler(BaseHTTPRequestHandler): def do_GET(self): self._handle_request() def do_POST(self): self._handle_request() def _send_json_response_headers(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() def _handle_request(self): content_len = int(self.headers.getheader('content-length', 0)) post_body = self.rfile.read(content_len) if self.path == '/hello': self._send_json_response_headers() self.wfile.write(json.dumps({'k': 'hello'})) elif self.path == '/foo/bar': self._send_json_response_headers() self.wfile.write(json.dumps([10, 20, 30])) else: self.send_response(404) self.end_headers() if __name__ == '__main__': server_address = ('', 8080) httpd = HTTPServer(server_address, JsonHttpHandler) httpd.serve_forever() set the response code and add the headers you want
  8. import urllib2, json data = {'barcode': '1234'} req = urllib2.Request('http://localhost:8080/foo')

    req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(data)) resp_data = response.read() print(resp_data) import urllib2 req = urllib2.Request('http://google.com') response = urllib2.urlopen(req) page = response.read() print(page) HTTP GET Request HTTP POST Request Json Encode/Decode import json data = [10, 20, 'foo', {'barcode': '1234'}] json_string = json.dumps(data) data_decoded = json.loads(json_string)
  9. Reading a File fd = open(‘my_file.txt’, ‘r’) try: while True:

    line = fd.readline() if not line: break print(line) finally: fd.close() with open(‘my_file.txt’, ‘r’) as fd: while True: buf = fd.read(512) if not buf: break print(buf) with open(‘my_file.txt’, ‘w’) as fd: fd.write(‘Hello File!\n’) fd.write(‘moar!\n’) using the with statement Writing a File Writing Binary Data a = 2 ** 23 # uint32 (I) b = 2 ** 56 # uint64 (Q) c = -300 # int16 (h) d = 0x7f # uint8 (B) import struct le_data = struct.pack(‘<IQhB’, a, b, c, d); be_data = struct.pack(‘>IQhB’, a, b, c, d); a, b, c, d = struct.unpack(‘<IQhB’, le_data) a, b, c, d = struct.unpack(‘>IQhB’, be_data) Reading Binary Data 0x00 0x00FF008F 0xFF 0x00 0x8F 0x8F 0x00 0xFF 0x00 Little Endian (Intel) Big Endian
  10. import thread, time def my_thread_func(): for i in range(10): print('thread

    func %d' % i) time.sleep(5) thread.start_new_thread(my_thread_func) Threads Yield def my_func(): for i in range(10): yield 'thread func %d' % i def my_func(): raise Exception(“bang!”) try: my_func() except Exception as e: print(‘got an exception: %r’ % e) Exceptions it = iter(my_func()) while True: try: v = next(it) print(v) print(‘yooo’) except StopIteration: break for v in my_func(): print(v) print(‘yooo’)
  11. import ctypes my_lib = ctypes.CDLL(‘my_lib.dylib’) x = my_lib.my_method() buf =

    ctypes.create_string_buffer(16) my_lib.my_rand(buf, 16) Calling C methods from Python int my_method (void); int my_rand (void *buf, int n); my_lib.so/my_lib.dylib/…
  12. …lots of builtin modules import collections import itertools import re

    import hashlib import os import sys import multiprocessing import socket https://www.python.org/doc/ Docs are really good! import zlib, gzip, bz2 import smtplib, imaplib, poplib import ftplib, httplib, nntp