Python Basics
cheatsheet
Expression & Variables
Data Types
- String
- Float
- Integer
- Booleank
String
below are string method
- string indexing
- slice
- create new string
- upper and lower
- strip 篩除空格/lstrip 刪除左方空格/rstrip 刪除右方空格
- count 計算字串內的字母數量
- endswith 檢查 String 的結尾
- isnumeric 檢查 string 是否都是數字
- int 將 string 轉換成數字
- join 插入
- split 分割
formatting strings
比 str()
更好用的 string 轉換器

EXAMPLES of String
Lists & Tuples
x = ["Now", "we", "are"]
- check the list length
len(x)
- check if the element is in the list
"are" in x
- check the spesific position in the list
print(x[0])
- List 與 String 同屬於sequence,都能使用
- for elemrnt in sequence
- sequence[x]
- len(sequence)
- sequence + sequence
- element in sequence
- lists 與 string 的不同點在於:lists is mutable(能直接在list內更改element)
enumerate
- list comprehension
Modify The Content Of A List
.append("element")
.insert(index, "element")
.remove("element")
.pop(index)
Lists And Tuples
Tuple 的特色
- 順序性
- elements 可以是任何資料型態
- immutable,不可改變
- tuple 的「位置順序」是有意義的
fruits = ['apple', 'pineapple', 'melon']
是 string
fruits = ('apple', 'pineapple', 'melon')
是 tuple
- 使用 unpack 方式分割 tuple
EXAMPLES of Lists & Tuple
def group_list(group, users):
members = ",".join(users)
return group + ": " + members
print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"]))
print(group_list("Engineering", ["Kim", "Jay", "Tom"]))
print(group_list("Users", ""))
def skip_elements(elements):
new_elements = []
length = len(elements)
for i in range(0, length, 2):
new_elements.append(elements[i])
return new_elements
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
print(skip_elements([]))
def guest_list(guests):
for guest in guests:
name, age, role = guest
print("{name} is {age} years old and works as {role}".format(name=name, age=age, role=role))
def skip_elements(elements):
new_elements = []
for index, element in enumerate(elements):
if index % 2 == 0:
new_elements.append(element)
return new_elements
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
def full_emails(people):
result = []
for email, name in people:
result.append("{} <{}>".formate(name, email))
return result
print(full_emails(['tcmiss@gmail.com', 'TC Huang'], ['brian@gmail.com', 'Brian Wu']))
def skip_elements(elements):
return [element for element in elements if elements.index(element) % 2 == 0]
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
Common sequence operations
- len(sequence) Returns the length of the sequence
- for element in sequence Iterates over each element in the sequence
- if element in sequence Checks whether the element is part of the sequence
- sequence[i] Accesses the element at index i of the sequence, starting at zero
- sequence[i:j] Accesses a slice starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(sequence) by default.
- for index, element in enumerate(sequence) Iterates over both the indexes and the elements in the sequence at the same time
List-specific operations and methods
- list[i] = x Replaces the element at index i with x
- list.append(x) Inserts x at the end of the list
- list.insert(i, x) Inserts x at index i
- list.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.
- list.remove(x) Removes the first occurrence of x in the list
- list.sort() Sorts the items in the list
- list.reverse() Reverses the order of items of the list
- list.clear() Removes all the items of the list
- list.copy() Creates a copy of the list
- list.extend(other_list) Appends all the elements of other_list at the end of lis
List comprehension
- [expression for variable in sequence] Creates a new list based on the given sequence. Each element is the result of the given expression.
- [expression for variable in sequence if condition] Creates a new list based on the given sequence. Each element is the result of the given expression; elements only get added if the condition is true.
x = {"key":value, "key2":value2}
Operations
- len(dictionary) - Returns the number of items in the dictionary
- for key in dictionary - Iterates over each key in the dictionary
- for key, value in dictionary.items() - Iterates over each key,value pair in the dictionary
- if key in dictionary - Checks whether the key is in the dictionary
- dictionary[key] - Accesses the item with key key of the dictionary
- dictionary[key] = value - Sets the value associated with key
- del dictionary[key] - Removes the item with key key from the dictionary
Methods
- dict.get(key, default) - Returns the element corresponding to key, or default if it's not present
- dict.keys() - Returns a sequence containing the keys in the dictionary
- dict.values() - Returns a sequence containing the values in the dictionary
- dict.update(other_dictionary) - Updates the dictionary with the items coming from the other dictionary. - Existing entries will be replaced; new entries will be added.
- dict.clear() - Removes all the items of the dictionary
Dictionaries is mutable 更改
Variables
- length, width, area are variables
- variable 命名限制
- 不能使用 Python 內建的關鍵字或 function 名稱
- 不能使用空白格
- 必須以
字母
或_
當開頭
- 只能以
字母
、_
與 數字
組成變數名稱
Type Conversion
Function
- function name = greeting
- paremeter = name
- body(action)
Value
Condition
*練習題
Loops
While Loops
寫 Loop 該注意的事項
- 確認variables 是否都被定義了
- 確認是否有 break 的條件
common errors in Loops: initialize the variables
忘了先定義 variable
以 Loop 做質因數分解
以下程式能找出組成 number 的所有質因數。
例如:number = 100,其質因數是 2, 2, 5, 5,因為 2x2x5x5 = 100。
n 是否為 2 的次方?
- 檢查 n 是否能被 2 整除
- 若能被 2 整除
- 讓 n 再除以 2(排除 6, 10 等非 2 次方數字)
- 若 n 除以 2 之後的數字,能被 2 整除,且 n 不等於 0
For Loop
-
range function
- start by 0
- a list of numbers will be less than the given value
x 會從 0 開始到 4,0, 1, 2, 3, 4
,總共 5 個項目,最後一個 x 一定是 range 數字 - 1
-
examples
range()
的用法
- range(n): 0, 1, 2, … n-1
- range(x,y): x, x+1, x+2, … y-1
- range(p,q,r): p, p+r, p+2r, p+3r, … q-1 (if it's a valid increment)
Nested For Loops
- 雙重循環的概念
- Newline Character:
end=""
能自動換行
- 在
for right in range(left, 7):
會將 range
數字跑完。

for loops 的自動化應用
- copy files to machines
- process the contents of files
- automatically install software
各種 Loop 的使用時機
- for loops 適合有列表元素的任務
- while loops 適合有條件式的重複性任務
Recursion
- Recursion is common in soft-ware but rare in automation.
- Recursion is the repeated application of the same procedure to a smaller problem,
- can tackle complex problems by reducing to a simpler one.
- 會有一個 base-case 設定最低值,運作方式會從 base-case 開始,一直累計到 n
- 會在 function recall 自己
- 適合用在有多層套疊的情境(例如俄羅斯娃娃、多層資料夾)
Recursive 使用情境
- 適合:active directory, LDAP
- 不適合:超過 1000 次執行次數的項目,就無法使用