【问题标题】:User Input Validation using Try|Except使用 Try|Except 验证用户输入
【发布时间】:2021-12-04 11:19:46
【问题描述】:

我对 Python 很陌生,最近我正在使用嵌套的 try/except 进行用户输入验证。我的代码如下:

def user_input():
try:
    myinput = 0
    myinput = float(input("Enter a numberic value:"))
    if myinput > 10:
        raise ValueError('Expect a number between 0 and 10')
    #print(myinput)
    return myinput
except:
    print("something went wrong try again!")
    user_input()

打印(用户输入())

虽然它几乎可以按预期工作,但我注意到了一个问题。当我调用这个函数并且在初始阶段,如果我传递了一个可接受的输入,该函数将返回正确的数值。

但是当我最初尝试输入一个错误值并随后传递正确的值时,该函数似乎没有返回数值。我尝试在函数内打印返回输出,我得到了预期值。

提前致谢

【问题讨论】:

  • 您需要在代码的最后一行return user_input()

标签: python-3.x try-except


【解决方案1】:

except 块中尝试return user_input() 而不是user_input()

【讨论】:

  • 非常感谢您的回复。确实,这有助于解决问题。你介意分享这背后的登录信息吗?
  • @sky 是递归的基本概念。我认为this 的文章对你有好处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2022-11-12
  • 2014-05-26
相关资源
最近更新 更多