1. 3位整數逆序python
num = input("請輸入一個三位整數:") print(num[::-1])
2. if - else 練習正則表達式
sex = input('請輸入您的性別(F 或 M): ') age = int(input("請輸入您的年齡: ")) if sex == "M": if age < 30: print('young') elif age <= 36: print('marriageable age') else: print('old') elif sex == 'F': if age < 25: print('young') elif age <= 30: print('marriageable age') else: print('old') else: print('wrong')
3. if-else 和 數學計算 練習學習
#Python學習交流羣:778463939 my_str = input("What's the temperature? ") if my_str[-1] in ['F', 'f']: C = round((eval(my_str[0:-1]) - 32) / 1.8, 1) print(f"The converted temperature is {C}C.") elif my_str[-1] in ['C', 'c']: F = round(1.8 * eval(my_str[0:-1]) + 32, 1) print(f"The converted temperature is {F}F.") else: print("input error my dear.")
4. 循環: 文件讀寫code
with open("movie.txt") as f_in: with open("out.txt") as f_out: for line in f_in: # 假設每行數據, 分割符是 ',' line_list = line.split(',') # 時長 Lasting 是最後一列 if line_list[-1] < 90: # 將該行序號寫到 out.txt f_out.write(str(line_list[0]))
5.循環練習: 親密數排序
#Python學習交流羣:778463939 x = int(input("請輸入一個正整數: ")) for a in range(2, x): b = 0 for i in range(1, a): if a % i == 0: b += i r = 0 for j in range(1, b): if b % j == 0: r += j if r == a and a < b: print(a, b)
6.循環: 邏輯判斷get
n = int(input('請輸入最大兵力人數: ')) for i in range(n + 1): if (i % 3 == 2) and (i % 5 == 1) and (i % 7 == 0): print(i, end=' ')
7.列表推導式input
num = int(input("請輸入一個 1-100 間的整數: ")) print([i for i in range(1, num + 1) if i % 2 != 0])
8.正則表達式數學
# 匹配: 首字母爲 '數字或下劃線, 其他字母爲 字母,數字,下劃線' import re my_str = input("請輸入您將要註冊的用戶名: ") ret = re.match(r"[a-z_]?[a-z\d\s_]*", my_str) print(ret.group()) print(True) if ret else print(False)
9.字典按值排序it
import operator int(input("輸入您要處理的整數個數: ")) num_lst = list(map(int, input("請在一行輸入, 兩兩間用 空格 隔開").split())) my_dict = {} for num in num_lst: if num not in my_dict: my_dict[num] = 1 else: my_dict[num] += 1 items = sorted(my_dict.items(), key=operator.itemgetter(1), reverse=True) for i, j in items: print(str(i) + ' ' + str(j))