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

2 投票
2 回答
28297 浏览
提问于 2025-04-17 05:23

我正在学习Python,并且给自己设定了一个小挑战:写一个程序,让用户输入一辆车的基本价格,然后把这个价格保存到一个叫做 base 的变量里。这个程序还有两个变量,分别叫 taxlicense,它们是百分比的形式。所以程序会先获取基本价格,然后计算出 base 价格的七(7)个百分点,并把这个值加到基本价格上。对于牌照费用也是这样处理,等等。

不过,我想知道的是,当程序运行到这行代码时: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 个回答

4

在Python中,你不能在同一行里这样做。不过你可以先定义一个叫after_tax的变量,然后再把它打印出来:

after_tax = base * tax / 100 + base
print "\nAfter taxes the price is: ", after_tax
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.")

撰写回答