204217 Computer Programming Languages Python Lecture 2 Types

  • Slides: 34
Download presentation
204217: Computer Programming Languages (Python) Lecture 2 Types, Literals, Variables, Operators, and Expressions Assembled

204217: Computer Programming Languages (Python) Lecture 2 Types, Literals, Variables, Operators, and Expressions Assembled for 204217 by Kittipitch Kuptavanich

204217: Computer Programming Languages (Python) Some Built-in Types 01 # Some Builtin Types 02

204217: Computer Programming Languages (Python) Some Built-in Types 01 # Some Builtin Types 02 import math. . . 05 def f(): 06 print("This is a user-defined function") 07 08 print("Some basic types in Python: ") 09 print(type(2)) # int 10 print(type(2 ** 500)) # long int 11 print(type(2. 2)) # float 12 print(type("2. 2")) # str (string) 13 print(type(2 < 2. 2)) # bool (boolean) 14 print(type(math)) # module 15 print(type(math. tan)) # builtin_function_or_method 16 print(type(f)) # function (user-defined function) 17 print(type(42))) # type 4

204217: Computer Programming Languages (Python) Some Built-in Types [2] 23 24 25 26 27

204217: Computer Programming Languages (Python) Some Built-in Types [2] 23 24 25 26 27 28 29 30 31 32 33 34 35 36 print("Later in the course. . . ") print(type(Exception())) # Exception print(type(range(5))) # range print(type([1, 2, 3])) # list print(type((1, 2, 3))) # tuple print(type({1, 2})) # set print(type({1: 42})) # dict (dictionary or map) print(type(2 + 3 j)) # complex (complex number) # Some Builtin Constants print("Some builtin constants: ") print(True) print(False) print(None) 5

Aside 204217: Computer Programming Languages (Python) Expressions and Statements • An expression is a

Aside 204217: Computer Programming Languages (Python) Expressions and Statements • An expression is a combination of values, variables, and operators. • An expression can be evaluated to a value เราสามารถประเมนคา ของ Expression ได • A statement is a unit of code that the Python interpreter can execute. Statement คอหนวยยอยของชด คำสง ท Python Interpreter ดำเนนการได • For example, >>> x = 3 # statement >>> x == 3 # expression assignment statement True • Expression has value; >>> x # expression 3 a statement does not. 7

204217: Computer Programming Languages (Python) Variables [2] >>> the. Sum = 0 >>> the.

204217: Computer Programming Languages (Python) Variables [2] >>> the. Sum = 0 >>> the. Sum = the. Sum + 1 >>> the. Sum = True >>> the. Sum True ในภาษา Programmingหลายๆ ภาษาเชน Python ชนดของตวแปร สามารถเปลยนแปลงไ ด (Dynamic Typing) 1 8

Aside 204217: Computer Programming Languages (Python) Python Keywords False as continue else from in

Aside 204217: Computer Programming Languages (Python) Python Keywords False as continue else from in not return yield None assert def except global is or try True break del finally if lambda pass while and class elif for import nonlocal raise with • เราสามารถแสดง list ของ keyword ไดโดยการใชคำสง >>> import keyword >>> keyword. kwlist 10

204217: Computer Programming Languages (Python) Numeric and Boolean Operators Category Arithmetic Relational Bitwise Operators

204217: Computer Programming Languages (Python) Numeric and Boolean Operators Category Arithmetic Relational Bitwise Operators Assignment +=, -=, *=, //=, **=, %=, <<=, >>=, &=, |=, ^= Logical and, or, not +, -, *, /, //, **, %, - (unary), + (unary) <, <=, >, ==, !=, <<, >>, &, |, ^, ~ Note • • / is normal division // is floored division • ** is power Think Python: How to Think Like a Computer Scientist 3 / 2 == 1. 5 3 // 2 == 1 -3 // 2 == -2 12

204217: Computer Programming Languages (Python) Types Affect Semantics >>> print(3 * 2) 6 >>>

204217: Computer Programming Languages (Python) Types Affect Semantics >>> print(3 * 2) 6 >>> print(3 * "abc") abcabcabc >>> print(3 + 2) 5 >>> print("abc" + "def") abcdef >>> print(3 + "def") Type. Error: unsupported operand type(s) for +: 'int' and 'str' 13

