Python Basics

tags: Python

cheatsheet

Expression & Variables

Data Types

  • String
  • Float
  • Integer
  • Booleank
print("Sting")  #String
print(7 + 8)    #15
print(7 + "8")  #TypeError

# 使用 type() 查詢 data types
print(type("a"))  #<class 'str'>
print(type(2))  #<class 'int'>
print(type(2.5))  #<class 'float'>

String

below are string method

  • string indexing
    ​​​​name = "Jalen"
    ​​​​print(name[1]  # a
    ​​​​print(name[0]) # J
    ​​​​
    ​​​​# check the position of the elements in a string
    ​​​​name.index("l")  # 2
    ​​​​pets = "Cats & Dogs"
    ​​​​pets.index("Dog")  # 7
    ​​​​pets.index("s")  # 3,雖然有兩個s,只會返回第一個 s 的所在位置
    ​​​​
    ​​​​# check if the element is in a string
    ​​​​"Dragons" in pets. #因為 pets 內沒有 Dragon,顯示 False
    
  • slice
    ​​​​fruit = "Pineapple"
    ​​​​print(fruit[:4])  #Pine
    ​​​​print(friut[4:])  #apple
    
  • create new string
    ​​​​message = "A kong string with a silly typo"
    ​​​​message[2] = "l"  #error, 因為 string is immutable,需用以下方式
    ​​​​
    ​​​​new_message = message[0:2] + "l" + mssage[3:]
    ​​​​#correct, result: A long string with a silly typo
    
  • upper and lower
    ​​​​"Mountains".upper()  #MOUNTAINS
    ​​​​"Mountains".lower()  #mountains
    
  • strip 篩除空格/lstrip 刪除左方空格/rstrip 刪除右方空格
    ​​​​" yes ".strip()  #'yes'
    ​​​​" yes ".lstrip() #'yes '
    ​​​​" yes ".rstrip() #' yes'
    
  • count 計算字串內的字母數量
    ​​​​"The number of times e occurs in this string is 4".count("e")
    ​​​​
    ​​​​#result: 4
    
  • endswith 檢查 String 的結尾
    ​​​​"Forest".endswith("rest")  #True
    
  • isnumeric 檢查 string 是否都是數字
    ​​​​"Forest".isnumeric() #False
    ​​​​"12345".isnumeric()  #True
    
  • int 將 string 轉換成數字
    ​​​​int('12345') + int('54321')
    ​​​​# 66666
    ​​​​# 因為 12345 + 54321 = 66666
    
  • join 插入
    ​​​​" ".join(["This", "is", "test."])
    ​​​​# This is test.
    ​​​​
    ​​​​"......".join(["This", "is". "test."])
    ​​​​# This......is......test.
    
  • split 分割
    ​​​​"This is another example".split()
    ​​​​#['This', 'is', 'another', 'example']
    

formatting strings
str() 更好用的 string 轉換器

name = "Manny"
number = leng(name) * 3
print("Hello {}, your lucky number is {}".format(name, number))

# Hello Manny, your lucky number is 15


# formatting example: set the position in {}
print("Your lucky number is {number}, {name}.".format(name=name, number=len(name)*3))

# Your lucky number is 15. Manny.


#formatting expression
price = 7.5
with_tax = price * 1.09
print(price, with_tax)  #7.5 8.175

print("Base price: ${:.2f}. With Tax: ${:.2f}".format(price, with_tax))
# Base price: $7.50. With Tax: $8.18
# 表示改為 float 且四捨五入顯示兩位數

EXAMPLES of String

#EXAMPLE 1 def double_word(word): length = len(word*2) return word*2 + str(length) print(double_word("hello")) # Should return hellohello10 print(double_word("abc")) # Should return abcabc6 print(double_word("")) # Should return 0 #EXAMPLE 2 def first_and_last(message): if message == "" or message[0] == message[-1]: return True return False print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last("")) #result: 如果第一個字母與最後一個字母相同/“”,回傳 True, 否則回傳 False #EXAMPLE 3: 替換email,以新domain取代舊domain def replace_domain(email, old_domain, new_domain): if "@" + old_domain in email: index = email.index("@" + old_domain) new_email = email[:index] + "@" + new_domain return new_email return email #EXAMPLE 4 def initials(phrase): words = phrase.split() result = "" for word in words: result += word[0].upper() return result print(initials("Universal Serial Bus")) # Should be: USB print(initials("local area network")) # Should be: LAN print(initials("Operating system")) # Should be: OS #EXAMPLE 5 def to_celsius(x): return (x-32)*5/9 for x in range(0, 101, 10): print("{:>3} F | {:>6.2f} C".format(x, to_celsius(x))) #result # 0 F | -17.78 C # 10 F | -12.22 C # 20 F | -6.67 C # 30 F | -1.11 C # 40 F | 4.44 C # 50 F | 10.00 C # 60 F | 15.56 C # 70 F | 21.11 C # 80 F | 26.67 C # 90 F | 32.22 C # 100 F | 37.78 C #EXAMPLE 6: 互文 def is_palindrome(input_string): # We'll create two strings, to compare them new_string = "" reverse_string = "" # Traverse through each letter of the input string for x in input_string.upper(): # Add any non-blank letters to the # end of one string, and to the front # of the other string. if x != " ": new_string = new_string + x reverse_string = x + reverse_string # Compare the strings if new_string == reverse_string: return True return False print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True #EXAMPLE 7 def pig_latin(text): say = "" # Separate the text into words words = text.split() a = [] for word in words: # Create the pig latin word and add it to the list say = word[1:]+ word[0] + "ay" a.append(say) # Turn the list back into a phrase return " ".join(a) print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

Lists & Tuples

x = ["Now", "we", "are"]

  • check the list length :point_right: len(x)
  • check if the element is in the list :point_right: "are" in x
    • check the spesific position in the list :point_right: 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
    ​​​​winners = ["Ashley", "Dylan", "Reese"]
    ​​​​for index, person in enumerate(winners):
    ​​​​    print("{} - {}".formate(index+1, person))
    ​​​​
    ​​​​# 1 - Ashley
    ​​​​# 2 - Dylan
    ​​​​# 3 - Reese
    
  • list comprehension
    ​​​​multiple = []
    ​​​​for x in range(1, 11):
    ​​​​    multiples.append(x*7)
    ​​​​
    ​​​​print(multiples)
    ​​​​#[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
    ​​​​
    ​​​​#list comprehension can do it in one-line
    ​​​​multiples = [x*7 for x in range(1, 11)]
    ​​​​print(multiples)
    ​​​​#[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
    ​​​​
    ​​​​languages = ["Python", "Perl", "Ruby", "Go"]
    ​​​​lengths = [len(language) for langue in langues]
    ​​​​print(lengths)
    ​​​​# [6, 4, 4, 2]
    ​​​​
    ​​​​# 從 1-100 中找出 3 的倍數
    ​​​​z = [x for x in range(0, 101) if x % 3 == 0]
    ​​​​print(z)
    ​​​​#[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
    
x = ["Now", "we", "are"]

len(x) #3
"are" in x  #True
x[0]  #'Now'
x[1:3]  #['We', 'are']
x[:2]  #['Now', 'we']
x[2:]  #['are']

Modify The Content Of A List

  • .append("element")
  • .insert(index, "element")
  • .remove("element")
  • .pop(index)
fruits = ["pineapple", "banana", "apple", "melon"]

friuts.append("kiwi")
# fruits = ["pineapple", "banana", "apple", "melon", "kiwi"]

fruits.insert(0, "orange")
# fruits = ["orange", "pineapple", "banana", "apple", "melon", "kiwi"]

#即使 insert 的位置超過 lists 也能用
friuts.insert(100, "grape")
# fruits = ["orange", "pineapple", "banana", "apple", "melon", "kiwi", "grape"]

fruites.remove("melon")
# fruits = ["orange", "pineapple", "banana", "apple", "kiwi", "grape"]

fruites.pop(3)
# 原本的 fruits = ["orange", "pineapple", "banana", "apple", "kiwi", "grape"]
# 第 3 個位置的元素會被拿掉
# fruits = ["orange", "pineapple", "banana", "kiwi", "grape"]

fruites[2] = "strawberry"
# 原本的 fruits = ["orange", "pineapple", "banana", "kiwi", "grape"]
# 第 2 個位置會被 strawberry 取代
# fruits = ["orange", "pineapple", "strawberry", "kiwi", "grape"]

Lists And Tuples

Tuple 的特色

  • 順序性
  • elements 可以是任何資料型態
  • immutable,不可改變
  • tuple 的「位置順序」是有意義的
  • fruits = ['apple', 'pineapple', 'melon'] 是 string
  • fruits = ('apple', 'pineapple', 'melon') 是 tuple
  • 使用 unpack 方式分割 tuple
    ​​​​def convert_seconds(seconds):
    ​​​​    hours = seconds // 3600
    ​​​​    minutes = (seconds - hours * 3600)//60
    ​​​​    remaining_seconds = seconds - hours * 3600 - minutes * 60
    ​​​​    return hours, minutes, remaining_seconds
    ​​​​
    ​​​​result = convert_seconds(5000)
    ​​​​type(result) #<class 'tuple'>
    ​​​​print(result) # (1, 23, 20)
    ​​​​
    ​​​​# 以 unpack 方式分割 tuple
    ​​​​hours, minutes, seconds = result
    ​​​​print(hours, minutes, seconds) # 1 23 20
    

EXAMPLES of Lists & Tuple

#EXAMPLE 1 def group_list(group, users): members = ",".join(users) return group + ": " + members print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha" print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom" print(group_list("Users", "")) # Should be "Users:" #EXAMPLE 2: lisrs 間隔列印 def skip_elements(elements): # code goes here 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"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] print(skip_elements([])) # Should be [] #EXAMPLE 3 unpack tuple #guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")) 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)) #guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) #EXAMPLE 4: List's enumerate 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"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] #EXAMPLE 5: enter a bunch of email and name as a list 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'])) #['TC Huang <tcmiss@gamil.com>', 'Brian Wu <brian@gmail.com>'] #EXAMPLE 6 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"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']

:bulb: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

:bulb: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

:bulb: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.

Dictionaries

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
files = {"jpg": 10, "csv": 25}

files["jpg"]
# 結果是 10

"jpg" in files
# 結果是 True,因為 file 內有 jpg

Dictionaries is mutable 更改

toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30}

