【问题标题】:in Python how do I print the result of a calculation and then save the result to a variable?在 Python 中,如何打印计算结果,然后将结果保存到变量中?
【发布时间】:2011-11-01 01:24:01
【问题描述】:

我正在学习 python,我正在挑战自己编写一个小程序,询问用户汽车的基本价格,然后将基本价格保存到一个名为 base 的变量中。它还有另外两个变量,称为taxlicense,它们是百分比。因此,它获取基本价格,得到base 价格的seven (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.")

【问题讨论】:

    标签: python variables printing command


    【解决方案1】:

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

    【讨论】:

    • 我不敢相信我没有想到这一点。这当然有效。我会用这个。
    • 哈哈,有时最难看到的是显而易见的答案 ;-)
    • 您可以选择最佳答案作为正确答案。回答的用户和提问者都会获得声誉积分。
    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多