【问题标题】:Loop issue with python3python3的循环问题
【发布时间】:2013-10-31 22:44:52
【问题描述】:

我正在为我正在编写的一个小程序的一部分代码苦苦挣扎。请记住,我对此很陌生。

代码如下:

def sell():
    sell = input("\nGreetings! What would you like to do today?\nPress 1 to sell an animal\nPress 2 to buy an animal\nPress 3 If you want to see all the farms and their animals first\n")

    if sell == "1":
        whichs = input("Which animal do you want to sell?\nPress 1 for pig\nPress 2 for horse\nPress 3 for cow\nPress 4 for bull\n")
        if whichs == "1":
            print ("\nYou just sold\n",p[0])
            print ("\nYou now have 350gold")
            print ("\nThese are the animals you have left:")
            print (p[1], p[2], p[3]) #Prints the animals you have left from p list.
        elif whichs == "2":
            print ("\nYou just sold\n",p[1])
            print ("\nYou now have 350gold")
            print ("\nThese are the animals you have left:")
            print (p[0], p[2], p[3])
        elif whichs == "3":
            print ("\nYou just sold\n",p[2])
            print ("\nYou now have 360gold.")
            print ("\nThese are the animals you have left:")
            print (p[0], p[1], p[3])
        elif whichs == "4":
            print ("\nYou just sold\n",p[3])
            print ("\nYou now have 350gold.")
            print ("\nThese are the animals you have left:")
            print (p[0], p[1], p[2])
        else:
            print ("Error")

我希望这个循环,所以当用户卖掉一只动物时,他们会重新开始:

sell = input("\nGreetings! What would you like to do today?\nPress 1 to sell an animal\nPress 2 to buy an animal\nPress 3 If you want to see all the farms and their animals first\n")

我正在为如何做到这一点而苦苦挣扎。

【问题讨论】:

标签: python loops if-statement while-loop


【解决方案1】:

其他两个答案告诉您使用 while 循环是正确的,但未能解决更普遍的问题:循环不应在 sell 函数的内部,而应在其外部,因为您的文字表明用户还可以购买东西或查看他的统计信息。您应该为所有这些动作创建单独的函数,然后创建一个循环来检查动作并调用适当的函数:

def buy():
    #...

def sell():
    #...

def stats():
    #...

while True:
    choice = input("1: Buy 2:Sell 3:Stats - press any other key to exit")
    if choice == "1": buy()
    elif choice == "2": sell()
    elif choice == "3": stats()
    else: break

可以通过使用更多的 Python 方法来优化循环,例如将选择映射到字典中的函数,但为了清楚起见,我用简单的 if 编写了它。

此外,如果您不选择将所有状态保存在全局变量中(您不应该这样做),那么将函数放入一个同时保存当前余额、库存和其他游戏参数的类中是有意义的.

【讨论】:

  • 非常感谢,我一直在考虑将所有代码放在一个函数中是否最佳。现在我的代码看起来更干净了,一切都很好!我不太确定你对映射选择的意思。如果这就是你的意思,我会为所有农场和动物类型使用课程。
【解决方案2】:
def sell():
    looping = True

    while looping:
        sell = input("\nGreetings! ... Press Q for quit")

        if sell == "1":
            #rest of your code
        elif sell == "Q":
            looping = False

【讨论】:

    【解决方案3】:

    尝试使用while 循环:

    def sell_function():
        while True:
            sell = input("\nGreetings! What would you like to do today?\nPress 1 to sell an animal\nPress 2 to buy an animal\nPress 3 If you want to see all the farms and their animals first\n")
            # ...
                else:
                    print("Error")
                    break        # Stop looping on error
    

    我们也可以将变量设置为True,完成while variable,然后使用variable = False 而不是break,以获得相同的效果(在本例中)。

    我重命名了您的函数,因为您使用了一个名为 sell 的变量并且有一个同名的函数,这可能会导致问题。此外,毫无疑问,您稍后会发现 breakcontinue 语句很有用。

    【讨论】:

    • 应该在哪里休息才能让循环正常工作并在正确的地方退出?我试过把 break 放在 else 语句之后,但是没有用。
    • 是的,我注意到,我必须为我的整个代码获得正确的缩进级别,这就是它不起作用的原因。现在它工作非常顺利,非常感谢您的帮助!顺便说一句,我如何接受答案?我也是新来的:)
    • @user2877270 点击答案投票数下方的勾号。
    • @user2877270 我不认为这会阻止你accepting
    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 2014-05-23
    • 2011-06-19
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    相关资源
    最近更新 更多