Python /烧瓶确保传递值

时间:2019-07-13 22:21:50

标签: python flask cs50

我正在尝试做的是,如果用户没有输入任何东西或除了正整数之外的任何其他东西,它将给出一个错误。如果用户不输入任何内容,则不会显示该错误。如何禁止空输入?

    # get positive number of shares user wants to buy
    shares = int(request.form.get("shares"))
    if shares is None or shares < 0:
        return apology("Please make sure that the shares you are buying is more than 0")

1 个答案:

答案 0 :(得分:0)

因为0既不是正数也不是负数。您可能需要将代码更改为此:

shares = request.form.get("shares", 0)  # set default to 0 if input is empty
if int(shares) <= 0:
    return apology("Please make sure that the shares you are buying is more than 0")

但是,将字符串转换为整数时,可能需要使用try ... except语句:

shares = request.form.get("shares", 0)  # set default to 0 if input is empty

try:
   shares_int = int(shares)
except ValueError:
   shares_int = 0

if shares_int <= 0:
    return apology("Please make sure that the shares you are buying is more than 0")