Skip to main content
 首页 » 编程设计

python之在函数中使用 if "x"进行计算,但未生成总计

2025年05月04日13qq号

我是 Python 的新手,我的代码有问题,我正在使用函数中的 if 来计算蔬菜水果商的计算器,当输入三个正在购买的苹果时,总计为 £ 0 应该是 £3.90

total = 0 
 
 
print "Welcome to the green grocers, what would you like?" 
print "1. Apples" 
print "2: Bananas" 
print "3. Oranges" 
print "4. Total" 
 
 
 
fruit = raw_input("What would you like?") 
 
if "1" in fruit: 
   q = input("How many?") 
   total + (q*1.3) 
   fruit = raw_input("What would you like?") 
 
if "2" in fruit: 
   g = input("How many?") 
   total + (g*1.5) 
   fruit = raw_input("What would you like?") 
 
if "3" in fruit: 
   l = input("How many?") 
   total = (l*1.6) 
   fruit = raw_input("What would you like?") 
 
   if "4" in fruit: 
   print "Your total is £", total 

请您参考如下方法:

你需要:

total = total + (q*1.3) 

或:

total += (q*1.3) 

整数是不可变的,只是执​​行 total + (q*1.3) 不会影响 total,它只是返回一个新的整数。

>>> x = 1 
>>> x + 2   # Simply returns a new value, doesn't affects `x` 
3 
>>> x       # `x` is still unchanged 
1 
>>> x += 1  # Assign the new value back to `x` 
>>> x       # `x` is now updated. 
2