toc["Chapter 5"] = 50
# 新增 Chapter 5

del toc["Chapter 4"]
# 刪除 Chapter 4
# EXAMPLE 1 cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} for key, value in cool_beasts.items(): print("{} have {}".format(key, value)) #result # octopuses have tentacles # dolphins have fins # rhinos have horns #EXAMPLE 2 wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} for item, color in wardrobe.items(): for color in color: print("{} {}".format(color, item)) # result # red shirt # blue shirt # white shirt # blue jeans # black jeans #EXAMPLE 3 def email_list(domains): emails = [] for mail, users in domains.items(): for user in users: emails.append(user + "@" + mail) return(emails) print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]})) #result # ['clark.kent@gmail.com', 'diana.prince@gmail.com', 'peter.parker@gmail.com', 'barbara.gordon@yahoo.com', 'jean.grey@yahoo.com', 'bruce.wayne@hotmail.com'] #EXAMPLE 4 def groups_per_user(group_dictionary): user_groups = {} # Go through group_dictionary for groups, users in group_dictionary.items(): # Now go through the users in the group for user in users: ### Now add the group to the the list of ### groups for this user, creating the entry ### in the dictionary if necessary # if user is exist in user_goups, append to # the list. At first it does not exist so # it goes else part. if user in user_groups: user_groups[user].append(groups) # if user not exist it is create the firts # key:value pair. else: user_groups[user] = [groups] return(user_groups) print(groups_per_user({"local": ["admin", "userA"], "public": ["admin", "userB"], "administrator": ["admin"] })) #result # {'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']} #EXAMPLE 5 def combine_guests(guests1, guests2): # Combine both dictionaries into one, with each key listed # only once, and the value from guests1 taking precedence guests2.update(guests1) return guests2 Rorys_guests = { "Adam":2, "Brenda":3, "David":1, "Jose":3, "Charlotte":2, "Terry":1, "Robert":4} Taylors_guests = { "David":4, "Nancy":1, "Robert":2, "Adam":1, "Samantha":3, "Chris":5} print(combine_guests(Rorys_guests, Taylors_guests)) #result # {'David': 1, 'Nancy': 1, 'Robert': 4, 'Adam': 2, 'Samantha': 3, 'Chris': 5, 'Brenda': 3, 'Jose': 3, 'Charlotte': 2, 'Terry': 1}

