【问题标题】:python handling invalid inputs from a userpython处理来自用户的无效输入
【发布时间】:2020-11-30 12:38:17
【问题描述】:

我被这个作业困住了:

重写以下程序,以便它可以处理来自用户的任何无效输入。

def example():
   for i in range(3)
       x=eval(input('Enter a number: '))
       y=eval(input('enter another one: '))
       print(x/y)

我试了试...除了ValueError,但程序仍然无法运行。

【问题讨论】:

  • 你写,你试过try...except。这通常应该有效。你能添加你的代码吗?基本上,您应该尝试自己解决作业。否则,你什么都学不到。如果您发布您的代码以及您在解决方案中遇到的问题的详细信息,我们可以为您提供更好的帮助。

标签: python exception error-handling invalid-characters


【解决方案1】:

那是因为您可能没有考虑 y = 0 时得到的 ZeroDivisionError! 怎么样

def example():
   for i in range(3):
      correct_inputs = False
      while not correct_inputs:
         try:
            x=eval(input('Enter a number: '))
            y=eval(input('enter another one: '))
            print(x/y)
            correct_inputs = True
         except:
            print("bad input received")
            continue

此函数精确计算 3 个正确的除法 x/y! 如果您需要关于continue 运算符的良好参考,请查看here

【讨论】:

    【解决方案2】:
    def example():
    
       for i in range(3)
          try:
             x=eval(input('Enter a number: '))
          except ValueError:
             print("Sorry, value error")
          try:
             y=eval(input('enter another one: '))
          except ValueError:
             print("Sorry, value error")`enter code here`
          try:
             print(x/y)
          except ValueError:
             print("Sorry, cant divide zero")
    

    【讨论】:

    • 该代码只会处理除以零错误,其他错误(例如用户输入字符串)不会被处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2015-06-03
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多