python - 缩短重复的 Python 代码

标签 python repeat

我目前正在进行类实践评估,我想知道是否可以使用某种循环来缩短我的代码?

BASIC=500
accident_price = 0
total_price=0
total_price+=BASIC
age=float(input("what is your age?"))
accidents=int(input("How many accidents have you had?"))
for i in range(1):
  if age < 25:
    total_price=total_price+100
    print("Peole under 25 pay extra 100$")
  if accidents == 1:
    total_price+=50
    break
  elif accidents == 2:
    total_price+=125
    break
  elif accidents==3:
    total_price+=225
    break
  elif accidents == 4:
    total_price+=375
    break
  elif accidents == 5:
    total_price+=500
    break
  elif accidents == 0:
    print("No extra charge!")
    break
if accidents > 5:
  print("No insurance!")
  total_price=0
if accidents < 6:
  print("Your total comes to: ${}".format(total_price))

最佳答案

你可以为意外创建一个字典,比如

accident_bonus = {1: 50, 2: 125, 3: 225, 4: 375, 5: 500}

你的代码可以没有 elif 系列,并且变成这样:

if accidents in accident_bonus:
    total_price += accident_bonus[accidents]
elif accidents > 5:
    print("No insurance!")
else:
    print("No extra charge!")

还有,EV。库尼斯是对的。为什么 for i in range(1)?这不是一个循环...

关于python - 缩短重复的 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44130326/

相关文章:

python - 在 python 3.4.3 上安装 pandas 时,出现错误 - No module tempita

c++ - 优化变量值的重复赋值

java - 在java中垂直和水平重复图像

javascript - 如何缩短重复的 javascript php 代码

python - 从列表 append 索引无法正常工作

python - 查找最接近给定值的值并返回行索引

python - 无法在 sqlite3 python 中对关闭的游标进行操作

C# 正则表达式和用于重复的大括号

python - Pandas 用重复的索引值填充组内缺失的日期和值

python - 从下拉列表中的数据库 mysql 中选择条目,python Flask