我目前正在尝试编写一个程序,用户输入他们想要的颜色地毯,然后根据他们输入的地毯和区域,它会给他们不同的价格,但我当前的问题是正确使用参数因为我对使用python和编程都很新。当前的程序规范要求使用子程序。一个示例问题是我的最后一行main(exit1),它表示exit1未定义,如果我尝试将代码编辑为main(),则表示exit1是必需的。任何帮助将不胜感激。
def prices():
PriceA = 40
PriceB = 50
PriceC = 60
def main(exit1):
exit1 = False
while exit1 == False:
carpet = str(input("What carpet would you like blue, red or yellow "))
carpet = carpet.upper()
if carpet == "X":
exit1 = True
else:
width = int(input("What is the width of the room in M^2 "))
height = int(input("What is the height of the room in M^2 "))
area = width * height
if carpet == "BLUE":
a(area)
elif carpet == "RED":
b(area)
elif carpet == "YELLOW":
c(area)
else:
print("Invalid carpet")
cost = 0
output(cost)
def output(cost, exit1):
print ("the price is £", cost)
def a(area, PriceA):
cost = PriceA * area
output(cost)
def b(area, PriceB):
cost = PriceB * area
output(cost)
def c(area, PriceC):
cost = PriceC * area
output(cost)
main(exit1)
答案 0 :(得分:0)
您正尝试将变量作为参数传递给程序最后一行的main
函数,但在执行该行之前尚未定义exit1
变量(您定义)它在main
函数的范围内。要实现您想要的功能,您不需要为main
提供exit1
参数,因此您只需将其从函数定义和函数调用中删除即可。
def main():
...
...
main()
答案 1 :(得分:0)
您遇到的问题是在将变量输入函数之前需要定义变量。我修复了代码并进行了一些修正,看起来你还有一个缩进错误,并且当你调用它们时没有为你的函数提供足够的参数。我写的代码有点容易。如果我做了什么你不明白给我发消息,否则我推荐代码acadamy和pythonprogramming .net等网站。 def main():
PriceA = 40
PriceB = 50
PriceC = 60
while True:
carpet = str(input('What carpet would you like blue, red or yellow? '))
carpet = carpet.upper()
if carpet == 'X':
break
else:
width = int(input("What is the width of the room in M? "))
height = int(input("What is the height of the room in M? "))
area = width * height
if carpet == "BLUE":
output(area,PriceA)
elif carpet == "RED":
output(area,PriceB)
elif carpet == "YELLOW":
output(area,PriceC)
else:
print('Invalid carpet')
def output(area,Price):
cost = area*Price
print('the price is £',cost)
main()