Skip to content

輸入和輸出

輸入和輸出操作

浮點數格式

1
2
3
4
5
# 浮點數格式

num = 123456.789
print('{:.2f}'.format(num))
print('{:,.2f}'.format(num))

產品銷量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 產品銷量

item = input('產品名稱: ')
price = int(input('產品單價: '))
sales = int(input('銷售數量: '))
total = price * sales

print(f'("{item}", {total})')
print('("{0}", {1})'.format(item, total))
print('("%s", %d)' % (item, total))
print('("' + item + '", ' + str(total) + ')')

計算平均分數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 計算平均分數

name = input("請輸入名字: ")
total = score = count = 0
while (score != -1):
    score = int(input("輸入分數,輸入 -1 則結束: "))
    if score == -1:
        break
    total += score
    count += 1
    average = total / count
    # %-20s: 靠左對齊,欄位固定寬度 20 字元
    # %6.2f: 欄位總寬度 6 個字元,小數保留 2 位
    print("%-20s 的平均分數: %6.2f" % (name, average))

平均星級評等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 平均星級評等

total = count = done = 0
while (done != -1):
    rating = float(input("輸入評等(1-5),輸入 -1 則結束: "))
    if rating == -1:
        break
    total += rating
    count += 1
average = float(total / count)
print("平均星級評等: " + format(average, '.2f'))
print("平均星級評等: {:.2f}".format(average))
print(f"平均星級評等: {average:.2f}")

外匯換算

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# 外匯換算

def print_table(data, money):
    for row in data:
        fields = row.split(",")
        fields[1] = money / eval(fields[1])
        fields[2] = money * eval(fields[2])
        print("{0:30} {1:8.1f} {2:11.2f}".format(
            fields[0], fields[1], fields[2]))


# 幣別,買入匯率,賣出匯率
exchange_rates = [
    "USD(United States Dollar),29.98,30.65",
    "JPY(Japanese Yen),0.2284,0.2412",
    "EUR(Euro),32.1,33.44",
    "KRW(Korean Won),0.02281,0.02671",
    "CNY(Chinese Yuan Renminbi),4.434,4.596"
]

print_table(exchange_rates, 1000)

字串格式化參數順序

1
2
3
4
5
6
7
# 字串格式化參數順序

a = 'Apple'
b = 'Banana'
c = 'Cherry'
fruit = "{1}, {0} and {2}"
print(fruit.format(a, b, c))

莓果銷售數量★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 莓果銷售數量★

"""
輸出格式要求:
水果名稱兩側標字串雙引號之後接一個英文冒號及空白,再接數量

例如:
"strawberry": 4
"blackberry": 7
"blueberry": 5
"raspberry": 4
"""
fruit_list = [
    'strawberry', 'blackberry', 'blackberry', 'blueberry',
    'blueberry',  'raspberry',  'blueberry',  'blackberry',
    'strawberry', 'raspberry',  'blueberry',  'strawberry',
    'raspberry',  'blackberry', 'blueberry',  'blackberry',
    'blackberry', 'blueberry',  'raspberry',  'blackberry'
]

輸出檔案第一行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 輸出檔案第一行

"""
檔案處理函式設計必須符合以下條件:
* 如果指定檔案不存在,回傳 "檔案不存在"
* 如果該檔案存在,回傳第一行內容
"""

import os

def get_first_line_of_file(fname):
    if os.path.isfile(fname):
        with open(fname, 'r') as fho:
            return fho.readline()
    else:
        return "檔案不存在"

print(get_first_line_of_file('data1.txt'))
print(get_first_line_of_file('data2.txt'))

檔案處理錯誤

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 檔案處理錯誤

# 函式功能:讀取檔案後,將檔案中的每一行列印出來
01 def print_file(filename):
02     line = None
03     if os.path.isfile(filename):
04         data = open(filename, 'r')
05         for line in data:
06             print(line)

# 假設 data.txt 和程式放在同一個資料夾
print_file('data.txt')

"""
# 呼叫執行這個函式,會收到 03 行的錯誤,錯誤的原因應該是什麼?
A. 需要匯入 os 模組而沒有匯入
B. path 方法並不存在 os 模組中
C. path 物件中不存在 isfile 方法
D. isfile 方法不接受一個參數
"""

讀取銷售資料檔案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 讀取銷售資料檔案

"""
[測資開始]
'A01', 180, 1
'B02', 240, 5

'C01', 195, 3
'D02', 215, 4

'E01', 360, 2

[測資結束]

檔案處理設計必須符合以下條件:
* 檔案有多行,一行一筆銷售資料
* 資料欄位包含:產品編號、產品單價、購買數量
* 檔案的每一行都必須讀取和輸出
* 可能有空行,遇到空行則略過讀取和輸出
* 讀取完畢後,必須關閉檔案
"""

fho = open('data.txt', 'r')
while True:
    line = fho.readline()
    if line != '':
        if line != '\n':
            print(line.strip())
    else:
        print("End of File")
        break
fho.close()

檔案附加內容★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# 檔案附加內容★

"""
檔案處理設計必須符合以下條件:
* 檢查指定檔案是否存在
* 如果該檔案存在,就顯示檔案內容
* 如果該檔案不存在,就使用指定名稱新增檔案
* 在檔案最後加入字串:"End of File"
"""

import os

fname = 'data.txt'
if os.path.isfile(fname):
    fho = open(fname)
    print(fho.read())
    fho.close()
# r, r+, a, a+, w, w+, x, x+ 的差異
fho = open(fname, 'a')
fho.write("End of File")
fho.close()