Shorten repetitive Python code(缩短重复性的Python代码)
本文介绍了缩短重复性的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))
推荐答案
您可以创建一个事故词典,类似于
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代码
基础教程推荐
猜你喜欢
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
