0
def complex():
    answer = raw_input("Would you like to run this program?")

    answer = answer.lower()

    money = 5

    if "yes" in answer:
        print money
        money = money - 1
        complex()

    else:
        quit()

complex()

出于某种原因,每次我在 raw_input 中输入“yes”时,它都会吐出 5。但是我希望它吐出 5,然后当我再次键入 yes 时,我希望它吐出 4,然后如果我再次键入 yes,我想让它吐出 3....

我通过使用 Global 语句解决了这个问题:

money = 5
def complex():
answer = raw_input("Would you like to run this program?")
answer = answer.lower()


    if "yes" in answer:
        global money
        print money
        money = money - 1
        complex()

    else:
        quit()

complex()
4

5 回答 5

1

This is what your procedure is doing :

  1. Get user input
  2. Set variable money to 5
  3. Validate if user input value is "yes" and if so print value if variable money which is 5.
  4. Set variable money to 5 - 1 = 4
  5. Run procedure complex()
  6. Get user input
  7. Set variable money to 5
  8. Validate if user input value is "yes" and if so print value if variable money which is 5.
  9. Set variable money to 5 - 1 = 4
  10. Run procedure complex()

... etc.

As you can see your procedure is overwriting the desired value (4) with the value of 5 with each iteration that that is why it is not working as you desire.

What you could do is make a loop to run x number of times after money has been set to five.

于 2012-08-20T18:26:43.607 回答
1

moneycomplex函数的局部变量。

每次调用complex函数时都会创建变量。

尝试在方法之前创建变量。

于 2012-08-20T18:06:28.170 回答
0

在“复杂”函数中,您不断将 money 变量重置为 5。

于 2012-08-20T18:06:23.493 回答
0

由于您调用了 complex(),因此一直调用 money = 5 行。要解决此问题,您的递归调用不应包含此设置。或者,使用迭代。

于 2012-08-20T18:07:33.520 回答
0

将钱 = 钱 - 1 更改为您使用它太多次的不同变量,它将把钱当作 5

print dollars 
dollars = money - 1
于 2012-08-20T18:08:18.843 回答