Quick Python Lecturers Boontee Kruatrachue Room no 913
Quick Python Lecturers : Boontee Kruatrachue Room no. 913 Kritawan Siriboon Room no. 913 Text : รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 21
Why Python ? https: //snakify. org/ Python is a great choice whether it's your first or next programming language. 1. Python is very easy and flexible. The programs in Python are tinier than in other languages. 2. Powerful. Due to its huge community Python is very popular as a server-side language. Google (spider, search engine, Google Maps), Netflix and Pinterest use it a lot. Youtube, Quora, Reddit, Dropbox, Yahoo, Battlefield 2, Civilization 4, NASA, Alpha. Gene — all of them use Python; see the entire list here. 3. รศ. ดร. บญธร High demand for programmers. See open job positions on Stack. Overflow เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Study by Yourself : many options https: //snakify. org/lessons/lists/steps/1/ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ Input, print and numbers Conditions: if, then, else Integer and float numbers For loop with range Strings While loop Lists Functions and recursion Two-dimensional lists (arrays) Sets Dictionaries KMITL 01076249 Data Structures & Algorithms : Tree 2
Python • Guido van Rossum : early 1990 s • Python 2 : 2000 • major version Python 3 : 2008 • latest version freely available at www. python. org รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Python Interpreter prompt ���� ��� >>> 3 + 5 Outp ut 8 >>>20 - 2*2 Interpreter ����� �� ����� comment �� ���� 16 >>>print('Hello') # string ใน '…' หรอ "…" Hello >>> รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Built-in Types Commonly-used built-in class (type) : type ? Python : • numbers Object Oriented • integral Programming (OOP) • int >>> type(5) • bool class Compl <class 'int'> • float ��������� data ex • complex 7 + 3 j type • sequences (��������� ) >>> type(3. 5) • immutable ������� content ������ j/J • str (string) s = 'Hi' imaginary part <class 'float'> • tuple s[1] = 'A' #error • byte ������� content ��� • mutable >>> type("Hi") • list <class 'str'> • range • bytearray • mappings >>> type('Python') • dict • set <class 'str'> • set (mutable) • frozenset (immutable) • callable types (~ fn call) >>> type([1, 2, 3]) • class <class 'list'> • function • … รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Variable (Name, Identifier) Na me case sensitive a to z A to Z 0 to 9 _ _var 1 if keyword my. Var elif keyword num 9 i ���� ��� 0 --9 ���������� keywords Python Keywords รศ. ดร. บญธร False and break def else None as class del except from import lamda True assert continue elif finally in เครอตราช รศ. กฤตวน ศรบรณ for global if is not raise or return with nonlocal pass try while yield KMITL 01076249 Data Structures & Algorithms : Tree 2
Assignment Statement Assignment Operator name = expression Python : Dynamic int(2) ����� instance ���� (instantiate (��� class int ����� 2 Type��� Identifier Assignment Statement: constructor )fn ���� call ��������� instantiate ��� set ����� ( identifier expression คอ สงท return value declared type evaluate expression ������ constructor ������� object ������ reference str name = �� type "Hello" output: No RS a = 5. 2 type !!! float int a = 7. 2 b = int(2) 5; print(a, b) 5. 2 2 a = a + b print(a) 7. 2 a = "Hello" print(a) Hello a float 5. 2 b int 2 name RS object reference to a = Identifier a references ����� instance ��� float class ���� a 5. 2 Instantiation : Process of creating new instance of a class. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Instantiation , Calling Method Instantiation : Process of creating new instance of a class. Instantiation : 3 ���� trunc 3. 2 -> 3 1. j = int(3. 2) var = class. Name(…) invoke constructor 2. s = ‘hello’ ������ built-in class ��� literal ��� 3. upper. Case. Str = upper(s) call function ��� return object รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ calling method : instance. Name. method(…) output: s = ‘hello’ print(s. upper()) HELLO KMITL 01076249 Data Structures & Algorithms : Tree 2
id(), is >>> i = 1 >>> j = i >>> print('i: ', id(i), ' i: 1435750864 j: ', id(j)) j: 1435750864 >>> print(i is j) i True same obj ? >>> i = 3. 5 >>> print('i: ', id(i), ' i: 6757328 j: 1435750864 >>> print(i is j) False รศ. ดร. บญธร 3. 5 เครอตราช รศ. กฤตวน ศรบรณ j: ', id(j)) j 1 i is j False 1435750864 id(i) returns (int) id ��� obj ��� bound ��� i KMITL 01076249 Data Structures & Algorithms : Tree 2
Multiple Assignments 1 2 3 >>> a, b, c = 1, 3. 5, 'Hello' >>> print(a, b, c) 1 3. 5 Hello >>> i = j = k = 'same' >>> print(id(i), id(j), id(k)) 37565440 ���� evaluate ������ exp 3, exp 4 = exp 1, exp 2 exp 3 = exp 1 exp 4 = exp 2 b = 5 10 5 i = 1 x[1] = 2 1 2 a = 10 1 - >>> a = 5 >>> b = 10 >>> a, b = b, a >>> print(a, b) 10 5 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ >>> >>> [7, 20 x = [17, 3] i = 0 i, x[i] = 1, 2 print(x) 2] 0, 1 List [0, 1] ����������� index access ������ -> ��������� index 0, 1 , . . . ������ -> ��������� index 1 -, 2 - , . . . KMITL 01076249 Data Structures & Algorithms : Tree 2
Undefined Name Using Undefined Variable >>> n Traceback (most recent call last): File "<stdin>", line 1, in <module> Name. Error: name 'n' is not defined ERRO R รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
print() output a = 5 print() end ���� 5 print(a) newline print(a, '+', b, "=", a+b) 12 = 7 + 5 b = 2 ���� seperate ���� space ����� >>> print(a, '+', b, "=", a+b, sep = '', end = '***n') ***5+7=12 รศ. ดร. บญธร ����� �set sep ����� �set end ��� เครอตราช รศ. กฤตวน ศรบรณ null charac ter KMITL 01076249 Data Structures & Algorithms : Tree 2
input(), int() retur prom n pt strin g a = input('enter a: ') input/output: enter a: 5<enter> print(a) 5 b = input() 2<enter> string concatenati on print(a + b) 52 print(a) + int(b)) 7 int(a) instantiate instance int ���� input str a convert a ��� str ������� int รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Arithmetic Operators (…) ����� � >>> (20 - 2*2)/4 4. 0 floating point division >>> 5/2 2. 5 div >>> 5//2 2 mo d >>> 5%2 1 pow er >>> 2**3 8 >>> 3. 5 - 2 1. 5 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ mix : convert int ���� float ���� KMITL 01076249 Data Structures & Algorithms : Tree 2
import statement, module math ����� imp module : module. Name. variable ort file ����� ��� >>> from math import pi math>>> fns import & math �������� >>> print(pi) >>> print(math) <module 'math' (built-in)> 3. 141592653589793 >>> print(math. pi) >>> from math import * 3. 141592653589793 >>> cos(pi) >>> math. cos(math. pi) -1. 0 >>> pi = 5 >>> math. log 2(8) >>> cos(pi) 3. 0 0. 28366218546322625 >>> math. sqrt(16) 4. 0 ��� name ������ �� * wildcar d charact er = for all � �� � >>> math. trunc(3. 67) 3 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
bool class ������� 2 instanc es instantiate bool ��� class ���� • number (0, ��� 0) • sequence (empty, ��� empty) รศ. ดร. บญธร False True bool() False bool(0) False bool(3. 2) True bool([]) False bool([1, 2]) True เครอตราช รศ. กฤตวน ศรบรณ bool() default return False KMITL 01076249 Data Structures & Algorithms : Tree 2
int class ��� prefix ���� integer ������ Immuta (zerocharacter) Python ble ��������������� binary, octal, ��� integer hexadecimal 0 b 1011, 0 o 52, 0 x 7 f int() instantiate int ��� class ���� • float : truncate • รศ. ดร. บญธร string : ���� convert ��� เครอตราช รศ. กฤตวน ศรบรณ 0 int(3. 5) 3 int(-2. 3) -2 int (‘ 37’) int() default return 0 37 int(‘Hi’) error int(‘ 7 f’, 16) 127 base default base 10 KMITL 01076249 Data Structures & Algorithms : Tree 2
float class ���� floating point ������ C/Java double 2. Immuta 25 7. 022 e 25 7. 022 x 10 ble instantiate float ��� class ���� • int • str รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ float() 0. 0 float(2) 2. 0 float( ‘ 3. 14’ ) 3. 14 float ( 'hello' ) error float() default return 0. 0 KMITL 01076249 Data Structures & Algorithms : Tree 2
Arithmetic & Bitwise Operators Arithmetic Operators : + addition − subtraction * multiplication / true division // integer division % the modulo operator Bitwise ∼ & | ˆ << >> รศ. ดร. บญธร Operators : bitwise complement (prefix unary operator) bitwise and bitwise or bitwise exclusive-or shift bits left, filling in with zeros shift bits right, filling in with sign bit เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Arithmetic Operator Precedence output lowest precedence highest precedence รศ. ดร. บญธร 5 + 3 5 - 3 5 * 3 5 // 3 5 % 3 -5 +5 abs(-5) int(5. 2) 8 2 15 1. 666666667 1 2 -5 5 float(5) divmod(5, 3) pow(2, 3) 2 ** 3 5. 00 (1, 2) 8 8 float conversion เครอตราช รศ. กฤตวน ศรบรณ div mod absolute int conversion divmod pair KMITL 01076249 Data Structures & Algorithms : Tree 2
Sequence classes ����� mutable • str • list • tuple (immutable list) • range รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
str class ���� characters ������� ��� Unicode ���� Immuta ble ��� unicode characters ��� �� 20u 20 AC ������ string € 20 ���� ‘ ‘ ���� “ “ ����������� list ��� tuple instantiate str ��� class ���� • int • float รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ str() ‘’ str(2) ‘ 2’ str(2. 5) ‘ 2. 5’ str() default return null str KMITL 01076249 Data Structures & Algorithms : Tree 2
string 1 str ���� characters ������� >>> 'string' singl 'string' e/ >>> "This is also string" doub 'This is also string' le quot >>> 'don't' es escape "don't" >>> "don't" ������ ' >>> print('C: Peaname') C: Pea ame >>> print(r'C: Peaname') C: Peaname >>> 'C: Peaname' r (raw 'C: \Peaname' string) รศ. ดร. บญธร >>> print("""1234. . . 5678""") 1234 5678 >>> print(""". . . 1234. . . 5678""") 1234 5678 >>> print(""". . . 1234. . . 5678""") ����� 1234 5678 escape ������ �new line ��� n เครอตราช รศ. กฤตวน ศรบรณ tripple quote ������ string ���������������� n ��������� �� newline ������� KMITL 01076249 Data Structures & Algorithms : Tree 2
string Repetition & Concatenation * string repetition + string concatenation >>> '1234''5678' '12345678' string literals ������ concat >>> 3 *'aa' + 'bcd' 'aaaaaabcd' >>> s 2 = '1234' >>> s 2 + '5678' >>> str = 'x' >>> 6 * str 'xxxxxx' รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ '12345678' ��� string variable s ������ �+ >>> s 3 = ('longxxxxx'. . . 'stillxxxxxxx'. . . 'finallyxxxxxx') >>> s 3 'longxxxxxstillxxxxxxxfinallyxxxxxx' string literals ������ string ��� KMITL 01076249 Data Structures & Algorithms : Tree 2
string Indexing (subscript), len() >>> s = '01234' >>> s[0] '0' s >>> s[-1] '4' >>> s[-2] '3' 0 1 2 3 4 -5 -4 -3 -2 -1 >>> s[9] Traceback (most recent call last): File "<stdin>", line 1, in <module> Index. Error: string index out of range >>> len(s) 5 รศ. ดร. บญธร ��� index access ������ -> ��������� index 0, 1 , . . . ������ -> ��������� index 1 -, 2 - , . . . len() returns length เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
str : immutable >>> s = '0123456789' >>> s[0] = 'a' str : immutable ������ int ��� float Traceback (most recent call last): File "<stdin>", line 1, in <module> Type. Error: 'str' object does not support item assignment รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
list : Repetition, Concatenation, len(), append(), nested lists >>> li = [1, 2] >>> lis = [3, 4, 5] [1, 2, 3] >>> 2*li + lis >>> li. append(3) >>> li. append([3, 4]) [1, 2, 3, 4, 5] >>> li [1, 2, 3] [1, 2, 3, [3, 4]] >>> len(li) >>> li[3] 2 [3, 4] nested list >>> li[3][1] 4 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Python List L = [ 1, 3, 7, 3 ] methods �������� len(L) 4 ����� list max(L) 7 �� max item, ���������� min(L) 1 �� min item, ���������� sum(L) 14 �� sum ��� item, ���� number L. count(3) 2 ���� 3 L. index(7) 2 �� index ��� 7 ������ L. reverse() [3 , 7 , 3 , 1] �������� L. clear() [] ����� empty list L. append(5) [1, 3, 7, 3, 5] insert object ������� list L. extend([6, 7]) [ 1 , 3 , 7 , 3 , 6, 7 ] insert list ������� list del L[1] [ 1, 7 , 3 ] remove item index 1 L. remove(3) [ 1, 7 , 3 ] remove item ������ = 3 L. insert(1, "Hi") [ 1 , "Hi", 3 , 7 , 3 ] insert new item ������� index ���� รศ. ดร. บญธร remove KMITL 01076249 Data Structures & Algorithms : Tree 2 L. pop(0) เครอตราช รศ. กฤตวน [ 3, 7 , 3 ศรบรณ ] & return item index 0 , ������ index
tuple class tuple ���� (��� type ��� ) ������� immutable )list : mutable ( t = (1, 2, 'hi') t = 1, 2, 'hi' print(t) (1, 2, 'hi') print(t[0]) 1 t 2 = t, (1, 2, 3) nest ed ������ ((1, 2, 'hi'), (1, 2, 3)) print(t 2) t 3 = ([1, 2], [3, 4]) รศ. ดร. บญธร can be ������� mutable �������� immutabl e print(t 3) [3, 4] t[0] = 5 Type. Error 'tuple' object does not support item assignment เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
range class range (a, b, s) return sequence a, a + 1 s, a + 2 s, a + 3 s, . . . , before b ของตวเลข upto but exclude end start step range type : ���� immutable sequence ��� numbers ����� loop : for print(list(range(0, 9, 3))) [ 0, 3, 6 ] print(list(range(5))) [ 0, 1, 2, 3, 4 ] argument n ���������� �� n ��� step 1 รศ. ดร. บญธร print(list(range(1, 5))) [ 1, 2, 3, 4 ] print(list(range(-10, -50, -20))) [ -10, -30 ] print(list(range(1, 0))) [] เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Sequence Operators : ( str, tuple, list , and range ) s[j] element at index j s[start: stop] slice including indices [start, stop) s[start: stop: step] slice including indices start, start + step, start + 2 step, . . . , up to but not equalling or stop s + t k s val in s val not in s concatenation of sequences s + s +. . . (k times) containment check non-containment check c = '{' c in ['(', '{', '['] returns True c in '({[' returns True 3 in range(0, 10) 3 in range(0, 10, 2) returns True returns False s = '0123456789' print(s[0: 5: 3]) list = list(range(0, 10)) print(list[0: 10: 2]) [0, รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ 03 2, 4, 6, 8] KMITL 01076249 Data Structures & Algorithms : Tree 2
dict class ������ key ����� retur n mutab dictionary / mapping le value map distinct immutable keys ��� values a = {'one': 1, 'two': 2, 'three': 3} print(a['one']) # index ��� key 1 Key. Error: 'four' print(a['four']) b = dict(one=1, two=2, three=3) c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) d = dict([('two', 2), ('one', 1), ('three', 3)]) e = dict({'three': 3, 'one': 1, 'two': 2}) print(a == b == c == d == e) print(a is b) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ same obj ? True False KMITL 01076249 Data Structures & Algorithms : Tree 2
set class KMITLskirt = {'blue', 'black'} print(KMITLskirt) {'black', print('blue' in KMITLskirt) True print('blue' not in KMITLskirt) False set ������� type ��������� mutable ���� 'blue'} frozens immutable ����� et ��� set ���� mutable immuta ble a = set('abc') b = set('ade') print(a) print(b) ∩ union {'a', 'c', 'b'} {'a', 'e', 'd'} print(a | b) {'a', 'c', 'e', 'b', 'd' } print(a & b) {'a'} {'c', 'b'} print(a - b) difference รศ. ดร. บญธร ���� set : ����� hash table -> optimized checking เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Set and Dictionary Operators : key in s containment check key not in s non-containment check s 1 == s 2 s 1 is equivalent to s 2 s 1 != s 2 s 1 is not equivalent to s 2 s 1 <= s 2 s 1 is subset of s 2 s 1 < s 2 s 1 is proper subset of s 2 s 1 >= s 2 s 1 is superset of s 2 s 1 > s 2 s 1 is proper superset of s 2 s 1 | s 2 the union of s 1 and s 2 s 1 & s 2 the intersection of s 1 and s 2 s 1 − s 2 the set of elements in s 1 but not s 2 s 1 ˆ s 2 the set of elements in precisely one of s 1 or s 2 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Operators Logical Operators : and, or, not short-circuit : a and b a or b if a == false ��� evaluate b a Equality Operators : is, is not, ==, != b float 5. 2 c same obj ? Comparison Operators : alias same value ? <, <=, >, >= float 5. 2 a is b returns True a is c returns False a == c returns True 3 <= 5 <= 10 returns True 'ad' < 'ad' returns True 5 < 'a' exception raise : ‘Type. Error’ รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Operator Precedence lowest precedence Operator Description lambda Lambda expression if - else Conditional expression or Boolean OR Logical Operators and Boolean AND not x Boolean NOT in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, Membership & Identitiy test Operators | Bitwise OR ^ Bitwise XOR Bitwise Operators & Bitwise AND << , >> Shifts - , + Addition and subtraction Arithematics Operators Multiplication, matrix multiplication division, % , // , @ , * remainder +x, -x, ~x Positive, negative, bitwise NOT ** Exponentiation await x Await expression Sequence Operators x[index], x[index: index], x(arguments. . . ), x. attribute Subscription, slicing, call, attribute reference highest precedence รศ. ดร. บญธร (expressions. . . ), [expressions. . . ], {key: value. . . }, {exp Binding or tuple display, list display, dictionary ressions. . . } display, set display เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
if if test expression: statement(s) Body of if if test expression: Body of if elif test expression: else: : ��������� Body of elif Body of else body block else: condition ����� Body of else �� ���� () score = int(input('input score: ')) if score < 50: print('fail') elif score == 50: print('Ohh!! almost fail') else: print('pass') รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
int() cast float() string str() ������� int if example x = int(input("Please enter an integer: ")) print(x, end ='') if x >= 0: if x == 0: print('=0') else: print('>0') level ��� nesting ������ indentation ���������� �� else: print('<0') รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
if example ������� x, y, z = 15, 7, 20 3 ��� if x > y > z : ����� ! print('max = ', x) elif y > x > z : print('max = ', y) else: print('max = ', z) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
while test expression: Body of while # initialize sum and counter sum, i = 0, 1 while i <= n: sum += i i += 1 print("The sum is", sum) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
for var ������� sequence for val in ����� sequence: iteration Body of for # Find sum of elements in list = [2, 1, 3, 4] sum = 0 for ele in list: # iterate over the list sum += ele = 10 Sum print("Sum =", sum) ? รศ. ดร. บญธร list[0] list[1] list[2] list[3] เครอตราช รศ. กฤตวน ศรบรณ = = 2 1 3 4 KMITL 01076249 Data Structures & Algorithms : Tree 2
for, range() for i in range(5): print(i, end = ' ') print() 0 1 2 3 4 s = 'abcdefghij' for i in range(len(s)): abcdefghij print(s[i], end = '') print() for i in range(1, 8, 3): beh print(s[i], end = '') print() รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
break , continue, else clauses on loops continue ������ for n in range(2, 10): iteration for x in range(2, n): ����� if n % x == 0: iteration break ������ loop ����� print(n, '=', x, '*', n//x) ������ break ����� else: ��� loop ���� else ����� for ���� while condition ���� false รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ 2 3 4 5 6 7 8 9 is prime = 2 * 2 is prime = 2 * 3 is prime = 2 * 4 = 3 * 3 # loop fell through without finding a factor print(n, 'is prime') KMITL 01076249 Data Structures & Algorithms : Tree 2
Function actual paramet er identif (formal) ier def paramete keywo ���� r list fn rd output Hello('Kritawan', 3) Hello Kritawan Hello('Boontee', 1) Hello Boontee Hello(5. 3, 2) Hello 5. 3 def Hello(name, n): for i in range(n): print('Hello, ', name) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
return output def triangle. Area(height, base): a = triangle. Area(20, 5) return 1/2 * height * base print(a) 50. 0 a, b, c = 5, 10, 15. 2 def add. One(x, y, z): return x+1, y+1, z+1 a, b, c = add. One(a, b, c) print(a, b, c) 6 11 16. 2 return ������� รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Passing Immutable Variable output รศ. ดร. บญธร def f(x): id(a) 499765776 a = 5 print('id(x)', id(x)) id(x) 499765776 print('id(a)', id(a)) x += 2 id(x) 499765808 f(a) print('id(x)', id(x)) 5 print(a) เครอตราช รศ. กฤตวน ศรบรณ x 7 a 5 KMITL 01076249 Data Structures & Algorithms : Tree 2
Passing Mutable variable output def f(x): id(a) 37745568 [5] a = [5] print('id(x)', id(x), x) id(x) 37745568 [5] print('id(a)', id(a), a) x. append(6) id(x) 37745568 [5, 6] f(a) print('id(x)', id(x), x) id(a) 37745568 [5, 6] print('id(a)', id(a), a) f a รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ [5] , 6] KMITL 01076249 Data Structures & Algorithms : Tree 2
Default Argument default value ����� evlauated ����� � function definition �� scope ��� define i = 5 7 def f( arg = i+2): print(arg) 0 arg = 0 print(arg) print('----') i = 6 f() ����� call fn formal arg. ����� bind ��� default value ���� output arg 7 0 -------3 0 -------7 0 ---- f(3) f() รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Default Argument default value ����� evlauated ���������� � default arg. ���� function mutable type definition �� scope ��� define 2 output def f(x, L = None): if L is None: L = [] L. append(x) return(L) output f() [] print(f(1)) [1] f() [] print(f(2)) [2] f([2]) [2] print(f(7, [5, 6])) [5, 6, 7] f() [1, 1] f() [] print(f(3)) [3] output def f(L = None): if L is None: L = [] print(L) L. append(1) f() [] f() def f( L = []): print(L) L. append(1) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
class Object : class Attribute 2 underscores print( Person. __doc__) Class Attributes: Person เปน class object print( Person. species) species: 'Homo Sapiens' class Person: __doc__: docstring """My first class""" """My first class""" eat(self, calorie) class Person share ทก Person 1. Attribute References : class. Obj. attribute. Name 2. Instantiation : สราง instance ใหมของ class. Obj() เครอตราช รศ. กฤตวน ศรบรณ species = 'Homo Sapiens' def eat(self, calorie): Person. eat print('eating', calorie, 'cal' ) class object �� 2 operations รศ. ดร. บญธร class definition def hi(): print('Hi') output: Person. hi() Hi KMITL 01076249 Data Structures & Algorithms : Tree 2
Instantiation, Instance Attribute, __init__(), __str__() constructor fn ����������� Attributes สำหรบ Instance Attributes: for each Person() instantiate empty object name & weight ? name pim = Person() Instantiation pim = Person('Pim', 50) Person Pim 50 Pea pea = Person('Pea', 45) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ self ������� obj ��������� pim = Person('Pim', 50) weight class Pim Person แตละคน 45 self ������� obj ��� reference ��� pim class Person: ����� pass ������ def __init__(self, n, ������ weight): method ����� self self. name = n argument ���� self. weight = weight def __str__(self): return self. name + ' weight = ' + str(self. weight) def eat(self, calorie): self. weight += calorie/500 print(pim) output: Pim weight = 50 pim. eat(500) print(pim) Pim weight = 51. 0 KMITL 01076249 Data Structures & Algorithms : Tree 2
Try Instance Attributes: Class Attributes: species: 'Homo Sapiens' name __doc__: """…………. """ __init__() __str__() weight ����� ��� attributes ����������� output ���� class Person money output: pim = Person('Pim', 500) print(pim) Pim weight = 50 money = 500 earn(self, n) pim. eat(500) print(pim) Pim weight = 51. 0 money = 500 spend(self, n) pim. earn(450) print(pim) earned 450 Pim weight = 51. 0 money = 950 pim. spend(45) print(pim) spent 45 Pim weight = 51. 0 money = 905 eat(self, calorie) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
class Person: """My first class""" species = 'Homo Sapiens' def __init__(self, n, weight, money): self. name = n self. weight = weight self. money = money def __str__(self): return self. name + ' weight = ' + str(self. weight) + ' money = ' + str(self. money) def eat(self, calorie): self. weight += calorie/500 def earn(self, n): print('earned', n) self. money += n def spend(self, n): print('spent', n) self. money -= n รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Inheritance living thing animal invertebrate plant vertebrate fish reptile mammal super class Person rabbit tiger is a Government Officer Employee Freelance sub class รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Inherit, Override 1. inheritance: class ��� inherits data + methods ��� class ����� 2. class ��� �� data + method ������ move() �������� vertebrate is a move() ��� �� � is a human bird �� � super class base class sub class derived class cannine move() ����� �() 2 �� �� � move() ���� 4 �� Python : ����� private variable ��� access outside ������� _ ����� 3. overriding : treat ���� non-public class ������ method ������� class ������ Python ���������� double ) ��� signature ����� (���� parameters return type(( underscore __ ? ? ) overrides method ������ ( รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ Python : �� virtual fun. , dynamic binding, abstract class ? ? KMITL 01076249 Data Structures & Algorithms : Tree 2
Inheritance, Overriding ��� command __init__() class Person: ������� def __init__(self, name, age): self. name = name self. age = age __str__(self) say() def __str__(self): return self. name + ', age = ' + str(self. age) def say(self, str): print(str) class Employee(Person): name Person age is a __init__() Employee __str__(self) id overridden method total. Emp = 0 def __init__(self, name, age): super(). __init__(name, age) Employee. total. Emp += 1 self. id = Employee. total. Emp def __str__(self): return 'p: ' + self. id + ' ' + super(). __str__() + ', id = ' + str(self. id) total. Emp class ��� �� data + method ������ output: p 1 = Employee('Natsha', 25) print(p 1) inheritance ���� : p 1. say('Hello') class ��� inherits ������ data + methods ��� class ����� print(Employee. total. Emp) p 1: Natsha, age = 25, id = 1 Hello 1 overriding ������ : p 2 = Employee('Dan', 22) class ������ method ������� class ������ print(p 2) )method ��� signature ����� (���� parameters return type(( print(Employee. total. Emp) )overrides method ������ ( p 2: Dan, age = 22, id = 2 2 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
https: //docs. python. org/3/howto/descriptor. html รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Meta. Class, Abstract Based Classes ABCs https: //docs. python. org/3/library/abc. html ABCMeta class My. ABC(metaclass=ABCMeta): pass My. ABC. register) from abc import (assert ) , My. ABC) assert , ()) รศ. ดร. บญธร My. ABC( เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
class Foo: def __getitem__(self, get_iterator(self): return index): . . . def __len__(self): . . . def metaclass=ABCMeta )self) class My. Iterable( ): @abstractmethod def __iter__(self): while False: yield None def get_iterator(self): return self . __iter__ cls, C): if cls is () @classmethod def __subclasshook__( My. Iterable: if __")iter__" in B. __dict__ for B in C. __mro__): return True return Not. Implemented รศ. ดร. บญธร My. Iterable. register(Foo( เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
https: //docs. python. org/3/reference/datamodel. html object. __radd__(self, other( object. __rsub__(self, other( object. __add__(self, other( object. __lt__(self, other( object. __le__(self, other( object. __eq__(self, other( object. __ne__(self, other( object. __gt__(self, other( object. __ge__(self, other( object. __sub__(self, other( object. __mul__(self, other( object. __matmul__(self, other( object. __truediv__(self, other( object. __floordiv__(self, other( object. __mod__(self, other( object. __divmod__(self, other( object. __pow__(self, other[, modulo([ x<y calls x. __lt__(y( object. __lshift__(self, other( object. __rshift__(self, other( object. __and__(self, other( object. __rmul__(self, other( object. __rmatmul__(self, other( object. __rtruediv__(self, other( object. __rfloordiv__(self, other( object. __rmod__(self, other( object. __rdivmod__(self, other( object. __rpow__(self, other( object. __rlshift__(self, other( object. __rrshift__(self, other( object. __rand__(self, other( object. __rxor__(self, other( object. __ror__(self, other( object. __xor__(self, other( object. __or__(self, other( - , +) , % , // , @ , * , divmod(), pow , () (| , ^ , & , << , >> , ** รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ with reflected (swapped) operands. KMITL 01076249 Data Structures & Algorithms : Tree 2
https: //docs. python. org/3/reference/datamodel. html object. __radd__(self, other( object. __rsub__(self, other( object. __rmul__(self, other( object. __rmatmul__(self, other( object. __rtruediv__(self, other( object. __rfloordiv__(self, other( These functions are only called if the left operand does not support the corresponding operation [3] and the operands are of different types. [4] For instance, to evaluate the expression x - y, where y is an instance of a class that has an __rsub__() method, y. __rsub__(x) is called if x. __sub__(y)returns Not. Implemented. object. __rmod__(self, other( object. __rdivmod__(self, other( object. __rpow__(self, other( object. __rlshift__(self, other( object. __rrshift__(self, other( object. __rand__(self, other( object. __rxor__(self, other( object. __ror__(self, other( with reflected (swapped) operands. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
object. __iadd__(self, other( object. __isub__(self, other( object. __imul__(self, other( object. __imatmul__(self, other( object. __itruediv__(self, other( object. __ifloordiv__(self, other( object. __imod__(self, other( object. __ipow__(self, other[, modulo([ x += y is to x =x. __iadd__(y ( equivalent object. __ilshift__(self, other( object. __irshift__(self, other( object. __iand__(self, other( object. __ixor__(self, other( object. __ior__(self, other( These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
object. __neg__(self( object. __pos__(self( object. __abs__(self( object. __invert__(self( Called to implement the unary arithmetic operations (-, +, abs() and. (~ object. __complex__(self( object. __int__(self( object. __float__(self( object. __round__(self[, n([ Called to implement the built-in functions complex(), int(), float() and round(). Should return a value of the appropriat รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
object. __index__(self( Called to implement operator. index() , and whenever Python needs to losslessly convert the numeric object to an integer object (such as in slicing, or in the builtin bin(), hex() and oct() functions). Presence of this method indicates that the numeric object is an integer type. Must return an integer. Note In order to have a coherent integer type class, when __index__() is defined __int__() should also be defined, and both should return the same value. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
object. __enter__(self( Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. object. __exit__(self, exc_type, exc_value, traceback( Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None. If an exception is supplied, and the method wishes to suppress the exception (i. e. , prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method. Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
scope def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam = "nonlocal spam" def do_global(): global spam = "global spam" spam = "test spam" do_local() print("After local assignment: ", spam) do_nonlocal() print("After nonlocal assignment: ", spam) do_global() print("After global assignment: ", spam) scope_test() print("In global scope: ", spam) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2
Python Version Text • Free Book: http: //interactivepython. org/courselib/st atic/pythonds/index. html • https: //www. amazon. com/Problem-Solving -Structures-Algorithms. Python/dp/1541128257/ref=sr_1_5? ie=U TF 8&qid=1483445752&s=books&sr=1 -5 • https: //www. amazon. com/Problem-Solving -Algorithms-Structures. Python/dp/1590282574/ref=pd_bxgy_14 _img_2? _encoding=UTF 8&pd_rd_i=15902 82574&pd_rd_r=6 TRCTXQRF 26 DB 6 NQF HDW&pd_rd_w=b. Ba. UI&pd_rd_wg=r. KP 7 Z &psc=1&ref. RID=6 TRCTXQRF 26 DB 6 NQF HDW Paperback: 438 pages Publisher: Franklin, Beedle & Associates; 2 nd edition (August 22, 2011) Product Dimensions: 7. 5 x 0. 9 x 9. 2 inches • • รศ. ดร. บญธร ISBN-13: 978 -1590282571 ISBN-10: 1590282574 เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 271
Python Visual Studio 1. Visual Studio Python Tutorial 1/6: Setting up Visual Studio for Python Development https: //www. youtube. com/watch? v=_ok. UV 47 e. M 5 c&index=1&list=PLRe. L 099 Y 5 n. Rd. Lg. G Adrb_Ye. Td. End 23 s 6 Ff 2. Visual Studio Python Tutorial 2/6: Start coding in Python using Visual Studio https: //www. youtube. com/watch? v=KHPo. Vp. L 7 z. Hg&index=2&list=PLRe. L 099 Y 5 n. Rd. Lg. G Adrb_Ye. Td. End 23 s 6 Ff 3. Visual Studio Python Tutorial 3/6: Editing Python code using Visual Studio https: //www. youtube. com/watch? v=u. ZGZNEyye. Ks&index=3&list=PLRe. L 099 Y 5 n. Rd. Lg. G Adrb_Ye. Td. End 23 s 6 Ff 4. Visual Studio Python Tutorial 4/6: Debugging https: //www. youtube. com/watch? v=b. O 7 wpzgy 74 A&list=PLRe. L 099 Y 5 n. Rd. Lg. GAdrb_Ye. T d. End 23 s 6 Ff&index=4 5. Visual Studio Python Tutorial 5/6: Interactive Python https: //www. youtube. com/watch? v=yc 2 CROt. Ts. C 0&list=PLRe. L 099 Y 5 n. Rd. Lg. GAdrb_Ye. Td End 23 s 6 Ff&index=5 6. Visual Studio Python Tutorial 6/6: Building a Website https: //www. youtube. com/watch? v=FJx 5 mutt 1 uk&index=6&list=PLRe. L 099 Y 5 n. Rd. Lg. GA drb_Ye. Td. End 23 s 6 Ff รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 272
Python : Interpreter Python is an interpreted language. Compiler Interpreter Compiler Takes Entire program as input Interpreter Takes Single instruction as input . Intermediate Object Code is Generated No Intermediate Object Code is Generated Conditional Control Statements are Executes faster Conditional Control Statements are Executes slower More Memory Requirement (Since Object Code is Generated) Less Memory Requirement Program need not be compiled every time Every time higher level program is converted into lower level program Errors are displayed after entire program is Errors are displayed for every instruction checked interpreted (if any) Example : C Compiler รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ Example : Python KMITL 01076249 Data Structures & Algorithms : Tree 273
- Slides: 73