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

时间:2011-11-01 01:24:01

标签: python variables printing command

我正在学习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.")

2 个答案:

答案 0 :(得分:3)

在Python中,你不能在同一行中这样做。但你可以做的是首先定义after_tax变量,然后将其打印出来:

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

答案 1 :(得分:2)

你可以预先做好所有的计算。我建议给变量(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.")