我正在学习python,我正在挑战自己编写一个小程序,询问用户汽车的基本价格,然后将基本价格保存到一个名为base的变量中。它还有两个称为taxlicense的变量,它们是百分比。所以它得到基价,得到seven (7)价格的base百分比,并将其添加到基价中。对于许可费等也一样。
不过,我想知道的是,当它运行时:
print "\nAfter taxes the price is: ", (base * tax / 100 + base)
如何将结果保存到另一个变量,以便下一行不必编写:
重写它感觉很多余,就像我在浪费时间计算已经计算过的东西。
我想将第一行print "\nAfter taxes and license fee the price is: ", (base*tax / 100)+(base*license /100) + base?的结果保存到一个名为print的变量中,这样我就可以编写:
after_tax
(我希望第一个print "\nAfter taxes and license fee the price is: ", after_tax + (base*license /100)命令也将数学计算的结果保存到一个名为print的变量中,这样我就可以重用结果,而不必重新键入整个计算以再次获得结果)。
以下是完整的代码:

#Car salesman calculations program.

base = int(raw_input("What is the base price of the car?" + "\n"))
tax = 7

license = 4

dealer_prep = 500

destination_charge = 1000


print "\nAfter taxes the price is: ", (base * tax / 100 + base)

print "\nAfter taxes and license fee the price is: ", (base*tax / 100)+(base*license /100) + base

print "\nAfter taxes and license fee and dealer prep the price is: ", (base*tax / 100)+(base*license /100) + base + dealer_prep

print "\nAfter taxes, license fees, dealer prep, and destination charge, the total price is: ", (base*tax / 100)+(base*license /100) + base + dealer_prep + destination_charge

raw_input("\nPress the enter key to close the window.")

最佳答案

你可以提前做所有的计算。我建议给变量(a、b、c等)起一个比我在这里更聪明的名字,但这足够说明问题了。

a = (base * tax / 100)
b = (base*license /100)
c = a + b + base
d = c + dealer_prep
e = d + destination_charge

print "\nAfter taxes the price is: ", a + base
print "\nAfter taxes and license fee the price is: ", c
print "\nAfter taxes and license fee and dealer prep the price is: ", d
print "\nAfter taxes, license fees, dealer prep, and destination charge, the total price is: ", e

raw_input("\nPress the enter key to close the window.")

关于python - 在Python中,如何打印计算结果,然后将结果保存到变量中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7961586/

10-16 22:45