使用python3循环问题

时间:2013-10-31 22:44:52

标签: python loops if-statement while-loop

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

下面是代码:

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

我正在努力完成这项工作。

3 个答案:

答案 0 :(得分: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方法进行优化,例如将选项映射到字典中的函数,但为了清楚起见,我用简单的方法编写了它。

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

答案 1 :(得分: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

答案 2 :(得分: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,完成while variable然后variable = False而不是break以获得相同的效果(在此示例中)。

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