說明
以下是我學習python基礎語法所完成的操作樣例
代碼位置:https://github.com/duganlx/fopnp
兩個數相加
def add(a, b):
return a + b
m, n = input('請輸入兩個數,用空格隔開:').split(' ')
print('{0} + {1} = {2}'.format(float(m), float(n), add(float(m), float(n))))
運行效果:
請輸入兩個數,用空格隔開:1 2
1.0 + 2.0 = 3.0
三數比大小
def sort(a, b):
return (a, b) if (a > b) else (b, a)
n1, n2, n3 = input('請輸入三個數,以空格隔開:').split(' ')
n1 = int(n1)
n2 = int(n2)
n3 = int(n3)
(n1, n2) = sort(n1, n2)
(n1, n3) = sort(n1, n3)
(n2, n3) = sort(n2, n3)
print("{}>{}>{}".format(n1, n2, n3))
運行效果:
請輸入三個數,以空格隔開:2 3 5
5>3>2
算平方根
def sqrt(num):
return num ** 0.5
num = float(input('輸入一個數:'))
print('%0.3f 的平方根爲 %0.3f' % (num, sqrt(num)))
運行效果:
輸入一個數:9
9.000 的平方根爲 3.000
計算三角形面積
def getTriangleArea(a, b, c):
return (a + b + c) / 2
a = float(input('請輸入第一條邊:'))
b = float(input('請輸入第二條邊:'))
c = float(input('請輸入第三條邊:'))
print('面積爲:', getTriangleArea(a, b, c))
運行效果:
請輸入第一條邊:3
請輸入第二條邊:4
請輸入第三條邊:5
面積爲: 6.0
解二次方程式
import cmath
def getRes(a, b, c):
d = (b ** 2) - (4 * a * c)
sol1 = (-b - cmath.sqrt(d)) / (2 * a)
sol2 = (-b + cmath.sqrt(d)) / (2 * a)
return sol1, sol2
a = float(input('輸入二次項係數:'))
b = float(input('輸入一次項係數:'))
c = float(input('輸入常數項係數:'))
print('該方程結果爲:', getRes(a, b, c))
運行效果:
輸入二次項係數:1
輸入一次項係數:2
輸入常數項係數:1
該方程結果爲: ((-1+0j), (-1+0j))
交換兩個變量
def swop(a, b):
return b, a
x = input("輸入x的值:")
y = input("輸入y的值:")
x, y = swop(x, y)
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
運行效果:
輸入x的值:5
輸入y的值:10
The value of x after swapping: 10
The value of y after swapping: 5
產生隨機數
import random
i = 1
for i in range(0, 10):
print(random.randint(0, 9), end=' ')
運行效果:
1 3 1 5 9 7 9 7 2 5
將公里數轉換爲英里數
def km2mi(num):
conv_fac = 0.621371
return num * conv_fac
kilometers = float(input('請輸入一個公里數:'))
print('%0.3f kilometers is equal to %0.3f miles' % (kilometers, km2mi(kilometers)))
運行效果:
請輸入一個公里數:10
10.000 kilometers is equal to 6.214 miles
將攝氏溫度轉換爲華氏溫度
def tdc2ftt(celsius):
return (celsius * 1.8) + 32
celsius = float(input('請輸入一個攝氏度值:'))
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius, tdc2ftt(celsius)))
運行效果:
請輸入一個攝氏度值:10
10.0 degree Celsius is equal to 50.0 degree Fahrenheit
檢查數字是正數,負數還是零
n = float(input('請輸入一個數:'))
if n > 0:
print('這是一個正數')
elif n < 0:
print('這是一個負數')
else:
print('零')
運行效果:
請輸入一個數:0
零
檢查數字是奇數還是偶數
number = int(input('輸入一個整數'))
if number % 2 == 0:
print('偶數')
else:
print('奇數')
運行效果:
輸入一個整數5
奇數
檢查是否閏年
def isLeapYear(year):
if year % 100 == 0:
return True if (year % 400 == 0) else False
else:
return True if (year % 4 == 0) else False
year = int(input('請輸入一個年份:'))
if isLeapYear(year):
print('閏年')
else:
print('不是閏年')
運行效果:
請輸入一個年份:2019
不是閏年
找到三個數字中的最大數
def max(a, b):
return a if (a > b) else b
num1 = float(input('輸入第一個數:'))
num2 = float(input('輸入第二個數:'))
num3 = float(input('輸入第三個數:'))
res = max(num1, max(num2, num3))
print('最大的數是:', res)
運行效果:
輸入第一個數:5
輸入第二個數:23
輸入第三個數:10
最大的數是: 23.0
檢查是否質數
def isPrimeNum(num):
for i in range(2, num - 1):
if num % i == 0:
return False
return True
num = int(input('請輸入一個整數:'))
if isPrimeNum(num):
print('質數')
else:
print('合數')
運行效果:
請輸入一個整數:29
質數
以間隔打印出所有質數
def isPrimeNum(num):
if num == 1 or num == 2:
return True
for i in range(2, num - 1):
if num % i == 0:
return False
return True
maxNum = int(input('請輸入一個最大數:'))
for n in range(1, maxNum):
if isPrimeNum(n):
print(n, end=' ')
運行效果:
請輸入一個最大數:100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
找數字的因子
def getFactor(num):
arr = []
for i in range(1, num):
if num % i == 0:
arr.append(i)
return arr
num = int(input('請輸入一個數:'))
print('因子爲', getFactor(num))
運行效果:
請輸入一個數:20
因子爲 [1, 2, 4, 5, 10]
顯示乘法表
def multiplicationtable():
for i in range(1, 10):
for j in range(1, i + 1):
print("%d * %d = %d " % (j, i, j * i), end=' ')
print(' ')
multiplicationtable()
運行效果:
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
打印 Fibonacci 數列
def getFibonacci(num):
if num == 1:
return [1]
arr = [1, 1]
for i in range(2, num):
arr.append(arr[i - 1] + arr[i - 2])
return arr
num = int(input('請輸入打印到Fibonacci第幾項:'))
print('結果爲', getFibonacci(num))
運行效果:
請輸入打印到Fibonacci第幾項:10
結果爲 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
檢查 Armstrong 數
import math
def isArmstrong(num):
sum = int(0)
n = int(num)
while n != 0:
temp = int(n % 10)
n = int(n / 10)
sum += math.pow(temp, 3)
if sum == num:
return True
else:
return False
num = int(input('請輸入一個三位數整數:'))
if isArmstrong(num):
print(num, '是水仙花數')
else:
print(num, '不是水仙花數')
運行效果:
請輸入一個三位數整數:123
123 不是水仙花數
在間隔中查找 Armstrong 數
import math
def isArmstrong(num):
sum = int(0)
n = int(num)
while n != 0:
temp = int(n % 10)
n = int(n / 10)
sum += math.pow(temp, 3)
if sum == num:
return True
else:
return False
num = int(input('請輸入範圍最大值:'))
for i in range(100, num):
if isArmstrong(i):
print(i, end=' ')
運行效果:
請輸入範圍最大值:1000
153 370 371 407
算自然數之和
def sum(num1, num2):
return num1 + num2
n1 = float(input('請輸入一個自然數:'))
n2 = float(input('請輸入另一個自然數:'))
print('求和結果爲:', sum(n1, n2))
運行效果:
請輸入一個自然數:10
請輸入另一個自然數:30
求和結果爲: 40.0
用函數顯示2的次方
import math
def showPower(n):
return math.pow(2, n)
num = int(input('請輸入想查看2的幾次方:'))
print('結果爲', showPower(num))
運行效果:
請輸入想查看2的幾次方:6
結果爲 64.0
計算可被另一個數字整除的數字
def getFactor(num):
arr = []
for i in range(1, num):
if num % i == 0:
arr.append(i)
return arr
num = int(input('請輸入一個數:'))
print('它可以被', getFactor(num), '整除')
運行效果:
請輸入一個數:30
它可以被 [1, 2, 3, 5, 6, 10, 15] 整除
十進制轉換爲二進制,八進制和十六進制
num = int(input('請輸入一個數字:'))
print('二進制結果爲:', bin(num))
print('八進制結果爲:', oct(num))
print('十六進制結果爲:', hex(num))
運行效果:
請輸入一個數字:10
二進制結果爲: 0b1010
八進制結果爲: 0o12
十六進制結果爲: 0xa
找字符的 ASCII 值
def findAscii(n):
return ord(n)
print('該字符的ASCII值爲:', findAscii(input('請輸入一個字符:')))
運行效果:
請輸入一個字符:a
該字符的ASCII值爲: 97
計算 HCF 或 GCD(最大公約數)
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a % b)
n, m = input('請輸入兩個數').split(' ')
print(gcd(int(n), int(m)))
運行效果:
請輸入兩個數10 30
10
計算 LCM(最小公倍數)
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a % b)
def lcm(a, b):
return a * b / gcd(a, b)
n, m = input('請輸入兩個數').split(' ')
print(lcm(int(n), int(m)))
運行效果:
請輸入兩個數10 30
30.0
找數字的因子
def getFactor(num):
arr = []
for i in range(1, num):
if num % i == 0:
arr.append(i)
return arr
num = int(input('請輸入一個數:'))
print('因子爲', getFactor(num))
運行效果:
請輸入一個數:40
因子爲 [1, 2, 4, 5, 8, 10, 20]
製作簡單計算器
import re
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
def cal(flag, a, b):
if re.match('add', flag):
return add(a, b)
elif re.match('sub', flag):
return sub(a, b)
elif re.match('mul', flag):
return mul(a, b)
elif re.match('div', flag):
return div(a, b)
else:
return 'err'
operation = input('請輸入操作碼(add, sub, mul, div):')
n, m = input('請輸入兩個數').split(' ')
print('計算結果爲:', cal(operation, int(n), int(m)))
運行效果:
請輸入操作碼(add, sub, mul, div):sub
請輸入兩個數10 30
計算結果爲: -20
發牌程序
import random
import operator
def getPokers():
pokers = []
poker = []
for i in ['♥', '♠', '♦', '♣']:
for j in ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']:
poker.append(i)
poker.append(j)
pokers.append(poker)
poker = []
return pokers
pokers = getPokers()
random.shuffle(pokers) # 將序列的所有元素隨機排序
li = {}
for player in ['player1', 'player2', 'player3', 'player4']:
b = random.sample(pokers, 13)
for s in b:
pokers.remove(s)
li.setdefault(player, b)
print('player1:', sorted(li['player1'], key=operator.itemgetter(0, 1))) # operator.itemgetter(0, 1)根據花色和數字來排序
print('player2:', sorted(li['player2'], key=operator.itemgetter(0, 1)))
print('player3:', sorted(li['player3'], key=operator.itemgetter(0, 1)))
print('player4:', sorted(li['player4'], key=operator.itemgetter(0, 1)))
運行效果:
player1: [['♠', '10'], ['♠', '3'], ['♠', '5'], ['♠', 'J'], ['♣', '2'], ['♣', '4'], ['♣', '7'], ['♣', '8'], ['♣', 'A'], ['♣', 'Q'], ['♥', '2'], ['♥', '4'], ['♦', '3']]
player2: [['♠', '2'], ['♠', '7'], ['♣', '5'], ['♣', '9'], ['♣', 'J'], ['♥', '3'], ['♥', '5'], ['♥', '6'], ['♥', 'J'], ['♥', 'K'], ['♦', '10'], ['♦', '8'], ['♦', 'K']]
player3: [['♠', '4'], ['♠', '6'], ['♠', '8'], ['♠', 'Q'], ['♣', '10'], ['♣', 'K'], ['♥', '7'], ['♥', '8'], ['♥', 'A'], ['♥', 'Q'], ['♦', '5'], ['♦', '9'], ['♦', 'J']]
player4: [['♠', '9'], ['♠', 'A'], ['♠', 'K'], ['♣', '3'], ['♣', '6'], ['♥', '10'], ['♥', '9'], ['♦', '2'], ['♦', '4'], ['♦', '6'], ['♦', '7'], ['♦', 'A'], ['♦', 'Q']]
顯示日曆
import calendar
# 設置第一天是星期天
calendar.setfirstweekday(firstweekday=6)
n = int(input('請輸入所查看日曆的級別 1(輸出全年),2(輸出某月):'))
if n == 1:
yy = int(input("輸入年份: "))
cal = calendar.TextCalendar()
cal.pryear(yy)
if n == 2:
yy = int(input("輸入年份: "))
mm = int(input("輸入月份: "))
print(calendar.month(yy, mm))
運行效果:
請輸入所查看日曆的級別 1(輸出全年),2(輸出某月):2
輸入年份: 2019
輸入月份: 5
May 2019
Su Mo Tu We Th Fr Sa
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
用遞歸顯示 Fibonacci 數列
def Fibonacci(n):
if n <= 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
n = int(input("輸入一個正整數n,n爲輸出項數:"))
for i in range(1, n + 1):
print(Fibonacci(i), end=' ')
運行效果:
輸入一個正整數n,n爲輸出項數:5
1 1 2 3 5
用遞歸找整數之和
def sum(n):
if n == 1:
return 1
else:
return sum(n - 1) + n
i = int(input('輸入一個整數:'))
print('其整數之和爲:', (sum(i)))
運行效果:
輸入一個整數:10
其整數之和爲: 55
用遞歸算階層
def Factorial(n):
if n == 0:
return 1
else:
return n * Factorial(n - 1)
i = int(input('輸入一個整數:'))
print(i, '的階乘爲', Factorial(i))
運行效果:
輸入一個整數:10
10 的階乘爲 3628800
用遞歸將十進制轉換爲二進制
def dec2bin(n):
result = "0"
if n == 0:
return result
else:
result = dec2bin(n // 2)
return result + str(n % 2)
n = int(input("請輸入一個十進制的數字:"))
print(dec2bin(n))
運行效果:
請輸入一個十進制的數字:10
01010
說明:
語句result = dec2bin(n // 2)
中的//
代表整數除法,若時/
則表示浮點數除法
添加兩個矩陣
import numpy
A = numpy.mat('1,2;3,4')
B = numpy.array([[3, 2], [3, 4], [9, 6]])
print(A)
print('')
print(B)
運行效果:
[[1 2]
[3 4]]
[[3 2]
[3 4]
[9 6]]
轉置矩陣
import numpy
A = numpy.array([[3, 2], [3, 4], [9, 6]])
print(A)
print('')
print(A.T)
運行效果:
[[3 2]
[3 4]
[9 6]]
[[3 3 9]
[2 4 6]]
兩個矩陣相乘
import numpy
A = numpy.array([[3, 2], [3, 4], [9, 6]])
B = numpy.array([[3, 1, 2], [3, 6, 4]])
C = numpy.dot(A, B)
print("A:\n", A)
print("B:\n", B)
print("A×B:\n", C)
運行效果:
A:
[[3 2]
[3 4]
[9 6]]
B:
[[3 1 2]
[3 6 4]]
A×B:
[[15 15 14]
[21 27 22]
[45 45 42]]
檢查字符串是否爲迴文
s = input("輸入一個字符串:")
d = ''.join(reversed(s))
print(d)
if s == d:
print("字符串是迴文")
else:
print("字符串不是迴文")
運行效果:
輸入一個字符串:abcba
abcba
字符串是迴文
說明:
str.join(sequence)
:通過指定字符str
來連接sequence
中元素生成新的字符串
示例:
str = "-";
seq = ("a", "b", "c"); # 字符串序列
print str.join( seq );
# 輸出
a-b-c
從字符串中刪除標點符號
import string
i = input("輸入一條帶標點的字符串(英文標點):")
print("".join(i.split('.')))
運行效果:
adfjkdffgdkfjk
按字母順序排序的單詞
list = ["delphi", "java", "python", "python", "c++", "c", "golang"]
list.sort(reverse=False) # 按降序排列
print(list)
運行效果:
['c', 'c++', 'delphi', 'golang', 'java', 'python', 'python']
不同集合的操作
set1 = set([1, 2, 3, 4, 5])
set2 = set([0, 2, 3, 6, 7])
print('交集', set1 & set2)
print('並集', set1 | set2)
print('差集', set1 - set2)
運行效果:
交集 {2, 3}
並集 {0, 1, 2, 3, 4, 5, 6, 7}
差集 {1, 4, 5}
來計算每個元音的數量
str = input('請輸入一個字符串')
strList = list(str)
a = 0
e = 0
i = 0
o = 0
u = 0
for n in range(0, len(strList)):
if strList[n] == 'a':
a = a + 1
elif strList[n] == 'e':
e = e + 1
elif strList[n] == 'i':
i = i + 1
elif strList[n] == 'o':
o = o + 1
elif strList[n] == 'u':
u = u + 1
print('a:', a, 'e:', e, 'i:', i, 'o:', o, 'u:', u)
運行效果:
a: 1 e: 1 i: 0 o: 0 u: 0
用於郵件的合併
from mailmerge import MailMerge
doc = MailMerge("./Ex44_file/test.docx")
doc.merge(
username="ddu",
clazz="17計算機科學與技術"
)
doc.write("./Ex44_file/res.docx")
運行效果:
# test.docx內容
我叫 «username»
我的班級是 «clazz»
# res.docx內容
我叫 ddu
我的班級是 17計算機科學與技術
找圖像大小分辨率
from PIL import Image
fileName = "./Ex45_file/tuxiang.jpg"
img = Image.open(fileName)
imgSize = img.size
print(imgSize)
運行效果:
(471, 472)
文件的雜湊搜尋(哈希表)
# 實現hashtable,指定在key位置存入data
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, value):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] is None: # 如果slot內是空值,則存進去
self.slots[hashvalue] = key
self.data[hashvalue] = value
else: # slot內已有key
if self.slots[hashvalue] == key: # 如果已有值等於key,更新data
self.data[hashvalue] = value
else: # 如果slot不等於key,找下一個爲None的地方
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] is not None and self.slots[nextslot] != key:
nextslot = self.rehash(nextslot, len(self.slots))
if self.slots[nextslot] is None:
self.slots[nextslot] = key
self.data[nextslot] = value
else:
self.data[nextslot] = value
def rehash(self, oldhash, size):
return (oldhash + 1) % size
# 散列函數
def hashfunction(self, key, size):
return key % size
def get(self, key):
startslot = self.hashfunction(key, len(self.slots))
data = None
found = False
stop = False
pos = startslot
while pos is not None and not found and not stop:
if self.slots[pos] == key:
found = True
data = self.data[pos]
else:
pos = self.rehash(pos, len(self.slots))
# 回到了原點,表示找遍了沒有找到
if pos == startslot:
stop = True
return data
# 重載載 __getitem__ 和 __setitem__ 方法以允許使用 [] 訪問
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.put(key, value)
if __name__ == '__main__':
H = HashTable()
H[54] = "cat"
H[26] = "dog"
H[93] = "lion"
H[17] = "tiger"
H[77] = "bird"
H[31] = "cow"
H[44] = "goat"
H[55] = "pig"
H[20] = "chicken"
print(H.slots) # [77, 44, 55, 20, 26, 93, 17, None, None, 31, 54]
print(H.data) # ['bird', 'goat', 'pig', 'chicken', 'dog', 'lion', 'tiger', None, None, 'cow', 'cat']
print(H[20]) # 'chicken'
H[20] = 'duck'
print(H[20]) # duck
print(H[99]) # None
運行效果:
[77, 44, 55, 20, 26, 93, 17, None, None, 31, 54]
['bird', 'goat', 'pig', 'chicken', 'dog', 'lion', 'tiger', None, None, 'cow', 'cat']
chicken
duck
None