Contents

image

亞洲大學基礎程式設計教材(AUP110-Fundamentals of Programming)

Open In Colab

#Week4 Python基本資料結構和簡單流程控制

image

Topic 1(主題1)-串列(list)

  • 串列把一堆變數放入[]中,形成一排資料

  • 串列變數是一堆變數的集合

Python語言括號有三種, 小括號()代表元組(tuple)資料型別、中括號[ ]代表串列(List)資料型別、大括號{ }代表字典(dict)或集合(set)資料型別。在這裡,我們先介紹最常見的資料型別串列(List)…

串列(List)

img

Step 1: 不使用 list變數的一堆變數

student0 = 'John'; student1 = 'Mary'; student2 = 'Ken'
print('Hello', student0)
print('Hello', student1)
print('Hello', student2)
Hello John
Hello Mary
Hello Ken

Step 2: 使用 list變數當集合變數, 用索引鍵得到變數/indexing of list elements

students = ['John', 'Mary', 'Ken']
print('Hello', students[0])
print('Hello', students[1])
print('Hello', students[2])
Hello John
Hello Mary
Hello Ken

Step 3: 負索引鍵得到變數

students = ['John', 'Mary', 'Ken']
print('Hello', students[-3])
print('Hello', students[-2])
print('Hello', students[-1])
Hello John
Hello Mary
Hello Ken

Step 4: list的長度/Length of a list

students = ['John', 'Mary', 'Ken']
print(students)
print(len(students))
['John', 'Mary', 'Ken']
3

Step 5: 增加串列(list)的元素

students.append('Lily')
print(students)
print(len(students))
['John', 'Mary', 'Ken', 'Lily']
4

Topic 2(主題2)-字串切割(str.split())

Step 1: 用空白間隔的子字串

students = 'John Mary Ken'
print(students)
print(len(students))
John Mary Ken
13

Step 2: 用split()切開子字串

students = 'John Mary Ken'.split()
print(students)
print(len(students))
print(type(students))
['John', 'Mary', 'Ken']
3
<class 'list'>

Step 3: 把input的字串用split()切開

# input 3 5 
paras = input().split()
print(paras[0])
print(paras[1])
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
/tmp/ipykernel_816/3824391208.py in <module>
      1 # input 3 5
----> 2 paras = input().split()
      3 print(paras[0])
      4 print(paras[1])

