Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Python Programming Concept

1,510 views

Published on

Python Programming

Published in: Education
  • Be the first to comment

Python Programming Concept

  1. 1. Python Programming Concept 17 December 2019
  2. 2. Outline Python 簡介 變數與動態資料型別 運算式 序列資料結構- list, tuple, range 流程控制 非序列資料結構-set, dict 函數與變數命名空間 例外處理 檔案處理(txt, csv, python, pickle) 模組與套件 類別設計 2 Anaconda 安裝教學 http://bit.ly/2IA3 qaQ
  3. 3. TIOBE Index for November 2019 3https://www.tiobe.com/tiobe-index/
  4. 4. 2019 IEEE Spectrum Top 10 Language 4 大多的Machine Learning 軟體框架中都支援 Python
  5. 5. Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object- oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. https://www.python.org/ What is Python? 5
  6. 6. Interpreted language v.s. Compiled language Object-Oriented language Dynamic type v.s. Static type Reference Counting and Cycle detecting garbage collector for memory management 6
  7. 7. Run the program directly without compile it Compiled language first compile the whole program into machine language (executables) We can execute commands one by one in python shell Interpreted language 7
  8. 8. What is an object? • An object can be a variable, a data structure, a function, a method. • A location in memory having a value and referenced by an identifier. Every thing in python is an object,including primitive types (int, float, string…) Object Oriented programming 8
  9. 9. Whitespace is meaningful in python: • Indentation defines block in python • Use 4-space indentation, and no tabs. • Placement of newline ends a statement. • Semicolon is not required • No braces {} required to mark blocks of code. • Often a colon appears at the start of a new block • Use when must go to next line prematurely • Single line comment # ……….. • Multi line comment ‘’’ ……….. ‘’’ White space matters! 9
  10. 10. https://www.python.org/downloads/ 本課程建議使用ipython, 請參考連結 “Anaconda安裝” http://bit.ly/2IA3qaQ Installing Python 10
  11. 11. Interactive mode • Simply type ipython in the shell • Type “Ctrl-D” to exit interactive mode • The definition to functions and variables are lost when you close the interpreter Execute a script • Run python script  “python xxxx.py” Using the Python Interpreter 11
  12. 12. Python 程式架構 12
  13. 13. Python 程式架構 (cont.) 13
  14. 14. 變數與資料型態
  15. 15. Dynamic type => no declaration needed x = 3 (x is an int) x = “This is a string” (x is a string) x = [1, 2, 3, 4, 5] (x is a list) …. Variable naming: • Case sensitive • Cannot start with number • Can contain letters, numbers, and underscores. Variables 15
  16. 16. The type of a python variable (represented by an identifier) is determined at runtime. i.e., the program loader does not know the type of the variable when loading the program The same variable (identifier) can be different types at different time during program execution. Late binding • Avoid too overwhelming type information • Handle type difference between platforms • The variable cast and access should pass lots of test to ensure the operation is valid. • Drastically decreases the performance Dynamic type 16
  17. 17. In C/C++, a variable is an allocated memory segment to store the information of the value In python, a variable is like an identifier of a memory segment What actually happens when python executes the statement x = 3? • An instance of int object of value 3 is created in memory. The identifier “x” is created and stored into the name list. The reference to the int object is then bind to identifier “x” Variables 17
  18. 18. Python 的變數僅是標籤 18 X=3 X=5 5X3X X=3 X=5 3 X 5 3X C Python C的變數代表記憶體位址 try it: x=3 id(x) = ? id(3) =? x is 3 ? x=5 id(x) = ? id(5) = ? id(3) =? immutable object is just to create a new one, rather than changing the old one.
  19. 19. Mutable v.s. Immutable 19 就是指constant value: number, strings, tuple
  20. 20. 20 3 50 1 a=[3,3,1] a[0]=50 容器內記錄了其他的物件 [ 3,3,1 ]a immutable object (can't be changed)
  21. 21. 21 3 100 a=[3,3,[100,200]] a[2][0]=200 容器內記錄了其他的物件 [ 3,3,[100,200 ]]a 200 immutable object (can't be changed)
  22. 22. The value of immutable object cannot be changed But why can we still write ? x = 3; x = 1; x = x + 1; What happened if we write x = “ dead “; x += “beef “; Immutable object 22 3 1 2x “dead” “beef” “deadbeef”x
  23. 23. “tuple” 是一個不可改變內容的容器 immutable object 23
  24. 24. mutable object 24 mutable object 是一個可以改變內容的 Container . 其所在的空間內容可改變
  25. 25. Literals are notations for constant values of some built-in types. False、True None • None is frequently used to represent the absence of a value, as when default arguments are not passed to a function Built-in Constants 25
  26. 26. Bool : True and False Numeric : int, float, complex Sequence : list, tuple, range Text Sequence : “Hi ! hello world” Binary Sequence : bytes, bytearray Set : set, frozenset Mapping : dict Data Type 26
  27. 27. Number 27
  28. 28. 28
  29. 29. In interactive mode, the last printed expression is assigned to the variable _. Float 29
  30. 30. city = "Amsterdam" country = "Netherlands” 輸出型式 ==> City Amsterdam is in the country Netherlands 傳遞引數的值 print("City", city, 'is in the country', country) 格式化字串 • 順序傳遞 print(“City {} is in the country {}”.format( city, country)) • 建立數字索引 print(“City {1} is in the country {0}, yes, in {0} ” .format( country, city) ) • 多個引數組成元組來傳遞引數 print(“City %s is in the country %s” %( city, country )) • 不要換行 print('………..', end=' ') 基本輸出 print 30
  31. 31. input()讀進來都是string 基本輸入 input 31
  32. 32. Non-Sequence DataType list, tuple, range
  33. 33. Summary 33 index
  34. 34. The operations in the following table are supported by most sequence types, both mutable and immutable Common Operations for sequence type 34
  35. 35. Lists are mutable sequences, typically used to store collections of homogeneous items Lists may be constructed in several ways: • Using a pair of square brackets to denote the empty list: [] • Using square brackets, separating items with commas: [a], [a, b, c] • Using a list comprehension: [x for x in iterable] • Using the type constructor: list() or list(iterable) • Lists implement all of the common and mutable sequence operati List 35
  36. 36. Boolean test whether a value is inside a container Example: ‘in’, ‘not in’ operator 36 dict: 比的是key 而不是value
  37. 37. Example: + operator 37
  38. 38. List example : Slicing for mutable object 38
  39. 39. List example : Slicing for mutable object 39
  40. 40. Common Operations for ‘mutable’ type 40 b=[1,2,3] b[0:2]=[10,20] b  [10,20,3]
  41. 41. List Example 41
  42. 42. List Example 42
  43. 43. List Example 43
  44. 44. Stack=> Last In First Out Using Lists as Stack 44
  45. 45. Queue=> Fist In First Out Using Lists as Queue 45
  46. 46. List comprehensions provide a concise way to create lists, common applications are • To make new lists where each element is the result of some operations applied to each member of another sequence or iterable • To create a subsequence of those elements that satisfy a certain condition List comprehension 46
  47. 47. The rule of list comprehension [mapping-expression for element in source-list if filter- expression] Some examples List comprehension 47
  48. 48. The mapping-expression can be as complicated as you want, can also be another list comprehension Example: List comprehension 48
  49. 49. Example: List comprehension 49
  50. 50. The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops. Ranges implement all of the common sequence operations except concatenation and repetition Ranges 50
  51. 51. Tuples are immutable sequences, typically used to store collections of heterogeneous data Tuples may be constructed in a number of ways: • Using a pair of parentheses to denote the empty tuple: () • Separating items with commas: a, b, c or (a, b, c) • Using a trailing comma for a singleton tuple: a, or (a,) • Using the tuple() built-in: tuple() or tuple(iterable) • Tuples implement all of the common sequence operations. Tuple: Read-only List 51
  52. 52. x=[(1,2),(3,4)] x[0][0]=100 #Error x[0]=100 #OK -------------------------------------------------------------------- x=([1,2],[3,4]) x[0]=100 #Error x[0][0]=100 x ([100,2],[3,4]) 了解immutable 的意思 52 [1,2] [3,4] 100Errorx is tuple
  53. 53. Non-Sequence DataType Dict & Set
  54. 54. “associative arrays” : { key: value pair, } How to use Dict? Dictionaries 54
  55. 55. Example 55 補充: 使用 dict get()方法: dict.get(key, default=None) tel. get(‘jack’)  4098 tel. get(‘joseph’)  None s.update(x) for dict 讀取不存在的 tel[‘joseph’]  是錯誤 設定不存在的tel[‘joseph’] =100  叫新增
  56. 56. Dict constructor and comprehension 56
  57. 57. A set is an unordered collection with no duplicate elements To create an empty set you have to use set(), not {} Set 57
  58. 58. Set comprehension 58
  59. 59. Looping Techniques 59
  60. 60. Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering 0 equals 0.0 Comparing Sequences and Other Types 60

×