经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
编程 - 实现简单功能:Python
来源:cnblogs  作者:划水De雁晓明  时间:2021/2/22 9:10:15  对本文有异议

 

 

1. 52周存钱挑战

  1. 1 import math
  2. 2 import datetime
  3. 3
  4. 4
  5. 5 def save_money_in_n_weeks(money_per_week, increase_money, total_week):
  6. 6 """
  7. 7 计算n周内的存款金额
  8. 8 """
  9. 9
  10. 10 money_list = [] # 记录每周存款数的列表
  11. 11 saved_money_list = [] # 记录每周账户累计
  12. 12
  13. 13 for i in range(total_week):
  14. 14 money_list.append(money_per_week)
  15. 15 saving = math.fsum(money_list)
  16. 16 saved_money_list.append(saving)
  17. 17
  18. 18 # 输出信息
  19. 19 # print('第{}周,存入{}元,账户累计{}元'.format(i + 1, money_per_week, saving))
  20. 20
  21. 21 # 更新下一周的存钱金额
  22. 22 money_per_week += increase_money
  23. 23
  24. 24 return saved_money_list
  25. 25
  26. 26
  27. 27 def main():
  28. 28 """
  29. 29 主函数
  30. 30 """
  31. 31 money_per_week = float(input('请输入每周的存入的金额:')) # 每周的存入的金额
  32. 32 increase_money = float(input('请输入每周的递增金额:')) # 递增的金额
  33. 33 total_week = int(input('请输入总共的周数:')) # 总共的周数
  34. 34
  35. 35 # 调用函数
  36. 36 saved_money_list = save_money_in_n_weeks(money_per_week, increase_money, total_week)
  37. 37
  38. 38 input_date_str = input('请输入日期(yyyy/mm/dd):')
  39. 39 input_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d')
  40. 40 week_num = input_date.isocalendar()[1]
  41. 41 print('第{}周的存款:{}元'.format(week_num, saved_money_list[week_num - 1]))
  42. 42
  43. 43 if __name__ == '__main__':
  44. 44 main()

 

 

2. 利用递归函数绘制分形树

  1. 1 import turtle
  2. 2
  3. 3
  4. 4 def draw_branch(branch_length):
  5. 5 """
  6. 6 绘制分形树
  7. 7 """
  8. 8 if branch_length > 5:
  9. 9 # 绘制右侧树枝
  10. 10 turtle.forward(branch_length)
  11. 11 print('向前 ', branch_length)
  12. 12 turtle.right(20)
  13. 13 print('右转 20')
  14. 14 draw_branch(branch_length - 15)
  15. 15
  16. 16 # 绘制左侧树枝
  17. 17 turtle.left(40)
  18. 18 print('左转 40')
  19. 19 draw_branch(branch_length - 15)
  20. 20
  21. 21 # 返回之前的树枝
  22. 22 turtle.right(20)
  23. 23 print('右转 20')
  24. 24 turtle.backward(branch_length)
  25. 25 print('向后 ', branch_length)
  26. 26
  27. 27
  28. 28 def main():
  29. 29 """
  30. 30 主函数
  31. 31 """
  32. 32 turtle.left(90)
  33. 33 turtle.penup()
  34. 34 turtle.backward(150)
  35. 35 turtle.pendown()
  36. 36 turtle.color('brown')
  37. 37 draw_branch(80)
  38. 38 turtle.exitonclick()
  39. 39
  40. 40 if __name__ == '__main__':
  41. 41 main()

 

 

