【问题标题】:Glitch with code?代码故障?
【发布时间】:2015-05-14 04:34:24
【问题描述】:
我有这个代码。如果您按照说明运行它,一切正常。但是我想对它进行 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
【问题讨论】:
标签:
python
function
python-3.x
【解决方案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