Variables

length = 10
width = 2
area = length * width
print(area)
  • length, width, area are variables
    • assignment
    • expression
  • variable 命名限制
    • 不能使用 Python 內建的關鍵字或 function 名稱
    • 不能使用空白格
    • 必須以字母_當開頭
    • 只能以 字母_數字 組成變數名稱

Type Conversion

  • implicit conversion
print("I " + "like " + "Python.")
  • explicit conversion
base = 6
height = 3
area = (base*height)/2
print("The area of the triangle is: " + str(area))  # str()將數字轉換成 string

Function

  • function name = greeting
  • paremeter = name
  • body(action)
def greeting(name):
    print("Welcome, " + name)

Value

  • return value
def area(base, height):
    return base*height/2
    
# 這種寫法可以儲存變數
#> area_a = area(5, 4)
#> area_b = area(7, 3)
#> sum = area_a + area_b
#> print("Sum of both areas is " + str(sum))
  • call value
def greeting(name):
    print("welcome, " + name)
    
    
# 給予變數就能 call value
result = greeting("Christine")

# call 一次後再 print 會顯示 none,表示 return nothing

Condition

# This function compares two numbers and returns them
# in increasing order.
def order_numbers(number1, number2):
	if number2 > number1:
		return number1, number2
	else:
		return number2, number1

