有没有办法把我的代码缩短到2个变量,同时保持在2个小数



试图将我的代码缩短到距离#1只有几点的位置。

我试着缩小它,但它太复杂了。

Taxers = int(input("Will you be eating in 1 For Yes 2 For No:"))
TotalCostA = TotalCostB * 0.05
Tax = TotalCostA
TotalCostF = "{:.2f}".format(Tax)
TotalCostT = Tax + TotalCostB
if Taxers == 2:
print("Tax = 0")
print("Your total pizza cost it", TotalCostB, "kd")
else:
print("Tax = ", TotalCostF)
print("Your total pizza cost it", TotalCostT, "kd")

您可以去掉额外的变量,使用f-string来获得更流畅的体验:

Taxers = int(input("Will you be eating in 1 For Yes 2 For No:"))
TotalCostA = TotalCostB * 0.05
TotalCostT = TotalCostA + TotalCostB
if Taxers == 2:
print("Tax = 0")
print(f"Your total pizza cost it {TotalCostB} kd")
else:
print(f"Tax = {TotalCostA:.2f}")
print(f"Your total pizza cost it {TotalCostT} kd")

进一步缩短它会降低代码的可读性。注意,我强烈建议您遵循Python命名约定,并将变量名称改进为更具描述性的名称,例如cost_with_tax

假设在输入和返回输出时无法更改打印的文本,下面是我的尝试。我认为您还没有定义TotalCostB,所以请相应地进行更改。

print(["Tax = 0"+"nYour total pizza cost it "+str(TotalCostB)+" kd","Tax = "+"{:.2f}".format(TotalCostB * 0.05)+"nYour total pizza cost it "+"{:.2f}".format(TotalCostB * 1.05)+" kd"][int(input("Will you be eating in 1 For Yes 2 For No:")) == 2])

您需要考虑使代码更加健壮(这涉及到更多的代码(,然后才能开始考虑简化。

考虑一下:

tax = {1: 0.05, 2: 0.00}
pizzacost = 4.00
while True:
userinput = input('Will you be eating in 1 For Yes 2 For No: ')
try:
if (inorout := int(userinput)) in tax:
break
except ValueError:
pass
print(f'Tax = {tax[inorout] * pizzacost:.2f}kdnYour total pizza cost is {pizzacost * (1 + tax[inorout]):.2f}kd')

相关内容

  • 没有找到相关文章

最新更新