我正在尝试检查输入的几种情况,然后将字符串转换为整数,此后,我要确保整数不是负数,否则提示用户再次输入。
它适用于字符串条件,但是当我输入一个负数时,输入会引发错误“输入最多应有1个参数,得到2个”
有关如何对此进行评估的任何想法?
#This compares whether the bet placed is greater than the value in the players chip_balance. It prompts the player for a lower bet if it is of greater value than chip_balance
while bet > chip_balance:
print('Sorry, you may only bet what you have 0 -', chip_balance)
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha() or bet == '':
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
if bet < 0:
bet = input("Sorry, you may only bet what you have sir! 0 \-", chip_balance)
bet = int(bet)
答案 0 :(得分:2)
sh4dowb已经识别出您的错误-您为to input([prompt])
提供了2个参数-该参数仅接受1个文本输入作为提示。
除此之外,还有很多改进的空间:
您可以使用error handling进行验证。 string formating也派上用场:
从ValueError派生两个自定义错误-如果验证无法解决,我们将提出它们。
class ValueTooLowError(ValueError):
"""Custom error. Raised on input if value too low."""
pass
class ValueTooHighError(ValueError):
"""Custom error. Raised in input if value too high."""
pass
代码:
chip_balance = 22
while True:
bet = input("Place your bet (0-{}): ".format(chip_balance))
try:
bet = int(bet) # raises a ValueError if not convertable to int
# bet is an int, now we do custom validation
if bet < 0:
raise ValueTooLowError()
elif bet > chip_balance:
raise ValueTooHighError()
# bet is fine, break from the `while True:` loop
break
except ValueTooLowError:
print("Can not bet negative amounts of '{}'.".format(bet))
except ValueTooHighError:
print("You do not own that much credit! You got {}.".format(chip_balance))
except ValueError as e:
if bet == "":
print("You are the silent type? Be sensible: input a number.")
else:
print("Try again.")
print("You betted: {}".format(bet))
输出(行距):
Place your bet (0-22): -30
Can not bet negative amounts of '-30'.
Place your bet (0-22): 55
You do not own that much credit! You got 22.
Place your bet (0-22): # nothing
You are the silent type? Be sensible: input a number.
Place your bet (0-22): 9
You betted: 9
建议阅读:
答案 1 :(得分:1)
@GetMapping("/listcustomers")
public List<Customers> getCustomers(){
return customerService.findAll();
}
输入函数不带2个参数,而打印则带2个参数。您可以这样操作;
bet = input("Sorry, you may only bet what you have sir! 0 \-", chip_balance)