Python 初級
執行
python main.py
執行並導入測資
python main.py < d1.txt
"""
# 內建函式 print()
# 功能:輸出字串、數據或變數
# print(參數: 字串、數據或變數)
設定函式呼叫步驟:
1. 設定函式名稱
2. 放一對圓括 ()
3. 放參數
"""
# print(1個參數)
# 輸出一個字串
print('Hello, World!')
# print(0個參數)
# 單純換行
print()
# print(2個以上參數,逗號分隔)
# 參數輸出時,彼此之間空一白
print('Hello, World!', 'I am Robot 987.')
可用單引號或雙引號設定,必須設在字串兩側
# 單引號設定字串,雙引號是可輸出的字串內容
print('The teacher asked, "Does anyone know the answer?"')
# 雙引號設定字串,單引號是可輸出的字串內容
print("I don't know what's going on with it.")
"""
# 內建函式 type()
# 功能:回傳數據或變數的類別
# type(參數: 數據或變數)
"""
# 字串 str (string)
print('123', type('123'))
# 整數 int (integer)
print(123, type(123))
# 浮點數 float
print(123.0, type(123.0))
# 布林數 bool (boolean)
# 例一: 電源的開和關 (on or off)
# 例二: 答案的是或否 (yes or no)
print(True, type(True))
print(False, type(False))
"""
f-string 設定 (f: format 格式化) --
[說明]
1. 放「輸出 f-string」
2. 放「例句字串」
3. 將數據換成花括{}
4. 放變數到花括裡面
[步驟]
1. print(f'')
2. print(f'Sum: 9')
3. print(f'Sum: {}')
4. print(f'Sum: {x}')
"""
# 變數 a 存整數 7
a = 7
# 變數 b 存整數 2
b = 2
# 變數 x 存 a + b 的和
x = a + b
# 依特定格式輸出變數 x
print(f'Sum: {x}')
保留小數位數
"""
f-string 設定 (f: format 格式化) --
[說明]
1. 放「輸出 f-string」
2. 放「例句字串」
3. 將數據換成花括{}
4. 放變數到花括裡面
5. 變數後面加英文冒號 : 再設定小數位數 .?f
[步驟]
1. print(f'')
2. print(f'Perimeter: 12.57')
3. print(f'Perimeter: {}')
4. print(f'Perimeter: {perimeter}')
5. print(f'Perimeter: {perimeter:.2f}')
"""
# 變數 pi 存圓周率
pi = 3.14159
# 變數 diameter 存直徑 8 公分
diameter = 8
# 變數 perimeter 存圓周長
perimeter = pi*diameter
# 依特定格式輸出圓周長,保留小數 2 位
print(f'Perimeter: {perimeter:.2f}')
# 依特定格式輸出圓周長,保留小數 4 位
print(f'Perimeter: {perimeter:.4f}')
"""
# 內建函式 input()
# 功能:接收並回傳使用者輸入的資料
# 變數:指到一格記憶體空間(位置)
# input(參數: 提示訊息字串)
"""
# input(0個參數)
# 解題使用
# 將第 1 行輸入存到變數 number
number = input()
# input(1個參數)
# 練習或小專題使用
# 將第 2 行輸入存到變數 name
name = input('What is your name? ')
"""
# 內建函式 int()
# 功能:將「整數字串」或「浮點數」轉為整數
# int(參數: 整數字串)
# int(參數: 浮點數)
"""
# 變數 a 存一個任意輸入的整數
a = int(input('a: '))
print(a)
# 變數 b 存一個任意輸入的整數
b = int(input('b: '))
print(b)
# 輸出 a + b 的和
print(a + b)
# 將 a + b 的結果存到變數 s
s = a + b
# 設定 f-string 格式化輸出訊息
print(f'Sum: {s}')
"""
# 內建函式 float()
# 將「浮點數字串」或「整數」轉為浮點數
# float(參數: 浮點數字串)
# float(參數: 整數)
"""
# 變數 a 存一個任意輸入的浮點數
a = float(input('a: '))
print(a)
# 變數 b 存一個任意輸入的浮點數
b = float(input('b: '))
print(b)
# 輸出 a + b 的和
print(a + b)
# 將 a + b 的結果存到變數 s
s = a + b
# 設定 f-string 格式化輸出訊息,小數保留 2 位
print(f'Sum: {s:.2f}')
# 變數 a 存一個浮點數的整數部分
a = int(float(input('a: ')))
print(a)
# 變數 b 存一個浮點數的整數部分
b = int(float(input('b: ')))
print(b)
# 輸出 a + b 的和
print(a + b)
# 七種算術運算
"""
# ex(+).
# 輸入 2 個整數
# 輸出數學算術等式
[輸入與輸出]
7
2
7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3.5
7 // 2 = 3
7 % 2 = 1
7 ** 2 = 49
"""
# 加(+)、減(-)、乘(*)、除(/)
7 + 2
7 - 2
7 * 2
7 / 2
# 商數(//)、餘數(%)
# % 其實是模數運算
7 // 2
7 % 2
# 指數(次方)
7 ** 2
# 運算子優先序
"""
# ex(+).
# 圓括 > 指數 > 負數 > 乘除、商餘 > 加減
# 先乘除後加減 -> 指負乘除加減
# 整數和浮點數計算 -> 結果是浮點數
5 + 1.0 -> 6.0
5.0 + 1 -> 6.0
Python 的 3 種除法:
1. / : 浮點數除法,整數相除得到「浮點數」
2. // : 商數除法,整數相除得到「商數」
3. % : 餘數除法,整數相除得到「餘數」
"""
# a = 7 + 2 - 3 * 2
# print('a:', a)
# b = 8 + 4 / 2 - 5 * 2
# print('b:', b)
# c = 8 * 2 + 7 - 9 / 4 * 3 ** 2
# print('c:', c)
# d = (8 + -4) / 2 - 5 * 2
# print('d:', d)
# e = 27 % 5 * 6 ** 2 - 12 // 6
# print('e:', e)
# 輸入兩個整數字串存到變數 a 和 b
a = input('a: ')
print(a)
b = input('b: ')
print(b)
print(a, type(a))
print(b, type(b))
print('Sum:', a + b)
print()
# 因為任何輸入都是字串
# 所以必須使用 int() 轉成整數
a = int(a)
b = int(b)
print(a, type(a))
print(b, type(b))
print('Sum:', a + b)
alist = input().split()
print(alist)
print(alist[0])
print(alist[1])
print(alist[2])
# 將串列中的數據依序分配到不同變數
a, b, c = alist
# 字串合併
print(a + b + c)
# 將原數據由字串轉為整數
a = int(a)
b = int(b)
c = int(c)
# 整數相加
print(a + b + c)
a = int(input('a: '))
print(a)
b = int(input('b: '))
print(b)
x = a - b
print(f'Difference = {x}')
x = abs(x)
print(f'Absolute value = {x}')
# s: sum
s = int(input())
# d: difference
d = int(input())
large = (s + d) // 2
small = (s - d) // 2
print(f"Large number: {large}")
print(f"Small number: {small}")
# 數的次方
"""
# ex(+).
# 使用指數運算 **
# 輸入 n 和 p
# 計算輸出 n 的 p 次方
[輸入與輸出]
n: 8
p: 2
8 to the power of 2 is 64
"""
n = input('n: ')
print(n)
p = input('p: ')
print(p)
print(f'n to the power of p = {n}')
import math
x = int(input('x: '))
print(x)
# square: 平方
square = x**2
print(f'square of {x} = {square}')
# square_root: 平方根
square_root = math.sqrt(x)
print(f'square root of {x} = {square_root}')
# 十進位的位數
"""
# ex(+).
# 輸入 3 位數整數
# 計算輸出每個位數的數字
[輸入與輸出]
n: 987
hundreds digit: 9
tens digit: 8
units digit: 7
"""
n = int(input('n: '))
print(n)
print(f"hundreds digit: {0}")
print(f" tens digit: {n // 10}")
print(f" units digit: {n % 10}")
a = int(input('a: '))
print(a)
b = int(input('b: '))
print(b)
print(a & b)
print(a | b)
print(a ^ b)
print(a >> b)
print(a << b)
"""
1. 語法錯誤 Syntax Error : 不可執行,錯誤類別一律為 SyntaxError
2. 執行錯誤 Runtime Error : 可以執行,過程可能顯示錯誤訊息
3. 語意錯誤 Semantic Error: 可以執行,不會顯示錯誤訊息,但結果不符題意
type(data): 回傳資料的類別
int('987'): 將數字字串轉成整數 -> integer
str(12345): 將整數轉成數字字串 -> string
"""
a = input('A: ))
print(a)
b = (input(B: ')
print(b)
print(f'A = {a}', type(a))
print(f'B = {b}', type(b))
q = a + b
print(f'The quotient of A over B = {x}')
兩個以上單字,單字之間以底線連接
"""
# 變數作用:存取資料
# 存:Set, Save, Store, Conserve
# 取:Get, Open, Fetch, Retrieve
"""
your_name = input("What is your name? ")
print(your_name)
your_best_friend = input("Who is your best friend? ")
print(your_best_friend)
print(f"{your_name} & {your_best_friend}")
a = int(input('a: '))
print(a)
b = int(input('b: '))
print(b)
print(f'a: {a}, b: {b}')
a, b = b, a
print(f'a: {a}, b: {b}')
"""
記憶體 vs. 變數
資料盒 vs. 便利貼
記憶體: 就如資料盒,是實際存放資料的空間
變數: 就如便利貼,可以在不同資料盒間貼來貼去
"""
a = 1
print(a, type(a), id(a))
a = 2
print(a, type(a), id(a))
a = 3
print(a, type(a), id(a))
print()
a = '1'
print(a, type(a), id(a))
a = '2'
print(a, type(a), id(a))
a = '3'
print(a, type(a), id(a))
# 簡單異常處理
"""
異常錯誤,其實就是執行錯誤
try:
可能會發生異常錯誤的程式
以及相關程式
except:
發生異常錯誤時的處理
可以寫 pass 表示略過
"""
n = input('n: ')
print(n)
try:
n = int(n)
print(f'The square of n is {n**2}.')
except:
print(f"'{n}' is not an integer.")
print(type(n))
條件式: 項目一 比較運算 項目二 (條件成立 True / 條件不成立 False)
if 和 elif 都必須接條件式
print("Beebo: Let's hang out.")
weather = input("How is the weather? ")
print(weather)
if weather == "sunny":
print("(1) Sure. Why not?")
print("Beebo: Let's hang out.")
weather = input("How is the weather? ")
print(weather)
print(f'weather == "sunny" ->', weather == "sunny")
if weather == "sunny":
print("(1) Sure. Why not?")
else:
print("(2) I want to stay home.")
alist = input().split()
a, b, c = alist
a = int(a)
b = int(b)
c = int(c)
g = a
if b > g:
g = b
if c > g:
g = c
print(f"The Greatest = {g}")
alist = input().split()
a, b, c = alist
a = int(a)
b = int(b)
c = int(c)
g = a if a > b else b
g = g if g > c else c
print(f"The Greatest = {g}")
移除多餘條件
score = int(input("Score: "))
print(score)
if score >= 80:
print("A, GPA is 4")
elif score < 80 and score >= 70:
print("B, GPA is 3")
elif score < 70 and score >= 60:
print("C, GPA is 2")
elif score < 60 and score >= 50:
print("D, GPA is 1")
else:
print("F, GPA is 0")
先判斷 is_small 再判斷 is_furry
is_furry = True
is_small = True
if is_furry is True:
if is_small is True:
print("Cat")
elif is_small is False:
print("Bear")
elif is_furry is False:
if is_small is True:
print("Gecko")
elif is_small is False:
print("Crocodile")
先判斷奇偶,再判斷正負
n = int(input('n: '))
print(n)
if n == 0:
print('Zero')
elif n > 0:
if n % 2 == 0:
print('Positive Even')
elif n % 2 == 1:
print('Positive Odd')
elif n < 0:
if n % 2 == 0:
print('Negative Even')
elif n % 2 != 0:
print('Negative Odd')
alist = input().split()
first_born = alist[0].upper()
second_born = alist[1].upper()
third_born = alist[2].upper()
if first_born == 'M':
print('1st child: Son -> Aaron')
if second_born == 'M':
print('2nd child: Son')
else:
print('2nd child: Daughter')
else:
print('1st child: Daughter -> Bella')
if second_born == 'M':
print('2nd child: Son')
else:
print('2nd child: Daughter')
for i in range(5):
print(i)
只有輸出符號,沒有輸出變數 i
for i in range(5):
print('*')
for i in range(1, 10):
print(i)
輸出整數 a ~ b,i 為 3 的倍數時,輸出 ***,其他值則輸出 *
a = int(input())
b = int(input())
for i in range(a, b):
if False:
print(i, '***')
else:
print(i, '*')
n = 10
total = 0
for i in range(1, n+1):
if i % 2 == 0:
total = total + i
print('Sum of even numbers:', total)
# start 到 stop 由小到大,step 要設正數
for i in range(1, 10, 2):
print(i, end=' ')
print()
# start 到 stop 由大到小,step 要設負數
for i in range(10, 1, -2):
print(i, end=' ')
print()
# 區分作用命名
"""
# ex(+).
# 使兩個相同迴圈輸出同樣結果
# 不得增加程式行數
# range() 參數不得直接放整數或算式,但可放變數
"""
i = 5
for i in range(i):
print(f'i: {i}', end=' ')
i = i * 2
print(f'* 2 -> {i}')
print('-'*20)
for i in range(i):
print(f'i: {i}', end=' ')
i = i * 2
print(f'* 2 -> {i}')
for i in range(10):
if i % 2 == 0:
continue
print(i)
else:
print('***')
break 則 else 相關敘述無效
for i in range(10):
if i % 2 == 0:
continue
if i == 7:
break
print(i)
else:
print('***')
正左直角、倒左直角、正右直角、倒右直角、正金字塔、倒金字塔、奇數菱形、三角沙漏
"""
# 正左直角
i *
1 1 *
2 2 **
3 3 ***
4 4 ****
5 5 *****
# 倒左直角
i *
1 5 *****
2 4 ****
3 3 ***
4 2 **
5 1 *
# 正右直角
i . *
1 4 1 *
2 3 2 **
3 2 3 ***
4 1 4 ****
5 0 5 *****
# 倒右直角
i . *
1 0 5 *****
2 1 4 ****
3 2 3 ***
4 3 2 **
5 4 1 *
# 正金字塔
i . *
1 4 1 *
2 3 3 ***
3 2 5 *****
4 1 7 *******
5 0 9 *********
# 倒金字塔
i . *
1 0 9 *********
2 1 7 *******
3 2 5 *****
4 3 3 ***
5 4 1 *
# 奇數菱形
i . *
1 2 1 *
2 1 3 ***
3 0 5 *****
4 1 3 ***
5 2 1 *
# 三角沙漏
i . *
1 0 5 *****
2 1 3 ***
3 2 1 *
4 1 3 ***
5 0 5 *****
"""
n = int(input('n: '))
print(n)
print('# 正左直角')
for i in range(1, n+1):
print('*'*i)
各式數列三角
"""
Case 1:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Case 2:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Case 3:
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
Case 4:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Case 5:
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Case 6:
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
"""
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print()
isplus = True
total = 0
while isplus:
total = total + 1
print(total)
if total == 10:
isplus = False
total = 0
while True:
total += 1
print(total)
if total == 10:
break
"""
[輸入與輸出]
step: 1
1 2 3 4 5 6 7 8 9 10
step: 2
2 4 6 8 10
step: 3
3 6 9
step: 4
4 8
"""
step = input("step: ")
print(step)
total = 0
while True:
total += 1
# 輸出目前 total 後,空一白,不換行
print(total, end=' ')
if total == 10:
# 離開迴圈前才換行
print()
# 離開本層迴圈
break
total = 0
while False:
total += 1
print(total)
if total == 10:
break
print('# for loop')
t = 0
for i in range(10):
t += 1
print(t)
print('-'*20)
print('# while loop')
t = 0
while t < 10:
t += 1
print(t)
依選項輸出圖形
while True:
print('1.正左直角 2.倒左直角')
print('3.正右直角 4.倒右直角')
print('5.正金字塔 6.倒金字塔')
print('7.奇數菱形 8.三角沙漏')
print('q.離開迴圈')
op = input('> ')
print(op)
if op == 'q':
break
n = int(input('n: '))
print(n)
if True:
for i in range(1, n+1):
print(i)
elif True:
for i in range(1, n+1):
print(i)
i = 0
while i < 10:
i += 1
if i % 3 == 0:
i += 1
print(i)
else:
print('***')
break 則 else 相關敘述無效
i = 0
while i < 10:
i += 1
if i % 3 == 0:
i += 1
elif i % 5 == 0:
break
print(i)
else:
print('***')
n = int(input('n: '))
print(n)
print(bin(n))
print(oct(n))
print(hex(n))
10進位轉 2/8/10/16 進位
digits = "0123456789abcdef"
print(digits)
n = int(input('n: '))
print(n)
while True:
break
print(f"Bin: {bin(n)}")
print(f"Oct: {oct(n)}")
print(f"Dec: {n}")
print(f"Hex: {hex(n)}")
"""
[輸入與輸出]
n: 5
-o-o-
x-x-x
-o-o-
x-x-x
-o-o-
n: 6
-o-o-o
x-x-x-
-o-o-o
x-x-x-
-o-o-o
x-x-x-
"""
n = int(input('n: '))
print(n)
for i in range(n):
print('-'*n)
a = int(input('a: '))
print(a)
b = int(input('b: '))
print(b)
for i in range(a, b+1):
print(i)
一次排除一個錯誤,避免增加程式行數
op = input('1.Create 2.Read 3.Update 4.Delete': )
if op == 1:
print(Create)
elif op == 2:
print(Read)
elif op == 3:
print(Update)
elif op == 4:
print(Delete)
一次排除一個錯誤,避免增加程式行數
n = input(int('n: '))
if n % 2 == 0:
print('It's an odd.')
else:
print('It's an even.)
一次排除一個錯誤,避免增加程式行數
print('L.Left')
print('R.Right')
print('U.Up')
print('D.Down')
input('> ') = op
if op == 'L'
print('Left')
elif op == 'R'
print('Right')
elif op == 'U'
print('Up')
else op == 'D'
print('Down')
一次排除一個錯誤,避免增加程式行數
"""
[輸入與輸出]
How much would you like to deposit? 100
Enjoy your mug!
Have a nice day!
How much would you like to deposit? 101
You get a free toaster!
Congratulations!
Have a nice day!
"""
deposit = input('How much would you like to deposit? '))
freeToaster = False
if int(deposit) > 100
print('You get a free toaster!')
freeToaster = true
else:
print('Enjoy your mug!')
if freeToaster:
print('Congratulations!')
print('Have a nice day!')
一次排除一個錯誤,避免增加程式行數
"""
[輸入與輸出]
n: 5
*
**
***
****
*****
"""
for i in range(input('n: '):
print('*'*n+1)
一次排除一個錯誤,避免增加程式行數
"""
[輸入與輸出]
n: 10
2
4
6
8
10
"""
n = int(input(n: '))
for i in range(n, 2):
if i % 2 = 0:
print(i)
一次排除一個錯誤,避免增加程式行數
"""
[輸入與輸出]
start: 10
10
9
8
7
6
5
4
3
2
1
Time's Up!
"""
countdown = input('start: ')
While false:
print(countdone)
countdown -= 1
if countdown === 0:
print('Time's Up!')
break
一次排除一個錯誤,避免增加程式行數
total = 0
while true:
i = input('Integer (-1 to leave the loop): ')
if i == -i:
break
total += i
print(i, total)
一次排除一個錯誤,避免增加程式行數
"""
[輸入與輸出]
n: 3
t: 0
a: 1
a: 2
a: 3
a: 4
3
----------
t: 1
a: 2
a: 4
1
----------
t: 2
a: 3
a: 2
a: 3
a: 2
a: 5
4
----------
"""
n = int(input('n: '))
for t in range(n):
count = 0
print(' t:', t)
while True:
a = input(' a: ')
if a < n:
break
count = 1
print(f' {count}')
print('-'*10)
一次排除一個錯誤,避免增加程式行數
"""
[輸入與輸出]
n: 3
----------
n: 4
4
----------
n: 5
5
----------
n: 6
6
66
----------
n: 7
7
77
----------
n:
"""
while True:
n = input('n: ')
if n == '':
break
m = n / 2
for i in range(1, n):
print(i*n)
print('-'*10)
test_error = input('1, 2, 3, 4 or 5: ')
if test_error == '1':
# ZeroDivisionError
incomes = (0, 140, 210, 0, 175, 280)
for i in range(1, len(incomes)):
print(incomes[i] / incomes[i-1])
elif test_error == '2':
# NameError
print(x * 3)
elif test_error == '3':
# TypeError
num1 = input('The number: ')
num2 = 2
print(num1 + num2)
elif test_error == '4':
# TypeError
for i in range(input('The stop number: ')):
print(i)
elif test_error == '5':
# ValueError
data = ('1', 'a', 'A')
for cell in data:
print(int(cell))
line = '3 -2 4 5 -6 0 7'
alist = list(map(int, line.split()))
print(alist)
acount = 0
# 迴圈讀取整數,讀到正整數則變數 acount += 1
for value in alist:
if value > 0:
acount += 1
print(acount)
line = '3 12 4 5 16 10 7'
alist = list(map(int, line.split()))
print(alist)
atotal = 0
# 迴圈讀取整數,並累加到變數 atotal
for value in alist:
atotal += value
print(atotal)
line = '3 12 4 5 16 10 7'
alist = list(map(int, line.split()))
print(alist)
atotal = 0
acount = 0
for value in alist:
atotal += value
acount += 1
avg = atotal / acount
print(f"Average = {avg:.2f}")
line1 = '88 72 84 75 63 91'
line2 = '4 3 2 5 4 3'
alist = list(map(int, line1.split()))
wlist = list(map(int, line2.split()))
n = len(alist)
print(alist)
print(wlist)
atotal = 0
acount = 0
for i in range(n):
atotal += alist[i] * wlist[i]
acount += wlist[i]
avg = atotal / acount
print(f"Average = {avg:.2f}")
兩個串列相加
alist = [1, 2, 3]
blist = [4, 5, 6]
clist = alist + blist
print(clist)
一個串列乘以一個整數 N,表示複製 N 組並合併
alist = [8, 7]
blist = alist * 5
print(blist)
alist = [0]
blist = alist * 10
print(blist)
alist = [3, 12, 4, 5, 16, 10, 7]
n = int(input('n: '))
pos = -1
for i in range(len(alist)):
print(f'{i} -> {alist[i]}')
if alist[i] == n:
pos = i
break
if pos == -1:
print('Not found.')
else:
print(f'The index of {n} is {pos}.')
alist = [3, 12, 4, 5, 16, 10, 7]
n = int(input('n: '))
pos = -1
if n in alist:
pos = alist.index(n)
if pos == -1:
print('Not found.')
else:
print(f'The index of {n} is {pos}.')
alist = list(range(1, 6))
print(alist)
n = len(alist)
for i in range(n):
alist.append(alist[i]*2)
print(alist)
random.randrange(): 參數設定規則與 range() 相同
import random
alist = []
for i in range(5):
rnum = random.randrange(1, 51)
alist.append(rnum)
print(alist)
sorted(): 可對字串或串列排序,排序結果存到串列
import random
alist = []
for i in range(5):
rnum = random.randrange(1,51)
alist.append(rnum)
print(alist)
# 升冪排序
alist = sorted(alist)
print(alist)
# 降冪排序
alist = sorted(alist, reverse=True)
print(alist)
氣泡排序、選擇排序、插入排序
import random
# 設定亂數種子
random.seed(5)
alist = []
for i in range(5):
rnum = random.randrange(1,51)
alist.append(rnum)
print(alist)
n = 3
m = 4
print("1D index -> 2D index")
for i in range(n*m):
ri = i // m
ci = i % m
print(f"i: {i:2d} -> ri: {ri} ci: {ci}")
n = 3
m = 4
print("2D index -> 1D index")
for ri in range(n):
for ci in range(m):
i = ri * m + ci;
print(f"ri: {ri} ci: {ci} -> i: {i:2d}")
| 試算表 | Python | 用途 |
|---|---|---|
| SUM() | sum() | 合計 |
| COUNT() COUNTIF() |
1. len() 2. count() |
1. 計算容器資料個數;計算字串字元個數 2. 計算容器內指定資料個數 |
| AVERAGE() | sum()/len() | 平均 |
| MAX() | max() | 取最大值 |
| MIN() | min() | 取最小值 |
| STDEV.P() 母體標準差 STDEVP() 母體標準差 POWER() 指數 SQRT() 平方根 |
pow() 指數 math.sqrt() 平方根 |
計算標準差 |
numbers = list(range(1, 11))
print(numbers)
print('sum():', sum(numbers))
print('len():', len(numbers))
print('Average:', sum(numbers) / len(numbers))
print('max():', max(numbers))
print('min():', min(numbers))
import random
numbers = []
for i in range(11):
numbers.append(random.randint(10, 99))
print(numbers)
print('sum():', sum(numbers))
print('len():', len(numbers))
avg = sum(numbers) / len(numbers)
print('avg:', avg)
print('Average:', round(avg, 2))
print('max():', max(numbers))
print('min():', min(numbers))
# 大於小於平均
"""
# ex(+).
# 分列輸出大於及小於平均數的數
[輸出]
大於平均 82 95 87 77
小於平均 71 63 54 64 59
"""
numbers = [71, 82, 63, 54, 95, 87, 64, 77, 59]
print(numbers)
avg = int(sum(numbers) / len(numbers))
print(avg)
# 計算資料個數
"""
# ex(+).
其中一行會發生執行錯誤
"""
print(len(('a', 'b', 'c', 'x', 'y', 'z')))
print(len('something'))
print(len(('something', 'nothing', 'everything')))
print(len((1, 2, 3, 4, 5)))
print(len('1234567'))
print(len(tuple('123456789')))
print(len(12345))
# 計算容器內指定資料個數
alist = ['a', 'b', 'c', 'a', 'x', 'b', 'y', 'b', 'z']
print(alist.count('a'))
print(alist.count('b'))
print(alist.count('c'))
print(alist.count('d'))
# 輸入數值存至 list
numbers = []
for i in range(1, 6):
anum = input('Enter number {}: '.format(i))
numbers.append(int(anum))
print(numbers)
# 挑出 list 內的最大數及最小數
print(max(numbers))
print(min(numbers))
# 計算正數平均
"""
# ex(+).
# 以 atotal 儲存要平均的數值總和
# 以 acount 儲存要平均的數值個數
# range(int) 不可放固定整數
"""
alist = [32, 4.5, -16, 0, 18, 27]
atotal = 0
acount = 0
print('Answer:', (32+4.5+18+27)/4)
# 求最小數
"""
# ex(+).
# 不可使用 min()
"""
alist = [32, 4.5, -16, 0, 18, 27]
min_num = alist[0]
import math
scores = (45, 56, 67, 78, 89)
n = len(scores)
avg = sum(scores) / n
sigma = 0
for i in scores:
sigma += pow(i-avg, 2)
print(math.sqrt(sigma/n))
scores = (45, 56, 67, 78, 89)
n = len(scores)
avg = sum(scores) / n
sigma = 0
for i in scores:
sigma += (i-avg)**2
print((sigma/n)**0.5)
"""
[輸入]
Jane
John
[輸出]
hello, Jane
hello, John
"""
while True:
try:
# 讀取一行字串
s = input()
# 依題意輸出訊息
print('hello, ' + s)
except EOFError:
break
"""
[輸入]
8
21
7
12
[輸出]
even
odd
odd
even
"""
while True:
try:
# 讀取一行字串,將字串轉成整數
n = int(input())
# 偶數除以 2 的餘數為 0
# 奇數除以 2 的餘數為 1
if n % 2 == 0:
print('even')
elif n % 2 == 1:
print('odd')
except EOFError:
break
"""
[輸入]
10 20
30 12
[輸出]
10
18
"""
while True:
try:
# a, b = list_object: 整數串列中有 2 個整數,用 2 個變數分配儲存
a, b = list(map(int, input().split()))
# 使用絕對值函式 abc()
print(abs(a-b))
except EOFError:
break
"""
[輸入]
5 9 1 6 8
9 8 7
1 7 3 8
[輸出]
29
24
19
"""
while True:
try:
alist = list(map(int, input().split()))
# 用合計函式 sum() 將整數 list 中的全部整數加總
print(sum(alist))
except EOFError:
break
"""
[輸入]
10 20 35
30 12 24 48
[輸出]
25
36
"""
while True:
try:
alist = list(map(int, input().split()))
# 用最大值函式 max() 取出整數 list 中的最大數
max_value = max(alist)
# 用最小值函式 min() 取出整數 list 中的最小數
min_value = min(alist)
result = max_value - min_value
print(result)
except EOFError:
break
"""
[輸入]
5
9
1
6
8
-1
9
8
7
-1
[輸出]
29
24
"""
while True:
try:
# 迴圈前設定 total 變數 為 0
# 準備在迴圈內將整數累加到 total
total = 0
while True:
n = int(input())
if n == -1:
# 離開迴圈前輸出 total
print(total)
# 離開本層迴圈
break
# 將整數 n 加到 total
total += n
except EOFError:
break
"""
[輸入]
4
5 9 1 6 8
9 8 7
1 7 3 8
1 3 1 4 9 8 7
[輸出]
5.80
8.00
4.75
4.71
"""
while True:
try:
n = int(input())
for i in range(n):
alist = list(map(int, input().split()))
# 用計算函式 len() 計算 list 的數據個數
average = sum(alist) / len(alist)
print(f'{average:.2f}')
except EOFError:
break
"""
[輸入]
7
5 9 1 6 8 8 8
1 3 1 4 9 8 7
[輸出]
6 12 2 10 17 16 15
"""
while True:
try:
n = int(input())
# alist: 整數 list
alist = list(map(int, input().split()))
# blist: 整數 list
blist = list(map(int, input().split()))
# clist: 空的 list
clist = []
for i in range(n):
# 用 indexing 操作取出兩個整數 list 的第 i 個整數後相加
# 用 list.append() 方法將上下兩數合計值新增到 clist
clist.append(alist[i] + blist[i])
# 展開輸出 clist 中的整數
print(*clist)
except EOFError:
break
"""
[輸入]
6 12 2 10 17 16 15
[輸出]
2 6 10 12 15 16 17
17 16 15 12 10 6 2
17 16 15
"""
while True:
try:
alist = list(map(int, input().split()))
# 由小到大排序
alist.sort()
print(*alist)
# 由大到小排序
alist.sort(reverse=True)
print(*alist)
# 用 slicing 操作取出前三大整數
print(*alist[:3])
except EOFError:
break
"""
[輸入]
4
A 10 1 1.0
B 20 8 0.8
C 30 5 0.9
A 10 12 0.8
3
E 12 12 0.8
F 28 4 0.9
E 36 2 0.95
[輸出]
369
284
"""
while True:
try:
n = int(input())
total = 0
for i in range(n):
# 一行字串含字母、整數、浮點數字串,不可以使用 map()
alist = input().split()
# 將第 2 個和第 3 個字串轉成整數
price = int(alist[1])
quantity = int(alist[2])
# 將第 4 個字串轉成浮點數
discount = float(alist[3])
total += price * quantity * discount
print(int(total))
except EOFError:
break