204217: Computer Programming Languages (Python) Operator Precedence • >>> 2**3**5 == (2**3)**5 ______ >>>

204217: Computer Programming Languages (Python) Operator Precedence • >>> 2**3**5 == (2**3)**5 ______ >>> 2**3**5 == 2**(3**5) ______ 15

204217: Computer Programming Languages (Python) Operator Precedence [2] Operator Description (expressions. . . ),

204217: Computer Programming Languages (Python) Operator Precedence [2] Operator Description (expressions. . . ), [expressions. . . ], {key: value. . . }, {expressions. . . } Binding or tuple display, list display, dictionary display, set display x[index], x[index: index], x(arguments. . . ), x. attribute Subscription, slicing, call, attribute reference ** +x, -x, ~x *, /, //, % +, <<, >> & ^ | in, not in, is not, <, <=, >, >=, !=, == not x and or if – else lambda Exponentiation high Mathematical Operators Positive, negative, bitwise NOT Multiplication, division, remainder Addition and subtraction Shifts Bitwise AND Bitwise XOR Bitwise OR Comparisons, including membership tests and identity tests Boolean NOT Boolean AND Boolean OR Conditional expression Lambda expression low 16

204217: Computer Programming Languages (Python) Boolean Expressions • Boolean Expression คอ Expression ทมคาเปน True

204217: Computer Programming Languages (Python) Boolean Expressions • Boolean Expression คอ Expression ทมคาเปน True (จรง ) หรอ False (เทจ ) >>> 5 == 5 True >>> 5 == 6 False • คา True หรอ False เปนคาเฉพาะทมาจากชนดขอมล >>>(และไมใช type(True) string) bool <class 'bool'> >>> type(False) <class 'bool'> 17

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Boolean Expressions [2]

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Boolean Expressions [2] • เครองหมาย == เปนหนงใน Operator ทางความสมพนธ (Relational Operator) • Relational Operator อนๆ ไดแก x x x != y > y < y >= y <= y # # # x x x is is is not equal to greater than less than y greater than less than or y y or equal to y • หากตองการเขยน Expression ขามบรรทด สามารถทำไดโดยการใชเครองหมาย Backslash () >>> x = 8 >>> หรอวงเลบ x = 8 >>> (x + 4 < 10 and x % 2 != 1) False >>> x + 4 < 10 and x % 2 != 1 False 18

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Boolean Expressions [2]

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Boolean Expressions [2] • Floating-point Number Comparisons >>> print(0. 1 + 0. 1 == 0. 2) True # True, but. . . >>> print(0. 1 + 0. 1 == 0. 3) False >>> print(0. 1 + 0. 1) 0. 3 # seems ok >>> print((0. 1 + 0. 1) - 0. 3) 5. 55111512313 e-17 # (tiny, but non-zero!) • คาทเกบในตวแปรชนด เปนคาประมาณ !! float 19

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Floating-Point Numbers and

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Floating-Point Numbers and almost_equal() 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 d 1 = 0. 1 + 0. 1 d 2 = 0. 3 print(d 1 == d 2) epsilon = 10 ** -10 print(abs(d 2 - d 1) < epsilon) # still False, of course # True! # Once again, using an almost. Equal function # (that we will write) def almost. Equal(d 1, d 2, epsilon=10 ** -10): return (abs(d 2 - d 1) < epsilon) d 1 = 0. 1 + 0. 1 d 2 = 0. 3 print(d 1 == d 2) # still False, of course # True, and now packaged in a handy reusable function! print(almost. Equal(d 1, d 2)) 20

204217: Computer Programming Languages (Python) Operator Precedence [2] Operator Description (expressions. . . ),

204217: Computer Programming Languages (Python) Operator Precedence [2] Operator Description (expressions. . . ), [expressions. . . ], {key: value. . . }, {expressions. . . } Binding or tuple display, list display, dictionary display, set display x[index], x[index: index], x(arguments. . . ), x. attribute Subscription, slicing, call, attribute reference ** +x, -x, ~x *, /, //, % +, <<, >> & ^ | in, not in, is not, <, <=, >, >=, !=, == not x and or if – else lambda high Exponentiation Positive, negative, bitwise NOT Multiplication, division, remainder Addition and subtraction Shifts Bitwise AND Bitwise XOR Bitwise OR Comparisons, including membership tests and identity tests Boolean NOT Boolean AND Boolean OR Conditional expression Lambda expression low 22

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Short-Circuit Evaluation [2]

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Short-Circuit Evaluation [2] >>> x = 1 >>> y = 0 >>> print((y != 0) and ((x / y) != 0)) False >>> print(((x / y) != 0) and (y != 0)). . . Zero. Division. Error: division by zero >>> print((y == 0) or ((x / y) == 0)) True >>> print(((x / y) == 0) or (y == 0)). . . Zero. Division. Error: division by zero # Works! # Crashes! 24

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Short-Circuit Evaluation [3]