3. 五角星的绘制

  1. 1 import turtle
  2. 2
  3. 3
  4. 4 def draw_pentagram(size):
  5. 5 """
  6. 6 绘制五角星
  7. 7 """
  8. 8 # 计数器
  9. 9 count = 1
  10. 10 while count <= 5:
  11. 11 turtle.forward(size)
  12. 12 turtle.right(144)
  13. 13 # count = count + 1
  14. 14 count += 1
  15. 15
  16. 16
  17. 17 def draw_recursive_pentagram(size):
  18. 18 """
  19. 19 迭代绘制五角星
  20. 20 """
  21. 21 # 计数器
  22. 22 count = 1
  23. 23 while count <= 5:
  24. 24 turtle.forward(size)
  25. 25 turtle.right(144)
  26. 26 # count = count + 1
  27. 27 count += 1
  28. 28
  29. 29 # 五角星绘制完成,更新参数
  30. 30 size += 10
  31. 31 if size <= 100:
  32. 32 draw_recursive_pentagram(size)
  33. 33
  34. 34
  35. 35 def main():
  36. 36 """
  37. 37 主函数
  38. 38 """
  39. 39
  40. 40 turtle.penup()
  41. 41 turtle.backward(200)
  42. 42 turtle.pendown()
  43. 43 turtle.pensize(2)
  44. 44 turtle.pencolor('red')
  45. 45
  46. 46 size = 50
  47. 47 draw_recursive_pentagram(size)
  48. 48
  49. 49 turtle.exitonclick()
  50. 50
  51. 51 if __name__ == '__main__':
  52. 52 main()

 

 

4. 汇率兑换

  1. 1 def main():
  2. 2 """
  3. 3 主函数
  4. 4 """
  5. 5 # 汇率
  6. 6 USD_VS_RMB = 6.47
  7. 7
  8. 8 # 带单位的货币输入
  9. 9 currency_str_value = input('请输入带单位的货币金额:')
  10. 10
  11. 11 unit = currency_str_value[-3:]
  12. 12
  13. 13 if unit == 'CNY':
  14. 14 exchange_rate = 1 / USD_VS_RMB
  15. 15
  16. 16 elif unit == 'USD':
  17. 17 exchange_rate = USD_VS_RMB
  18. 18
  19. 19 else:
  20. 20 exchange_rate = -1
  21. 21
  22. 22 if exchange_rate != -1:
  23. 23 in_money = eval(currency_str_value[:-3])
  24. 24 # 使用lambda定义函数
  25. 25 convert_currency2 = lambda x: x * exchange_rate
  26. 26
  27. 27 # # 调用函数
  28. 28 # out_money = convert_currency(in_money, exchange_rate)
  29. 29
  30. 30 # 调用lambda函数
  31. 31 out_money = convert_currency2(in_money)
  32. 32 print('转换后的金额:', out_money)
  33. 33 else:
  34. 34 print('不支持该种货币!')
  35. 35
  36. 36 if __name__ == '__main__':
  37. 37 main()

 

 

5.基础代谢率计算

  1. 1 def main():
  2. 2 """
  3. 3 主函数
  4. 4 """
  5. 5 y_or_n = input('是否退出程序(y/n)?')
  6. 6
  7. 7 while y_or_n != 'y':
  8. 8 # # 性别
  9. 9 # gender = input('性别:')
  10. 10 # # print(type(gender))
  11. 11 #
  12. 12 # # 体重 (kg)
  13. 13 # weight = float(input('体重(kg):'))
  14. 14 # # print(type(weight))
  15. 15 #
  16. 16 # # 身高 (cm)
  17. 17 # height = float(input('身高(cm):'))
  18. 18 # # print(type(height))
  19. 19 #
  20. 20 # # 年龄
  21. 21 # age = int(input('年龄:'))
  22. 22 # # print(type(age))
  23. 23 print('请输入以下信息,用空格分割')
  24. 24 input_str = input('性别 体重(kg) 身高(cm) 年龄:')
  25. 25 str_list = input_str.split(' ')
  26. 26
  27. 27 try:
  28. 28 gender = str_list[0]
  29. 29 weight = float(str_list[1])
  30. 30 height = float(str_list[2])
  31. 31 age = int(str_list[3])
  32. 32
  33. 33 if gender == '':
  34. 34 # 男性
  35. 35 bmr = (13.7 * weight) + (5.0 * height) - (6.8 * age) + 66
  36. 36 elif gender == '':
  37. 37 # 女性
  38. 38 bmr = (9.6 * weight) + (1.8 * height) - (4.7 * age) + 655
  39. 39 else:
  40. 40 bmr = -1
  41. 41
  42. 42 if bmr != -1:
  43. 43 print('您的性别:{},体重:{}公斤,身高:{}厘米,年龄:{}岁'.format(gender, weight, height, age))
  44. 44 print('您的基础代谢率:{}大卡'.format(bmr))
  45. 45 else:
  46. 46 print('暂不支持该性别')
  47. 47 except ValueError:
  48. 48 print('请输入正确的信息!')
  49. 49 except IndexError:
  50. 50 print('输入的信息过少!')
  51. 51 except:
  52. 52 print('程序异常!')
  53. 53
  54. 54 print() # 输出空行
  55. 55 y_or_n = input('是否退出程序(y/n)?')
  56. 56
  57. 57
  58. 58 if __name__ == '__main__':
  59. 59 main()

 

 

