缩短重复的Python代码

时间:2017-05-23 09:03:08

标签: 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))

4 个答案:

答案 0 :(得分:6)

您可以为事故创建字典,例如

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。 Kounis是对的。为什么for i in range(1)?这不是一个循环...

答案 1 :(得分:1)

这可能就是我如何缩短代码。缩短它太多是以可读性和可维护性为代价的。

BASIC=500
total_price=BASIC
accident_prices = [0, 50, 125, 225, 375, 500]

age=int(input("what is your age?"))
accidents=int(input("How many accidents have you had?"))

if age < 25:
    total_price+=100
    print("Peole under 25 pay extra 100$")

if accidents > 5:
    print("No insurance!")
    total_price=0
else:
    total_price += accident_prices[accidents]

if accidents < 6:
    print("Your total comes to: ${}".format(total_price))

答案 2 :(得分:0)

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

age = float(input("what is your age?"))
accidents = int(input("How many accidents have you had?"))
total_price = 500

if age < 25:
    total_price = total_price + 100
    print("Peole under 25 pay extra 100$")

print("No extra charge!"
      if accidents == 0 else
      "No insurance!"
      if accidents > 5 else
      "Your total comes to: ${}".format(total_price + prices[accidents])
      )

答案 3 :(得分:0)

BASIC=500
total_price=0
total_price+=BASIC

age=float(input("what is your age?"))
accidents=int(input("How many accidents have you had?"))

prices_list=[0,50,125,225,375,500]

try:
    total_price+=prices_list[accidents]
    if age < 25:
        total_price = total_price + 100
        print("Peole under 25 pay extra 100$")
except:
    total_price = 0
    print("No insurance!")

if accidents == 0:
    print("No extra charge!")

print("Your total comes to: ${}".format(total_price))