【问题标题】:How do I use a function multiple times in Python?如何在 Python 中多次使用函数?
【发布时间】:2015-01-19 19:07:16
【问题描述】:

我遇到了一些代码问题。当我再次调用一个函数时,它似乎不会再次调用该函数。

credit=0
x=1
d=1
def sum1():
    global x
    global credit
while x>0:
    g=int(input("Press 1 to continue inputting money or press 0 to select    and item"))
    if g==1:
        inpt=int(input("Please insert 10p, 20p, 50p, or £1 (100p) coins   into the machine."))
        credit=credit+inpt
    else:
        print("You have "+str(credit)+" pence in your credit balance")
        x=0
sum1()
print("something")
sum1()

这是我的代码的一部分,运行该函数一次似乎使另一个无法工作。感谢您的帮助。

【问题讨论】:

  • 你在错误地使用函数。
  • 你刚刚创建了一个函数来将一些变量定义为global。那么,为什么您首先制作了该功能?你不会在那个函数中做任何事情。
  • 我很难理解该函数在您的代码中的使用。如果它只是简单地返回全局值,为什么不在你的条件中这样做呢?

标签: python function loops arguments call


【解决方案1】:

我猜你正在尝试编写以下代码:

credit=0
x=1
d=1
def sum1():
    global x
    global credit
    while x>0:
        g=int(input("Press 1 to continue inputting money or press 0 to select    and item"))
        if g==1:
            inpt=int(input("Please insert 10p, 20p, 50p, or £1 (100p) coins   into the machine."))
            credit=credit+inpt
        else:
            print("You have "+str(credit)+" pence in your credit balance")
            x=0
sum1()
print("something")
sum1()

当您第一次调用 sum1() 时,根据您的输入(当您按 0 时),x 的值设置为零(x = 0)。所以下一次,当你调用 sum1() 时,while 循环里面的条件是 False (while x > 0),所以你什么都看不到。

如果你在定义函数后立即使用 print 语句,你会看到它工作了两次(函数被调用了两次)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多