Python 代码故障?

Python 代码故障?,python,function,python-3.x,Python,Function,Python 3.x,我有这个密码。如果您运行它,如果您按照说明操作,一切正常。然而,我想证明一下,但是当你输入太多,然后你修复了你的错误,当函数重新启动时,在修复错误后,你会得到一个错误 请看一下,帮我修一下 import time warriors = 100 def deploy(): #Calls fighters to front lines amount = input('How many warriors would you like to send to the front lines? Y

我有这个密码。如果您运行它,如果您按照说明操作,一切正常。然而,我想证明一下,但是当你输入太多,然后你修复了你的错误,当函数重新启动时,在修复错误后,你会得到一个错误

请看一下,帮我修一下

import time
warriors = 100
def deploy(): #Calls fighters to front lines
    amount = input('How many warriors would you like to send to the front lines?  Your limit is %i warriors. Keep in mind that enemy invaders have been spotted inside your base. You must keep 10 warriors in base at all times. ' %(warriors))
    try:
        amount = int(amount)
    except ValueError:
        print('Please use numbers.')
        time.sleep(1.5)
        deploy()
    if amount <= warriors:
        print (type(amount))
    elif amount > warriors:
        print("You can't send that many warriors. You only have %i warriors." %(warriors))
        time.sleep(1.5)
        amount=0
        deploy()
    else:
        print("You did something wrong. Try again.")
        time.sleep(1.5)
        deploy()
fighters = deploy()
warriors = warriors - fighters
导入时间
战士=100
def deploy():#呼叫战斗机到前线
数量=输入('您希望向前线派遣多少名战士?您的限制为%i名战士。请记住,在您的基地内发现了敌人入侵者。您必须始终在基地内保留10名战士。'%(战士))
尝试:
金额=整数(金额)
除值错误外:
打印('请使用数字')
时间。睡眠(1.5)
部署()
如果金额为:
打印(“你不能发送那么多战士。你只有%i个战士。”%(战士))
时间。睡眠(1.5)
金额=0
部署()
其他:
打印(“你做错了,再试一次。”)
时间。睡眠(1.5)
部署()
战斗机=部署()
战士=战士-战士

您不应该使用递归(例如,函数反复调用自身)来尝试进行验证。对于这方面的一些良好模式的一般示例,是一个良好的开端。在你的情况下,我可能会稍微重构一下

import time

warriors = 100


def deploy():
    while True:
        amount = input("...")  # your text here
        try:
            amount = int(amount)
        except ValueError:
            print("Please use numbers.")
            # move the time.sleep to the end
        else:  # only execute if the try block succeeds
            if amount > warriors:
                print("You can't send that many warriors. "
                      "You only have %i warriors." % warriors)
            else:
                # everything went right!
                print(type(amount))  # why are you doing this...?
                return amount  # did you forget this in your sample code?
        # if you get here: something broke
        time.sleep(1.5)
这就是说,这是一种丑陋,因为它是如此深刻的嵌套。记住禅宗:“扁平比嵌套好。”让我们重构一点,生成一个新函数,为我们进行验证

import time

warriors = 100


def int_less_than(prompt, ceil, type_error_msg=None,
                  value_error_msg=None, callback=None):
    """Returns a validated integer

    input(prompt) must be less than ceil. Print to console a std error msg
    if none is specified. If you specify a callback: run the callback if any
    errors are detected.
    """

    while True:
        user_in = input(prompt)
        try:
            user_in = int(user_in)
        except ValueError:
            print(type_error_msg or "You must enter a number")
        else:
            if user_in > ceil:
                print(value_error_msg or "You must enter a number "
                                         "less than {}".format(ceil))
            else:
                return user_in
        if callback is not None:
            callback()  # lets us insert a time.sleep call

def deploy():
    amount = int_less_than("How many warriors would you like to...",
                           warriors,
                           callback=lambda: time.sleep(1.5))
    return amount