这个程序是关于从“邮购”房屋订购东西。
他们销售五种产品。 P1 = 2.98,P2 = 4.5,P3 = 9.98,P4 = 4.49,P5 = 6.87
到目前为止,这是我的代码。
#Imports: None
#Defs:
def userInput1():
x = int(input("Product Number?"))
return x
def userInput2():
q = int(input("Quantity?"))
return q
def calculations(x,q):
p1 = 2.98
p2 = 4.5
p3 = 9.98
p4 = 4.49
p5 = 6.87
subtotal = q * x
return subtotal
def final(subtotal):
print ("Total:", subtotal)
def loop():
cont = input("Do you want to continue? (yes/no)")
if cont == 'yes':
main()
return
else:
final()
def main():
x = userInput1()
subtotal = calculations(x,q)
final(subtotal)
#Driver:
main()
我必须使用哨兵控制的循环。
这是我的追溯。
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_mailorder3.py", line 49, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_mailorder3.py", line 46, in main
subtotal = calculations(x,q)
NameError: name 'q' is not defined
这是它应该如何运作。
Product number?: 1
Quantity?: 2
Continue?(yes/no): yes
Product number?: 2
Quantity?: 5
Continue?(yes/no): yes
Product number?: 3
Quantity?: 3
Continue?(yes/no): yes
Product number?: 4
Quantity?: 1
Continue?(yes/no): no
Total: $62.89
可能存在更深层次的问题。
答案 0 :(得分:2)
假设你是编程的新手(我可以从你的代码中感受到)并且这个问题似乎是学校的功课很容易,而且你也不想尝试调试它(你需要调试很多)成为一名优秀的程序员)
在这里,我向您展示您的代码,并提供适当的注释,以解释您的代码出错的原因。
从主函数开始读取(而不是从第一行开始)
def userInput1():
x = int(input("Product Number?"))
return x
def userInput2():
q = int(input("Quantity?"))
return q
def calculations(x,q):
p1 = 2.98
p2 = 4.5
p3 = 9.98
p4 = 4.49
p5 = 6.87
subtotal = q * x
#here you are multiplying the item number by quantity
#not the price by quantity (use proper if else to check price for item number
# return to main function again for more comments
return subtotal
def final(subtotal):
print ("Total:", subtotal)
#nothing wrong here but since we have declared subtotal as global (remember that?)
#so no need to pass subtotal by argument.
def loop():
cont = input("Do you want to continue? (yes/no)")
if cont == 'yes':
main()
return
else:
final()
#you are calling final() but you declared with argument (are you mad?)
#now check final function
def main():
x = userInput1()
#Where you are taking input from user for quantity??
#first take quantity as input q = userInput2()
subtotal = calculations(x,q)
#now every time you call main function your subtotal will be revised
#remember teacher talking about global and local variables?
#subtotal needs to be global (declare it somewhere outside the functions
#now even if subtotal is global you need to increment it (not reassign)
# use subtotal += calculations(x,q)
#now check your calculations function
final(subtotal)
#you are calling final subtotal but where the hell you calling your loop?
#call it before calling final and now check your loop function
main()
希望现在您能够编写正确的代码 但即使您现在无法编写正确的代码,here也可以为您提供帮助。但是先尝试自己编写代码。快乐调试:)