如果未输入所需的输入,如何让代码重复?

时间:2017-06-12 03:12:52

标签: python-2.7

我刚刚在2周前开始使用python而且当输入类似于" fox"时,我不知道如何使我的代码重复。当这不是我接受的三种选择之一(马,牛,骡)。此外,如果我想要总计2马的成本,并说3骡子,它要求"你想再购买动物",我该怎么做?任何帮助都将非常感激。

c:\\xampp\htdocs\myproject

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此增强版代码:

zoo = {}  # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
    animal_type = raw_input("Please enter an animal:")
    print ("Animal Type Entered: " + str(animal_type))
    animal_quantity = int(raw_input("Please enter quantity of animals:"))
    print ("Animal Quantity Entered: " + str(animal_quantity))
    if animal_type in zoo: 
        zoo[animal_type] += animal_quantity
    else: zoo[animal_type] = animal_quantity
    if animal_type == 'horse':
        return 50 * animal_quantity
    if animal_type == 'oxen':
        return 35 * animal_quantity
    if animal_type == 'mule':
        return 20 * animal_quantity

# getting total_money after animal purchase
def cost(total_money):
    costing = animal_cost(total_money)
    total_money = total_money - costing
    if total_money <=0: # condition when money is less than or equal to 0.
        print("No Money left, resetting money to 1000.")
        total_money = 1000

    print ("Cost of Animals:" + str(costing))
    print ("Total Money Left:" + str(total_money))

    # Recursion for buying more animals:
    choice = raw_input("Do you want to buy any more animals?:")

    if choice in ('Yes','y','Y','yes','YES'):
        cost(total_money)

    # you can use this commented elif condition if you want.
    else: # elif choice in('no','No','n','N','NO'):
        print("thankyou!!")
        print("You have total animals: "+str(zoo))

# main function to initiate program
def main():
    print ("Animals available to purchase: " + "horse, oxen, mule")
    total_money = 1000
    print ("You have " + str(total_money) + " to spend")
    cost(total_money)

if __name__ == '__main__':
    main()

这可能会帮到你。 查看最后两行的this