python - 介绍 Python 程序的提示
问题描述
下面是我的第一个 python 程序。我正在尝试课堂上尚未涵盖的想法,因为我讨厌停滞不前,并且想要解决如果我只是使用我们在课堂上学到的信息可能出现的问题。至于我的问题,该程序可以工作,但是有什么方法可以压缩代码(如果有的话)?谢谢!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge
class colors:
ERROR = "\033[91m"
END = "\033[0m"
#input validation
while True:
while True:
try:
nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
else:
break
while True:
try:
number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
while True:
try:
campers=int(input("Enter the Number of Campers:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
break
#processing
while True:
try:
campsite=nightly_rate*number_of_nights
tax=(ELECTRICITY*0.07)+(campsite*0.07)
ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
total=campsite+ELECTRICITY+tax+ranger #total paid per camper
total_per=total/campers
except ZeroDivisionError: #attempt to work around ZeroDivisionError
total_per=0 #total per set to zero as the user inputed 0 for number-
break #-of campers
#Output #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper------------------- $%4.2f"%total_per)
解决方案
- 您可以删除两个外部
while
循环,如break
顶层所示,因此循环只运行一次。 - 如果需要,您可以转换
colors
为 Enum 类(这更像是一种风格选择) - 这条线
tax=(ELECTRICITY*0.07)+(campsite*0.07)
可以表示为x*0.07 + y*0.07
,可以简化为0.07(x+y
) 或0.07 * (ELECTRICITY + campsite)
在这种情况下。 - 您可以使用带有简单格式化技巧的 f 字符串,而不是手动填充语句
-
中的字符。例如,试试这个:print
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')
推荐阅读
- visual-studio-code - Visual Studio Code Remote SSH 使用 Windows 用户名而不是 ssh_config 中的用户名
- html - 如何在没有框架的 PWA 中实现暗模式?
- python - 对于线长的(x,y)像素坐标,调整角度变成圆形
- javascript - 字符串类型的 Mongoose _id 不抛出错误
- c# - ASP.NET 应用程序运行时如何将数据保存在内存(会话)中?
- ios - 如果集合中只有 1 个元素,则 UICollectionView 不进入 cellForItemAt 方法
- azure - 将自定义 exe 上传到 Azure Devops 管道
- regex - 如何将多个正则表达式字符串合并为一个?
- css - 引导下拉菜单类的问题
- javascript - Gatsby-Redux:组件不会在状态更改时重新渲染