6.模拟掷骰子

  1. 1 import matplotlib.pyplot as plt
  2. 2 import numpy as np
  3. 3
  4. 4 # 解决中文显示问题
  5. 5 plt.rcParams['font.sans-serif'] = ['SimHei']
  6. 6 plt.rcParams['axes.unicode_minus'] = False
  7. 7
  8. 8
  9. 9 def main():
  10. 10 """
  11. 11 主函数
  12. 12 """
  13. 13 total_times = 10000
  14. 14
  15. 15 # 记录骰子的结果
  16. 16 roll1_arr = np.random.randint(1, 7, size=total_times)
  17. 17 roll2_arr = np.random.randint(1, 7, size=total_times)
  18. 18 result_arr = roll1_arr + roll2_arr
  19. 19
  20. 20 hist, bins = np.histogram(result_arr, bins=range(2, 14))
  21. 21 print(hist)
  22. 22 print(bins)
  23. 23
  24. 24 # 数据可视化
  25. 25 plt.hist(result_arr, bins=range(2, 14), edgecolor='black', linewidth=1, rwidth=0.8)
  26. 26
  27. 27 # 设置x轴坐标点显示
  28. 28 tick_labels = ['2点', '3点', '4点', '5点',
  29. 29 '6点', '7点', '8点', '9点', '10点', '11点', '12点']
  30. 30 tick_pos = np.arange(2, 13) + 0.5
  31. 31 plt.xticks(tick_pos, tick_labels)
  32. 32
  33. 33 plt.title('骰子点数统计')
  34. 34 plt.xlabel('点数')
  35. 35 plt.ylabel('频率')
  36. 36 plt.show()
  37. 37
  38. 38
  39. 39 if __name__ == '__main__':
  40. 40 main()

 

 

7.输入某年某月某日,判断这一天是这一年的第几天?

  1. 1 from datetime import datetime
  2. 2
  3. 3
  4. 4 def is_leap_year(year):
  5. 5 """
  6. 6 判断year是否为闰年
  7. 7 是,返回True
  8. 8 否,返回False
  9. 9 """
  10. 10 is_leap = False
  11. 11
  12. 12 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
  13. 13 is_leap = True
  14. 14
  15. 15 return is_leap
  16. 16
  17. 17
  18. 18 def main():
  19. 19 """
  20. 20 主函数
  21. 21 """
  22. 22 input_date_str = input('请输入日期(yyyy/mm/dd):')
  23. 23 input_date = datetime.strptime(input_date_str, '%Y/%m/%d')
  24. 24
  25. 25 year = input_date.year
  26. 26 month = input_date.month
  27. 27 day = input_date.day
  28. 28
  29. 29 # # 包含30天 月份集合
  30. 30 # _30_days_month_set = {4, 6, 9, 11}
  31. 31 # _31_days_month_set = {1, 3, 5, 7, 8, 10, 12}
  32. 32
  33. 33 # 月份-天数 字典
  34. 34 month_day_dict = {1: 31,
  35. 35 2: 28,
  36. 36 3: 31,
  37. 37 4: 30,
  38. 38 5: 31,
  39. 39 6: 30,
  40. 40 7: 31,
  41. 41 8: 31,
  42. 42 9: 30,
  43. 43 10: 31,
  44. 44 11: 30,
  45. 45 12: 31}
  46. 46
  47. 47 day_month_dict = {30: {4, 6, 9, 11},
  48. 48 31: {1, 3, 5, 7, 8, 10, 12}}
  49. 49
  50. 50 # 初始化值
  51. 51 days = 0
  52. 52 days += day
  53. 53
  54. 54 for i in range(1, month):
  55. 55 days += month_day_dict[i]
  56. 56
  57. 57 if is_leap_year(year) and month > 2:
  58. 58 days += 1
  59. 59
  60. 60 print('这是{}年的第{}天。'.format(year, days))
  61. 61
  62. 62
  63. 63 if __name__ == '__main__':
  64. 64 main()

 

 

