0

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

继承人的代码:

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")

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

4

3 回答 3

2

其他两个答案在告诉您使用 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

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

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

于 2013-10-31T23:15:13.483 回答
1
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
于 2013-10-31T22:50:17.210 回答
0

尝试使用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、donewhile variable和 thenvariable = False而不是break相同的效果(在本例中)。

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

于 2013-10-31T22:48:52.853 回答