Python程序入门技巧

  • 本文关键字:程序 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 = "33[91m"
END = "33[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)
  1. elseintry语句不需要。你可以把break放到try语句的末尾。REF

  2. 最后,在print语句中,我建议您使用其他类型的格式化。您可以使用'...{}..'.format(..)或更python的f'...{val}'。你的方法是最古老的。更多参考

  1. 您可以删除两个外部的while循环,因为break在顶层,所以循环只运行一次。
  2. 如果需要,您可以将colors转换为Enum类(这更像是一种风格选择)
  3. tax=(ELECTRICITY*0.07)+(campsite*0.07)可以表示为x*0.07 + y*0.07,在本例中可以简化为0.07(x+y0.07 * (ELECTRICITY + campsite)
  4. 代替在print语句中手动填充-字符,您可以使用f字符串和简单的格式化技巧。例如,试试这个:
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')

最新更新