【问题标题】:Function not calling properly函数调用不正确
【发布时间】:2016-10-12 04:36:11
【问题描述】:
def main():

    def load():
        name=0
        count=0
        totalpr=0
        name=input("Enter stock name OR -999 to Quit: ")
        while name != '-999':
            count=count+1
            shares=int(input("Enter number of shares: "))
            pp=float(input("Enter purchase price: "))
            sp=float(input("Enter selling price: "))
            commission=float(input("Enter commission: "))
            name = input("Enter stock name OR -999 to Quit: ")

    def calc():
        amount_paid=shares*pp
        commission_paid_purchase=amount_paid*commission
        amount_sold=shares*sp
        commission_paid_sale=amount_sold*commission
        profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
        totalpr=totalpr+profit_loss

    def print():
        print("\nStock Name:", name)
        print("Amount paid for the stock:       $",      format(amount_paid, '10,.2f'))
        print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
        print("Amount the stock sold for:       $", format(amount_sold, '10,.2f'))
        print("Commission paid on the sale:     $", format(commission_paid_sale, '10,.2f'))
        print("Profit (or loss if negative):    $", format(profit_loss, '10,.2f'))
        print("Total Profit is $", format(totalpr, '10,.2f'))
        return main()




load() #to input the values
calc()
print()

我不确定我做错了什么:

我应该将变量名放入def load():def calc():def print(): 吗?

当我现在运行它时,它说"load" 没有定义。我将如何定义load?就此而言,如果我没有定义 def calc():def print(): 我如何定义它们?

我确实在代码末尾正确地调用它们,按照我想要调用它们的顺序 - loadcalc,然后是 print

我的“return main()”是正确的做法吗?我不知道,我只是希望这段代码能够正常运行而不会出错,仅此而已。我的印象是我只是错过了一些东西。任何帮助,将不胜感激。

【问题讨论】:

  • 您在main 内部定义了load,因此在main 外部不可见。如果您不打算使用main,为什么还要在main 中定义函数?
  • 好的,我如何使用 main 同时仍然调用 load()、calc() 和 print()?
  • 我个人不喜欢使用主函数。我觉得它们是多余的。许多人强烈反对。但如果你是,通常你定义你的函数 outside of main,然后按照你想要的顺序调用函数 inside of main。然后文件的最后一行是对main() 的调用。无需从main返回任何内容。
  • 无关,但请参阅此处了解如何正确进行字符串格式化。 pyformat.info
  • 请注意,一旦你的函数之一被命名为print,你就不能再使用内置的print了!

标签: python function python-3.x calling-convention


【解决方案1】:

您在main() 的范围内定义load()。这意味着您不能在main()之外使用该功能。

简单的解决方案是你应该把你的函数定义放在main()的定义之外(顺便说一句,把它叫做print_stock info,print已经是一个函数了!)

您也不需要return main()。我不确定您要做什么,但根本没有必要。

【讨论】:

  • 我想要做什么:
  • def main(): load() calc() print()
  • 我想写main()函数来调用上面的函数类似于上面的注释
  • 你绝对可以做到。在 main 之上定义你的函数,然后在 main 中调用它们。
  • 所以现在我有 [按从上到下的顺序] def load(): 其次是 def calc():, def print(): 最后是 def main(): 和里面 def main() : 是 load()、calc() 和 print()。但是当我运行它时,我什么也得不到。输出为空白。
【解决方案2】:

哎呀。
你的第一个错误:在另一个函数中调用一个函数。也许你打算这样做

class Main:
    def load(self):
        #do a thing

那么你必须这样做

main = Main()
main.load()

您的第二个错误是定义了一个新的 print() 函数,该函数使用了 print 函数,因为它已经存在。重命名它,因为这会导致巨大的错误

【讨论】:

  • 绝对不需要上课。这不是 Java。
  • 此外,从其他函数中调用函数是完全正常的(当然,除非您指的是通过将这些函数相互嵌套而发生的无限递归)。
【解决方案3】:

这是一个最小的工作示例,用于说明如何解决您正在尝试做的事情。

# helper for interpreting input
import ast
#: initial starting values
thing, count, cost, total = 'Nothing', 0, 0, 0

# define all functions at module indentation
def get_user_input():
    global thing, count, cost  # write to the GLOBAL names thing, count and cost
    thing = input('What have you?')  # ask for a string
    count = ast.literal_eval(input('How much do you have?'))  # ask for a string and interpret it: "3.2" => float
    cost = ast.literal_eval(input('How much does each cost?'))

def compute():
    global total  # write to global name total
    total = count * cost  # can read from global names

def pretty_print():  # not named print! we still need print to print!
    print("You have", count, thing)
    print("At", cost, "each, that makes", total, "in total")

# call functions at module indentation
get_user_input()  # ducks, 3, 42
compute()
pretty_print()
# You have 3 ducks
# At 42 each, that makes 126 in total

要警告您的一件事:使用全局变量通常是个坏主意。对于一个小脚本来说这很好,但你已经搞砸了基础——全局变量很棘手,所以尽可能避免使用它们。如果只想运行这些命令,不要写成函数,直接执行。基本上,去掉 def ...global ... 行并将所有内容放在同一个缩进上,然后删除最后三行。

如果你真的想存储和打印多个东西,你需要使用容器。只需在循环中分配一个值,例如thing = input('What have you?'),将保留最后输入的值。相反,您需要一个像list 这样的容器。然后你可以append给它附加值。

container = []  # [] is a list literal
for _ in range(3):  # non-infinite loop
    next_thing = ast.literal_eval(input('Place your order...\n'))
    container.append(next_thing)
print("You ordered", container)

【讨论】:

  • 谢谢。我试过这个。所以现在我有 [按从上到下的顺序] def load(): 其次是 def calc():, def print(): 最后是 def main(): 和里面 def main(): is load(), calc( ) 和打印()。但是当我运行它时,我什么也得不到。输出为空白。
  • 这是一个学校作业——将直线代码转换成 3 个函数。这就是为什么它真的很笨重。
  • 如果你已经尝试过这个并且仍然有def loaddef calcdef print,你一定要再试一次......提示:你不应该有def print
【解决方案4】:
def load():    
    global name
    global count
    global shares
    global pp
    global sp
    global commission
    name=input("Enter stock name OR -999 to Quit: ")
    count =0
    while name != '-999':
        count=count+1
        shares=int(input("Enter number of shares: "))
        pp=float(input("Enter purchase price: "))
        sp=float(input("Enter selling price: "))
        commission=float(input("Enter commission: "))
        calc()
        display()
        name=input("\nEnter stock name OR -999 to Quit: ")

def calc():
    global amount_paid
    global amount_sold
    global profit_loss
    global commission_paid_sale
    global commission_paid_purchase
    global totalpr
    totalpr=0
    amount_paid=shares*pp
    commission_paid_purchase=amount_paid*commission
    amount_sold=shares*sp
    commission_paid_sale=amount_sold*commission
    profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
    totalpr=totalpr+profit_loss

def display():
    print("\nStock Name:", name)
    print("Amount paid for the stock:       $",      format(amount_paid, '10,.2f'))
    print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
    print("Amount the stock sold for:       $", format(amount_sold, '10,.2f'))
    print("Commission paid on the sale:     $", format(commission_paid_sale, '10,.2f'))
    print("Profit (or loss if negative):    $", format(profit_loss, '10,.2f'))

def main():
    load()


main()

print("\nTotal Profit is $", format(totalpr, '10,.2f'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2016-08-13
    • 1970-01-01
    相关资源
    最近更新 更多