# 1) Fill in the blanks so the print statement displays the result
#    of the function call
smaller, bigger = order_numbers(100, 99)  # 變數的順序沒差
print(smaller, bigger)

#> 99 100

*練習題

def calculate_storage(filesize):
    block_size = 4096
    # Use floor division to calculate how many blocks are fully occupied
    full_blocks = filesize // block_size
    # Use the modulo operator to check whether there's any remainder
    partial_block_remainder = filesize % block_size
    # Depending on whether there's a remainder or not, return the right number.
    if partial_block_remainder > 0:
        return block_size*(full_blocks+1)
    return block_size

print(calculate_storage(1))    # Should be 4096
print(calculate_storage(4096)) # Should be 4096
print(calculate_storage(4097)) # Should be 8192
print(calculate_storage(6000)) # Should be 8192

Loops

While Loops

寫 Loop 該注意的事項

  1. 確認variables 是否都被定義了
  2. 確認是否有 break 的條件
x = 0
while x < 5:
    print("Not yet, the number is " + str(x))
    x = x + 1
print("x = " + str(x))

# EXAMPLE 1
def attempts(n):
    x = 1
    while x <= n:
        print("Attempt " + str(x))
        x += 1
    print("Done")
    
attempts(5)
#>Attepmt 1
#>Attepmt 2
#>Attepmt 3
#>Attepmt 4
#>Attepmt 5
#>Done


# EXAMPLE 2
def digits(n):
	count = 0
	if n == 0:
	  count = 1
	while (n >= 1):
		count += 1
		n = n/10
	return count
	
print(digits(25))   # Should print 2
print(digits(144))  # Should print 3
print(digits(1000)) # Should print 4
print(digits(0))    # Should print 1

#result
# 2
# 3
# 4
# 1

common errors in Loops: initialize the variables

忘了先定義 variable

# 錯誤寫法
def count_down(start_number):
  while (current > 0):
    print(current)
    current -= 1
  print("Zero!")

count_down(3)


# 正確寫法:有 initialize variable
def count_down(start_number):
  current = start_number  # 在這裡 initialize 'current' 這個變數為 'start_number'
  while (current > 0):
    print(current)
    current -= 1
  print("Zero!")

count_down(3)

以 Loop 做質因數分解

以下程式能找出組成 number 的所有質因數。
例如:number = 100,其質因數是 2, 2, 5, 5,因為 2x2x5x5 = 100。

def print_prime_factors(number):
  # Start with two, which is the first prime
  factor = 2
  # Keep going until the factor is larger than the number
  while factor <= number:
    # Check if factor is a divisor of number
    if number % factor == 0:
      # If it is, print it and divide the original number
      print(factor)
      number = number / factor
    else:
      # If it's not, increment the factor by one
      factor += 1
  return "Done"

print_prime_factors(100)
# Should print 2,2,5,5

n 是否為 2 的次方?

  • 檢查 n 是否能被 2 整除
    • 若能被 2 整除
      • 讓 n 再除以 2(排除 6, 10 等非 2 次方數字)
      • 若 n 除以 2 之後的數字,能被 2 整除,且 n 不等於 0
        • 返回 True
        • 否則返回 False
def is_power_of_two(n):
  while n % 2 == 0:
    n = n / 2
    if n % 2 ==0 and n !=0:
      return True
    return False
  # 例外狀況: 當 n = 2 時,n/2 =1 導致上述條件無法篩出 2
  if n == 1:
    return True
  return False
  

print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

For Loop

