“赋值前引用局部变量”,但赋值变量是我要做的第一件事

2024-09-26 18:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个初级Python课程中,我的导师编写了一些伪代码供我们学习。我已经按照它到了T(我觉得),而且无论我如何尝试更改程序,都会遇到bug。我宁愿让人迅速指出我的错误,也不愿花更多的时间胡闹。这是用python2.7.8编写的。在

#Anthony Richards
#25 February 2018
#This program is a simple simulation of an order-taking software.
#It demonstrates multiple variables, functions, decisions, and loops.

def main(): 

    declareVariables()

    while keepGoing == "y":

        resetVariables()

        while moreFood == "y":
            print "Enter 1 for Yum Yum Burger"
            print "Enter 2 for Grease Yum Fries"
            print "Enter 3 for Soda Yum"
            option = input("Please enter a number: ")
            if option == 1:
                getBurger()
            elif option == 2:
                getFries()
            elif option == 3:
                getSoda()
            else:
                print "You've made an incorrect entry. Please try again."
            moreFood = raw_input("Would you like to order anything else? (y/n): ")

    calcTotal(totalBurger, totalFries, totalSoda)
    printReceipt(total)
    keepGoing = raw_input("Would you like to place another order? (y/n): ")

def declareVariables():
    keepGoing = "y"
    moreFood = "y"
    totalBurger = 0
    totalFries = 0
    totalSoda = 0
    subtotal = 0
    tax = 0
    total = 0
    option = 0
    burgerCount = 0
    fryCount = 0
    sodaCount = 0

def resetVariables():
    totalBurger = 0
    totalFries = 0
    totalSoda = 0
    total = 0
    tax = 0

def getBurger(totalBurger):
    burgerCount = input("Please enter the number of burgers: ")
    totalBurger = totalBurger + burgerCount * .99

def getFries(totalFries):
    fryCount = input("Please enter the number of fry orders: ")
    totalFries = totalFries + fryCount * .79

def getSoda(totalSoda):
    sodaCount = input("Please enter the number of drinks: ")
    totalSoda = totalSoda + sodaCount * 1.09

def calcTotal(totalBurger, totalFries, totalSoda):
    subtotal = totalBurger + totalFries + totalSoda
    tax = subtotal * .06
    total = subtotal + tax

def printReceipt(total):
    print "Your total is $"+str(total)

main()

Tags: ofnumberinputdeftotaloptiontaxprint
2条回答

范围。您定义了变量,但它们只存在于declareVariables中。只需将引用移到您想要的函数(main)内,这样它们就可以存在了。更好的是,将所有函数合并为一个大函数,这样您就不必担心这个问题(或者让它们都存在于全局范围内[在定义任何函数之前定义它们])

def func():
    x = "this is not global"

func()

# print(x) would throw an error

def func2():
    global y
    y = "this is global"

func2()

print(y) # This indeed will print it

虽然你可以用这个,但这是非常非常糟糕的练习。在

相关问题 更多 >

    热门问题