小故障代码?

时间:2015-05-14 04:34:25

标签: python function python-3.x

我有这个代码。如果你按照说明运行它,一切正常。但是我想要dummyproof它,但当你进入也制造部队,然后你修复你的错误你修复错误后,当函数重新启动时会出现错误。

请看一看并帮我解决。

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

1 个答案:

答案 0 :(得分:1)

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

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