204217: Computer Programming Languages (Python) http: //www. cs. cmu. edu/~112/notes-data-and-exprs. html Short-Circuit Evaluation [3] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 def is. Positive(n): result = (n > 0) print("is. Positive(", n, ") =", result) return result def is. Even(n): result = (n % 2 == 0) print("is. Even(", n, ") =", result) return result print("Test 1: is. Even(-4) and is. Positive(-4)") print(is. Even(-4) and is. Positive(-4)) # Calls both print("-----") print("Test 2: is. Even(-3) and is. Positive(-3)") print(is. Even(-3) and is. Positive(-3)) # Calls only one 25

204217: Computer Programming Languages (Python) Truth Value Testing • ในภาษา Python, Object ทกตวม Truth

204217: Computer Programming Languages (Python) Truth Value Testing • ในภาษา Python, Object ทกตวม Truth Value ทงหมด (สามารถ Evaluate เปน True หรอ False ได ) • Value ดงตอไปน Evaluate เปน False (ทเหลอเปน True) • None • False • zero of any numeric type, for example, 0, 0 j. • any empty sequence, for example, '', (), []. • any empty mapping, for example, {}. • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False. 26

204217: Computer Programming Languages (Python) Boolean Arithmetic 02 03 04 05 06 07 08

204217: Computer Programming Languages (Python) Boolean Arithmetic 02 03 04 05 06 07 08 09 10 # In numeric expressions. . . # True is treated as 1 # False is treated as 0 # So. . . print(5 * * + + True) False) # # 5 0 6 5 • ไมควรใช Boolean Arithmetic เนองจากทำให อานยาก แตหากจำเปนควรมการ Cast ชนด int()# กอน 07 ดวยฟงกชน print(5 * int(True)) 5 Code 08 print(5 * int(False)) # 0 09 print(5 + int(True)) # 6 10 print(5 + int(False)) # 5 28

204217: Computer Programming Languages (Python) Bitwise Operations ตวอยาง • ให a = [0110] และ

204217: Computer Programming Languages (Python) Bitwise Operations ตวอยาง • ให a = [0110] และ b = [1100] • ในการทำ bitwise operation a & b, a | b, a ^ b, และ ~b จะไดผลลพธดงน ทำ Operation & ในแตละหลกแย กกน 29

204217: Computer Programming Languages (Python) Bitwise Operations [2] # 0 1 1 0 =

204217: Computer Programming Languages (Python) Bitwise Operations [2] # 0 1 1 0 = 4 + 2 = 6 # 0 1 = 4 + 1 = 5 >>> print("6 & 5 =", (6 & 5)) 6 & 5 = ______ >>> print("6 | 5 =", (6 | 5)) 6 | 5 = ______ >>> print("6 ^ 5 =", (6 ^ 5)) 6 ^ 5 = ______ >>> print("6 << 1 =", (6 << 1)) 6 << 1 = ______ >>> print("6 << 2 =", (6 << 2)) 6 << 2 = ______ >>> print("6 >> 1 =", (6 >> 1)) 6 >> 1 = ______ 30

204217: Computer Programming Languages (Python) References • https: //docs. python. org/3/library/stdtypes. html • https:

204217: Computer Programming Languages (Python) References • https: //docs. python. org/3/library/stdtypes. html • https: //docs. Python. org/3. 4/reference/expressions. html • https: //docs. Python. org/3. 4/tutorial/inputoutput. html • https: //docs. Python. org/3. 4/library/stdtypes. html#old-string -formatting • http: //www. cs. cmu. edu/~112/notes-data-andexprs. html • Miller, B. , and Ranum, D. Problem Solving with Algorithms and Data Structures Using Python, • Guttag, John V. Introduction to Computation and Programming Using Python, Revised 36