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

これをループさせて、ユーザーが 1 匹の動物を売ったら、最初からやり直します。

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

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に設定してから、同じ効果のvariable = False代わりに(この例では) 設定することもできます。break

呼び出された変数を使用し、sell問題を引き起こす可能性のある同じ名前の関数があったため、関数の名前を変更しました。また、後でbreakステートメントとcontinueステートメントが役立つことに気付くことは間違いありません。

于 2013-10-31T22:48:52.853 に答える