for x in range(5):
    print(x)
  1. 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

  2. examples

# EXAMPLE 1: do the number squared def square(n): # 平方的算法 return n*n def sum_squares(x): # 加總平方數 sum = 0 for n in range(x): sum += square(n) return sum print(sum_square(10)) # should be 285 # EXAMPLE 2: print out the range as list length friends = ['Taylor', 'Alex', 'Pat', 'Eli'] for friend in friends: print("Hi " + friend) # EXAMPLE 3: length and sum values = [23, 52, 59, 37, 48] sum = 0 length = 0 for value in values: sum += value length += 1 print("Total sum: " + str(sum) + " - Average: " + str(sum/length)) # EXAMPLE 4 def votes(params): for vote in params: print("Possible option:" + vote) votes(["yes", "no", "maybe"]) #result # Possible option:yes # Possible option:no # Possible option:maybe # EXAMPLE 5 def multiplication_table(start, stop): for x in range(1, 4): for y in range(1, 4): print(str(x*y), end=" ") print() multiplication_table(1, 3) # Should print the multiplication table shown above #result # 1 2 3 # 2 4 6 # 3 6 9

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)
# 設定特定的起始數字,不以 0 為起始數字
product = 1
for n in range(1, 10):
    product = product * n

print(product)


# 以 loop 計算階層,例如:4! = 1*2*3*4
def factorial(n):
    result = 1
    for i in range(1, n+1):
        result = result * i
    return result

print(factorial(4)) # 4! = 1*2*3*4, should return 24
print(factorial(5)) # 5! = 1*2*3*4*5, should return 120

# for loop 做 factorial
def factorial(n):
    result = 1
    for x in range(1, n+1):
        result = result * x
    return result

for n in range(10):
    print(n, factorial(n))

#result
# 0 1
# 1 1
# 2 2
# 3 6
# 4 24
# 5 120
# 6 720
# 7 5040
# 8 40320
# 9 362880


# range 的第三個 perameter
def to_celcius(x):
    return (x - 32)*5/9
    
for x in range(0, 101, 10):  #代表每 10 個循環一次
    print(x, to_celcius(x))

Nested For Loops

  • 雙重循環的概念
  • Newline Character: end="" 能自動換行
  • for right in range(left, 7): 會將 range 數字跑完。
#EXAMPLE 1 for left in range(7): for right in range(left, 7): print("[" + str(left) + "|" + str(right) + "]", end="") print() #result # [0|0][0|1][0|2][0|3][0|4][0|5][0|6] # [1|1][1|2][1|3][1|4][1|5][1|6] # [2|2][2|3][2|4][2|5][2|6] # [3|3][3|4][3|5][3|6] # [4|4][4|5][4|6] # [5|5][5|6] # [6|6] #EXAMPLE 2 teams = ['Lakers', 'Warriors', 'Rocket', 'Celtics'] for home_teams in teams: for away_teams in teams: if home_teams != away_teams: print(home_teams + " VS " + away_teams) #Result # Lakers VS Warriors # Lakers VS Rocket # Lakers VS Celtics # Warriors VS Lakers # Warriors VS Rocket # Warriors VS Celtics # Rocket VS Lakers # Rocket VS Warriors # Rocket VS Celtics # Celtics VS Lakers # Celtics VS Warriors # Celtics VS Rocket

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 自己
  • 適合用在有多層套疊的情境(例如俄羅斯娃娃、多層資料夾)

# 典型的 Recursion 寫法
def recursive_function(parameters):
    if base_case_condition(parameters):
        return base_case_value
    recursive_function(modified_parameters)


#EXAMPLE 1
def fatorial(n):
    if n < 2:
        return 1
    return n * fatorial(n-1)
#result: 1*2*3*4*.....*n
# 也能寫成
def fact(n):
...     if n >= 1:
...             return n * fact(n-1)
...     return 1
...
>>> fact(4)
24


#EXAMPLE 2
def sum_positive_numbers(n):
    # The base case is n being smaller than 1
    if n < 1:
        return 0
    # The recursive case is adding this number to 
    # the sum of the numbers smaller than this one.
    return n + sum_positive_numbers(n-1)

print(sum_positive_numbers(3)) # Should be 6 因為 1+2+3
print(sum_positive_numbers(5)) # Should be 15 因為 1+2+3+4+5

Recursive 使用情境

  • 適合:active directory, LDAP
  • 不適合:超過 1000 次執行次數的項目,就無法使用