1. 52周存錢挑戰app
1 import math 2 import datetime 3 4 5 def save_money_in_n_weeks(money_per_week, increase_money, total_week): 6 """ 7 計算n周內的存款金額 8 """ 9 10 money_list = [] # 記錄每週存款數的列表 11 saved_money_list = [] # 記錄每週帳戶累計 12 13 for i in range(total_week): 14 money_list.append(money_per_week) 15 saving = math.fsum(money_list) 16 saved_money_list.append(saving) 17 18 # 輸出信息 19 # print('第{}周,存入{}元,帳戶累計{}元'.format(i + 1, money_per_week, saving)) 20 21 # 更新下一週的存錢金額 22 money_per_week += increase_money 23 24 return saved_money_list 25 26 27 def main(): 28 """ 29 主函數 30 """ 31 money_per_week = float(input('請輸入每週的存入的金額:')) # 每週的存入的金額 32 increase_money = float(input('請輸入每週的遞增金額:')) # 遞增的金額 33 total_week = int(input('請輸入總共的週數:')) # 總共的週數 34 35 # 調用函數 36 saved_money_list = save_money_in_n_weeks(money_per_week, increase_money, total_week) 37 38 input_date_str = input('請輸入日期(yyyy/mm/dd):') 39 input_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d') 40 week_num = input_date.isocalendar()[1] 41 print('第{}周的存款:{}元'.format(week_num, saved_money_list[week_num - 1])) 42 43 if __name__ == '__main__': 44 main()
2. 利用遞歸函數繪製分形樹dom
1 import turtle 2 3 4 def draw_branch(branch_length): 5 """ 6 繪製分形樹 7 """ 8 if branch_length > 5: 9 # 繪製右側樹枝 10 turtle.forward(branch_length) 11 print('向前 ', branch_length) 12 turtle.right(20) 13 print('右轉 20') 14 draw_branch(branch_length - 15) 15 16 # 繪製左側樹枝 17 turtle.left(40) 18 print('左轉 40') 19 draw_branch(branch_length - 15) 20 21 # 返回以前的樹枝 22 turtle.right(20) 23 print('右轉 20') 24 turtle.backward(branch_length) 25 print('向後 ', branch_length) 26 27 28 def main(): 29 """ 30 主函數 31 """ 32 turtle.left(90) 33 turtle.penup() 34 turtle.backward(150) 35 turtle.pendown() 36 turtle.color('brown') 37 draw_branch(80) 38 turtle.exitonclick() 39 40 if __name__ == '__main__': 41 main()
3. 五角星的繪製函數
1 import turtle 2 3 4 def draw_pentagram(size): 5 """ 6 繪製五角星 7 """ 8 # 計數器 9 count = 1 10 while count <= 5: 11 turtle.forward(size) 12 turtle.right(144) 13 # count = count + 1 14 count += 1 15 16 17 def draw_recursive_pentagram(size): 18 """ 19 迭代繪製五角星 20 """ 21 # 計數器 22 count = 1 23 while count <= 5: 24 turtle.forward(size) 25 turtle.right(144) 26 # count = count + 1 27 count += 1 28 29 # 五角星繪製完成,更新參數 30 size += 10 31 if size <= 100: 32 draw_recursive_pentagram(size) 33 34 35 def main(): 36 """ 37 主函數 38 """ 39 40 turtle.penup() 41 turtle.backward(200) 42 turtle.pendown() 43 turtle.pensize(2) 44 turtle.pencolor('red') 45 46 size = 50 47 draw_recursive_pentagram(size) 48 49 turtle.exitonclick() 50 51 if __name__ == '__main__': 52 main()
4. 匯率兌換工具
1 def main(): 2 """ 3 主函數 4 """ 5 # 匯率 6 USD_VS_RMB = 6.77 7 8 # 帶單位的貨幣輸入 9 currency_str_value = input('請輸入帶單位的貨幣金額:') 10 11 unit = currency_str_value[-3:] 12 13 if unit == 'CNY': 14 exchange_rate = 1 / USD_VS_RMB 15 16 elif unit == 'USD': 17 exchange_rate = USD_VS_RMB 18 19 else: 20 exchange_rate = -1 21 22 if exchange_rate != -1: 23 in_money = eval(currency_str_value[:-3]) 24 # 使用lambda定義函數 25 convert_currency2 = lambda x: x * exchange_rate 26 27 # # 調用函數 28 # out_money = convert_currency(in_money, exchange_rate) 29 30 # 調用lambda函數 31 out_money = convert_currency2(in_money) 32 print('轉換後的金額:', out_money) 33 else: 34 print('不支持該種貨幣!') 35 36 if __name__ == '__main__': 37 main()
5.基礎代謝率計算spa
1 def main(): 2 """ 3 主函數 4 """ 5 y_or_n = input('是否退出程序(y/n)?') 6 7 while y_or_n != 'y': 8 # # 性別 9 # gender = input('性別:') 10 # # print(type(gender)) 11 # 12 # # 體重 (kg) 13 # weight = float(input('體重(kg):')) 14 # # print(type(weight)) 15 # 16 # # 身高 (cm) 17 # height = float(input('身高(cm):')) 18 # # print(type(height)) 19 # 20 # # 年齡 21 # age = int(input('年齡:')) 22 # # print(type(age)) 23 print('請輸入如下信息,用空格分割') 24 input_str = input('性別 體重(kg) 身高(cm) 年齡:') 25 str_list = input_str.split(' ') 26 27 try: 28 gender = str_list[0] 29 weight = float(str_list[1]) 30 height = float(str_list[2]) 31 age = int(str_list[3]) 32 33 if gender == '男': 34 # 男性 35 bmr = (13.7 * weight) + (5.0 * height) - (6.8 * age) + 66 36 elif gender == '女': 37 # 女性 38 bmr = (9.6 * weight) + (1.8 * height) - (4.7 * age) + 655 39 else: 40 bmr = -1 41 42 if bmr != -1: 43 print('您的性別:{},體重:{}公斤,身高:{}釐米,年齡:{}歲'.format(gender, weight, height, age)) 44 print('您的基礎代謝率:{}大卡'.format(bmr)) 45 else: 46 print('暫不支持該性別') 47 except ValueError: 48 print('請輸入正確的信息!') 49 except IndexError: 50 print('輸入的信息過少!') 51 except: 52 print('程序異常!') 53 54 print() # 輸出空行 55 y_or_n = input('是否退出程序(y/n)?') 56 57 58 if __name__ == '__main__': 59 main()
6.模擬擲骰子code
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 # 解決中文顯示問題 5 plt.rcParams['font.sans-serif'] = ['SimHei'] 6 plt.rcParams['axes.unicode_minus'] = False 7 8 9 def main(): 10 """ 11 主函數 12 """ 13 total_times = 10000 14 15 # 記錄骰子的結果 16 roll1_arr = np.random.randint(1, 7, size=total_times) 17 roll2_arr = np.random.randint(1, 7, size=total_times) 18 result_arr = roll1_arr + roll2_arr 19 20 hist, bins = np.histogram(result_arr, bins=range(2, 14)) 21 print(hist) 22 print(bins) 23 24 # 數據可視化 25 plt.hist(result_arr, bins=range(2, 14), normed=1, edgecolor='black', linewidth=1, rwidth=0.8) 26 27 # 設置x軸座標點顯示 28 tick_labels = ['2點', '3點', '4點', '5點', 29 '6點', '7點', '8點', '9點', '10點', '11點', '12點'] 30 tick_pos = np.arange(2, 13) + 0.5 31 plt.xticks(tick_pos, tick_labels) 32 33 plt.title('骰子點數統計') 34 plt.xlabel('點數') 35 plt.ylabel('頻率') 36 plt.show() 37 38 39 if __name__ == '__main__': 40 main()
7.輸入某年某月某日,判斷這一天是這一年的第幾天?orm
1 from datetime import datetime 2 3 4 def is_leap_year(year): 5 """ 6 判斷year是否爲閏年 7 是,返回True 8 否,返回False 9 """ 10 is_leap = False 11 12 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): 13 is_leap = True 14 15 return is_leap 16 17 18 def main(): 19 """ 20 主函數 21 """ 22 input_date_str = input('請輸入日期(yyyy/mm/dd):') 23 input_date = datetime.strptime(input_date_str, '%Y/%m/%d') 24 25 year = input_date.year 26 month = input_date.month 27 day = input_date.day 28 29 # # 包含30天 月份集合 30 # _30_days_month_set = {4, 6, 9, 11} 31 # _31_days_month_set = {1, 3, 5, 7, 8, 10, 12} 32 33 # 月份-天數 字典 34 month_day_dict = {1: 31, 35 2: 28, 36 3: 31, 37 4: 30, 38 5: 31, 39 6: 30, 40 7: 31, 41 8: 31, 42 9: 30, 43 10: 31, 44 11: 30, 45 12: 31} 46 47 day_month_dict = {30: {4, 6, 9, 11}, 48 31: {1, 3, 5, 7, 8, 10, 12}} 49 50 # 初始化值 51 days = 0 52 days += day 53 54 for i in range(1, month): 55 days += month_day_dict[i] 56 57 if is_leap_year(year) and month > 2: 58 days += 1 59 60 print('這是{}年的第{}天。'.format(year, days)) 61 62 63 if __name__ == '__main__': 64 main()
8. 判斷密碼強度對象
1 class PasswordTool: 2 """ 3 密碼工具類 4 """ 5 def __init__(self, password): 6 # 類的屬性 7 self.password = password 8 self.strength_level = 0 9 10 def process_password(self): 11 # 規則1:密碼長度大於8 12 if len(self.password) >= 8: 13 self.strength_level += 1 14 else: 15 print('密碼長度要求至少8位!') 16 17 # 規則2:包含數字 18 if self.check_number_exist(): 19 self.strength_level += 1 20 else: 21 print('密碼要求包含數字!') 22 23 # 規則3:包含字母 24 if self.check_letter_exist(): 25 self.strength_level += 1 26 else: 27 print('密碼要求包含字母!') 28 29 # 類的方法 30 def check_number_exist(self): 31 """ 32 判斷字符串中是否含有數字 33 """ 34 has_number = False 35 36 for c in self.password: 37 if c.isnumeric(): 38 has_number = True 39 break 40 41 return has_number 42 43 def check_letter_exist(self): 44 """ 45 判斷字符串中是否含有字母 46 """ 47 has_letter = False 48 for c in self.password: 49 if c.isalpha(): 50 has_letter = True 51 break 52 return has_letter 53 54 55 class FileTool: 56 """ 57 文件工具類 58 """ 59 def __init__(self, filepath): 60 self.filepath = filepath 61 62 def write_to_file(self, line): 63 f = open(self.filepath, 'a') 64 f.write(line) 65 f.close() 66 67 def read_from_file(self): 68 f = open(self.filepath, 'r') 69 lines = f.readlines() 70 f.close() 71 return lines 72 73 74 def main(): 75 """ 76 主函數 77 """ 78 79 try_times = 5 80 filepath = 'password_6.0.txt' 81 # 實例化文件工具對象 82 file_tool = FileTool(filepath) 83 84 while try_times > 0: 85 86 password = input('請輸入密碼:') 87 # 實例化密碼工具對象 88 password_tool = PasswordTool(password) 89 password_tool.process_password() 90 91 line = '密碼:{}, 強度:{}\n'.format(password, password_tool.strength_level) 92 # 寫操做 93 file_tool.write_to_file(line) 94 95 if password_tool.strength_level == 3: 96 print('恭喜!密碼強度合格!') 97 break 98 else: 99 print('密碼強度不合格!') 100 try_times -= 1 101 102 print() 103 104 if try_times <= 0: 105 print('嘗試次數過多,密碼設置失敗!') 106 107 # 讀操做 108 lines = file_tool.read_from_file() 109 print(lines) 110 111 112 if __name__ == '__main__': 113 main()