首页 > 解决方案 > 介绍 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)

标签: python

解决方案


  1. 您可以删除两个外部while循环,如break顶层所示,因此循环只运行一次。
  2. 如果需要,您可以转换colors为 Enum 类(这更像是一种风格选择)
  3. 这条线tax=(ELECTRICITY*0.07)+(campsite*0.07)可以表示为x*0.07 + y*0.07,可以简化为0.07(x+y) 或0.07 * (ELECTRICITY + campsite)在这种情况下。
  4. 您可以使用带有简单格式化技巧的 f 字符串,而不是手动填充语句-中的字符。例如,试试这个:print
width = 40
fill = '-'
tax = 1.2345

print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')

推荐阅读