编程 - 实现简单功能:Python

 

 

1. 52周存钱挑战

 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. 利用递归函数绘制分形树

 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.47
 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.基础代谢率计算

 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.模拟掷骰子

 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), 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.输入某年某月某日,判断这一天是这一年的第几天?

 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()

 

posted @ 2021-02-20 21:26  划水De雁小明  阅读(187)  评论(0编辑  收藏  举报