~/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
   1001         """
   1002         if not self._allow_stdin:
-> 1003             raise StdinNotImplementedError(
   1004                 "raw_input was called, but this frontend does not support input requests."
   1005             )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Step 4: 把input的字串用split()切開,再轉成整數

# input 3 5 
paras = input().split()
a = int(paras[0])
b = int(paras[1])
print(a + b)

Topic 3(主題3)-for迴圈/for-loop

Step 1: 對list變數使用迴圈

students = ['John', 'Mary', 'Ken']
for student in students:
  print('Hello ', student)

Step 2: 使用迴圈,印出1-9/print out the numbers 1-9

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
  print(number, end=' ')

##Topic 4: 多重指定敘述(multiple assignment)

Step 1: 各別指定

students = ['John', 'Mary', 'Ken']
a = students[0]
b = students[1]
c = students[2]
print(a, b, c)

Step 2: 多重指定(multiple assignment), 又稱為反打包(unpacking)

students = ['John', 'Mary', 'Ken']
a, b, c = students
print(a, b, c)

Step 3: 部份反打包(unpacking)

students = ['John', 'Mary', 'Ken']
a, *other = students
print(other)

##Topic 5: f-格式化字串和print()的格式化輸出

https://docs.python.org/3/tutorial/inputoutput.html

Step 1: f-字串

a = 'John'
str2 = f'Hi, {a}'
print(str2)

Step 2: 使用f-字串的格式化輸出

a = 'John'
print(f'Hi, {a}')

Step 3: 數字的格式化

yes_votes = 42_572_654
no_votes = 43_132_495
percentage = yes_votes / (yes_votes + no_votes)
print(f'{yes_votes:9} YES votes {percentage:2.2%}')

Topic 6: 印出99乘法表/print out the multiplication table

img

Step 1: 使用1層迴圈,印出1-9/print out the numbers 1-9

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for n in numbers:
  print(f'{n:1}*1 ={n*1:2}', end=' ')
  print(f'{n:1}*2 ={n*2:2}', end=' ')
  print(f'{n:1}*3 ={n*3:2}', end=' ')
  print(f'{n:1}*4 ={n*4:2}', end=' ')
  print(f'{n:1}*5 ={n*5:2}', end=' ')
  print(f'{n:1}*6 ={n*6:2}', end=' ')
  print(f'{n:1}*7 ={n*7:2}', end=' ')
  print(f'{n:1}*8 ={n*8:2}', end=' ')
  print(f'{n:1}*9 ={n*9:2}', end=' ')
  print()

Step 2: 使用2層迴圈,印出99乘法表/print out the multiplication table

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for a in numbers:
  for b in numbers:
    print(f'{a:1}*{b:1} ={a*b:2}', end=' ')
  print()

Topic 7(主題7)-range()函數

range(start, stop, step)

Step 1: parameters of range(): begin/end

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for n in a:
  print(f'{n}', end=' ')
print()
b = range(1, 10)
for n in b:
  print(f'{n}', end=' ')
print()
for n in range(1, 10):
  print(f'{n}', end=' ')
print()

Step 2: parameters of range(): step

for n in range(1, 10, 1):
  print(f'{n}', end=' ')
print()
for n in range(1, 18, 2):
  print(f'{n}', end=' ')
print()

Step 3: 使用range(),印出99乘法表/print out the multiplication table

for n in range(1,10):
  print(f'{n:1}*1 ={n*1:2}', end=' ')
  print(f'{n:1}*2 ={n*2:2}', end=' ')
  print(f'{n:1}*3 ={n*3:2}', end=' ')
  print(f'{n:1}*4 ={n*4:2}', end=' ')
  print(f'{n:1}*5 ={n*5:2}', end=' ')
  print(f'{n:1}*6 ={n*6:2}', end=' ')
  print(f'{n:1}*7 ={n*7:2}', end=' ')
  print(f'{n:1}*8 ={n*8:2}', end=' ')
  print(f'{n:1}*9 ={n*9:2}', end=' ')
  print()
for a in range(1,10):
  for b in range(1,10):
    print(f'{a:1}*{b:1} ={a*b:2}', end=' ')
  print()

Topic 8(主題8)-舊式字串格式化

A = 435; B = 59.058
print('Art: %5d, Price per Unit: %8.2f' % (A, B))          #%-formatting 格式化列印
print("Art: {0:5d}, Price per Unit: {1:8.2f}".format(A,B)) #str-format(Python 2.6+)
print(f"Art:{A:5d}, Price per Unit: {B:8.2f}")             #f-string (Python 3.6+)

Step 1: %-formatting 格式化列印

透過% 運算符號,將在元組(tuple)中的一組變量依照指定的格式化方式輸出。如 %s(字串)、%d (十進位整數)、 %f(浮點數)

for a in range(1,10):
  for b in range(1,10):
    print('%d*%d =%2d'%(a, b, a*b), end=' ')
  print()

Step 2: str-format(Python 2.6+)格式化列印

for a in range(1,10):
  for b in range(1,10):
    print('{0:1d}*{1:1d} ={2:2d}'.format(a, b, a*b), end=' ')
  print()

Step 3: f-string (Python 3.6+)格式化列印

for a in range(1,10):
  for b in range(1,10):
    c= a*b
    print(f'{a}*{b} ={c:2d}', end=' ')
  print()

Topic 9(主題9)-串列(List)的初始化和解析式

Step 1: 條列初始化

numbers = [2, 4, 6, 8, 10]
for n in numbers:
  print(f'{n}', end=' ')

Step 2: 使用串列解析式(List Comprehension)來初始化

numbers = [x for x in range(2,11,2)]
for n in numbers:
  print(f'{n}', end=' ')