繁体   English   中英

在Python中,如何打印计算结果,然后将结果保存到变量中?

[英]in Python how do I print the result of a calculation and then save the result to a variable?

我正在学习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命令还将数学计算的结果保存到一个名为after_tax的变量中,以便我可以重用结果,而不必重新键入整个计算来再次获得结果)。

以下是全部代码:

#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.")

在Python中,您不能在同一行中执行此操作。 但是您可以做的是先定义after_tax变量,然后将其打印出来:

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

您可以预先进行所有计算。 我建议给变量(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.")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM