2017-05-23 48 views
1

我目前正在进行课堂练习评估,我想知道是否可以使用某种类型的循环缩短我的代码?缩短重复的Python代码

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)) 
+6

创建一个字典'accidents'。另外为什么'为我在范围(1)'? –

+2

请注意你的for循环是完全冗余的 – e4c5

+0

它已经被@ e4c5说过了,但这是一个相当大的误解:'对于我在范围(1)中''意味着“只做一次”。这不需要任何循环。 –

回答

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)?这不是一个循环...

+0

我将代码添加到循环中,因为我不断收到elifs的错误,并将其与两个if相结合。我明白它根本不需要,它让我更容易“理解”我在做什么。 :) 非常感谢您的回复:) – TheKylieKappa

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