单独的成本取决于用户的输入,但是我的代码不会添加它们来创建总成本]1 当它运行时,变量totalcost保持不变
它应该根据我函数中的公式来计算总成本。我不明白为什么这样不行
import sys*
#VARIABLES
total_EntrancePrice=0
costcoins=0
totalcost=0
#PEOPLE IN PARTY
print("How many people are included in your party?")
num_of_people= int(input())
#ENTRANCE FEE
entrance_fee_price = 10
def get_total_EntrancePrice():
total_EntrancePrice=num_of_people*entrance_fee_price
print("Your total price with %s people is %s dollars" %(num_of_people, total_EntrancePrice))
get_total_EntrancePrice()
yes = "yes"
yes1 = "Yes"
no = "no"
no1 = "No"
#COINS?
coins = str(input("Would you like to buy coins?:"))
if coins == yes or yes1:
print("Okay great! Each coin costs 20 cents. How many coins would you like?")
coinsbought=int(input())
priceforcoin=.20
def get_costcoins():
costcoins=coinsbought*priceforcoin
print("Your total price of %s coins is %s dollars" %(coinsbought, costcoins))
get_costcoins()
elif coins ==no or no1:
print("No worries, it's not mandatory to buy some")
else:
print("Im sorry, I dont understand your response")
#TOTAL COST WITH TAX
tax=total_EntrancePrice+costcoins/10
def get_totalcost():
totalcost=total_EntrancePrice+costcoins+tax
print("Your total for today with %s people and %s coins is %s dollars. Thank you for visitiing our Lost at Sea location. Have a wonderful day!" %(num_of_people, coinsbought,totalcost))
get_totalcost()
这是一个范围的问题,如果这是您第一次遇到它,可能会让您感到困惑。我自己没有经验的编码,所以请原谅任何技术错误。我会尽力解释这个问题的根本原因。
举个简单的例子:
打印1
这种奇怪行为的原因是,当var在
change
中更改时,它被限制在函数内部。当您打印
var
时,您是在函数之外,或者在新变量的作用域之外打印它。如果你这样做了:输出将是
2
,但函数外部的var
仍然是1有多种方法可以解决你的问题。一种是使用(讨厌的)全局变量。另一种方法是用
return
将变量设置为“OUTSIDE”范围内函数的输出。这就是我的意思打印2
如果没有遇到,返回就是返回输出的函数。当我说
var = change()
时,python会这样做:“所以,var
将等于这个东西change
,当我运行change时,我得到这个输出2
,因此var = 2
。在您的例子中,您将计算函数中的成本,然后返回它并将此输出赋给函数外的变量
尝试在您自己的代码中实现它
相关问题 更多 >
编程相关推荐