8. 判断密码强度

  1. 1 class PasswordTool:
  2. 2 """
  3. 3 密码工具类
  4. 4 """
  5. 5 def __init__(self, password):
  6. 6 # 类的属性
  7. 7 self.password = password
  8. 8 self.strength_level = 0
  9. 9
  10. 10 def process_password(self):
  11. 11 # 规则1:密码长度大于8
  12. 12 if len(self.password) >= 8:
  13. 13 self.strength_level += 1
  14. 14 else:
  15. 15 print('密码长度要求至少8位!')
  16. 16
  17. 17 # 规则2:包含数字
  18. 18 if self.check_number_exist():
  19. 19 self.strength_level += 1
  20. 20 else:
  21. 21 print('密码要求包含数字!')
  22. 22
  23. 23 # 规则3:包含字母
  24. 24 if self.check_letter_exist():
  25. 25 self.strength_level += 1
  26. 26 else:
  27. 27 print('密码要求包含字母!')
  28. 28
  29. 29 # 类的方法
  30. 30 def check_number_exist(self):
  31. 31 """
  32. 32 判断字符串中是否含有数字
  33. 33 """
  34. 34 has_number = False
  35. 35
  36. 36 for c in self.password:
  37. 37 if c.isnumeric():
  38. 38 has_number = True
  39. 39 break
  40. 40
  41. 41 return has_number
  42. 42
  43. 43 def check_letter_exist(self):
  44. 44 """
  45. 45 判断字符串中是否含有字母
  46. 46 """
  47. 47 has_letter = False
  48. 48 for c in self.password:
  49. 49 if c.isalpha():
  50. 50 has_letter = True
  51. 51 break
  52. 52 return has_letter
  53. 53
  54. 54
  55. 55 class FileTool:
  56. 56 """
  57. 57 文件工具类
  58. 58 """
  59. 59 def __init__(self, filepath):
  60. 60 self.filepath = filepath
  61. 61
  62. 62 def write_to_file(self, line):
  63. 63 f = open(self.filepath, 'a')
  64. 64 f.write(line)
  65. 65 f.close()
  66. 66
  67. 67 def read_from_file(self):
  68. 68 f = open(self.filepath, 'r')
  69. 69 lines = f.readlines()
  70. 70 f.close()
  71. 71 return lines
  72. 72
  73. 73
  74. 74 def main():
  75. 75 """
  76. 76 主函数
  77. 77 """
  78. 78
  79. 79 try_times = 5
  80. 80 filepath = 'password_6.0.txt'
  81. 81 # 实例化文件工具对象
  82. 82 file_tool = FileTool(filepath)
  83. 83
  84. 84 while try_times > 0:
  85. 85
  86. 86 password = input('请输入密码:')
  87. 87 # 实例化密码工具对象
  88. 88 password_tool = PasswordTool(password)
  89. 89 password_tool.process_password()
  90. 90
  91. 91 line = '密码:{}, 强度:{}\n'.format(password, password_tool.strength_level)
  92. 92 # 写操作
  93. 93 file_tool.write_to_file(line)
  94. 94
  95. 95 if password_tool.strength_level == 3:
  96. 96 print('恭喜!密码强度合格!')
  97. 97 break
  98. 98 else:
  99. 99 print('密码强度不合格!')
  100. 100 try_times -= 1
  101. 101
  102. 102 print()
  103. 103
  104. 104 if try_times <= 0:
  105. 105 print('尝试次数过多,密码设置失败!')
  106. 106
  107. 107 # 读操作
  108. 108 lines = file_tool.read_from_file()
  109. 109 print(lines)
  110. 110
  111. 111
  112. 112 if __name__ == '__main__':
  113. 113 main()

 

原文链接:http://www.cnblogs.com/yxmings/p/14423401.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号