2017.9.3 Dictionaries

Dictionaries

1.

# 在 dictionary 中創造新的 key

dict_name[new_key] = new_value

2.

# 改變其中一個 key 的 value

dict_name[key] = new_value

3.

# 刪除一個 key

del dict_name[key_name]

 


stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

del stock['banana']
print(stock)

{‘apple’: 0, ‘orange’: 32, ‘pear’: 15}

閱讀更多»

廣告

2017.9.2 List / Slices

List

# 使用 for loop 定義 number 為 my_list 中的各項數據
# 使 my_list 不被變更,可重複使用

my_list = [1,9,3,8,5,7]
  for number in my_list:
    print(2 * number)

2
18
6
16
10
14


# 也可另外創一個 empty list
# 視情況去增加 .append() 或 排列 .sort()

start_list = [5, 3, 1, 2, 4]
square_list = []
  for number in start_list:
    square_list.append(number ** 2)
    square_list.sort()

print (square_list)

[1, 4, 9, 16, 25]

閱讀更多»

2017.8.31 Codecademy

練習1

  1. def a function called cube that takes an argument called number.
  2. make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again).
  3. def a second function called by_three that takes an argument called number.
  4. if that number is divisible by 3, by_three should call cube(number) and return its result.
  5. otherwise, by_three should return False.
def cube(number):
   return number * number * number

def by_three(number):
   if number % 3 == 0:
     return cube(number)
 else:
     return False

print(cube(2))
print(by_three(3))
print(by_three(4))

8
27
False

閱讀更多»

2017.8.29 Codecademy

  1. “%s" 可以被 “% ( )"內的字串給取代 (按照順序) (s=substitution)
  2.  " \ " 用來將程式碼換行
name='Jumping'
quest='learning Python'
color='black'

print('Ah, so your name is %s, your quest is %s,' \
' and your favorite color is %s.' % (name, quest, color))

Ah, so your name is Jumping, your quest is learning Python, and your favorite color is black.

閱讀更多»