【问题标题】:Try and Except Python尝试并排除 Python
【发布时间】:2018-08-09 12:59:21
【问题描述】:

我做了这个例子,但是除了在 Python 中处理错误之外,它没有通过 try 运行。

def my_fun(numCats):
    print('How many cats do you have?')
    numCats = input()
    try:
        if int(numCats) >=4:
            print('That is a lot of cats')
        else:
            print('That is not that many cats')
    except ValueError:
        print("Value error")

我试过了:

except Exception:
except  (ZeroDivisionError,ValueError) as e:
except  (ZeroDivisionError,ValueError) as error:

我做了其他例子,它能够捕捉到ZeroDivisionError 我正在使用 Jupyter 笔记本 Python 3。 我们非常感谢您对此事的任何帮助。

我在打电话

my_fun(int('six'))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-657852cb9525> in <module>()
----> 1 my_fun(int('six'))

ValueError: invalid literal for int() with base 10: 'six'

【问题讨论】:

  • 如果您修复缩进并调用函数,您的示例运行良好。
  • “它不运行”- 你是什么意思?你得到什么输出?你调用函数了吗?
  • 你需要添加一些库还是什么?另外,我正在使用 my_fun(int('six')) 来测试它。是的,它应该运行,因为它是一个示例,但我可能遗漏了一些东西。
  • 是3。我运行它
  • 那么你的问题是my_fun(int('six'))应该是my_fun('six'),不要在没有被抓到的地方调用int(),同时删除input()的行,它不是需要你解析函数的参数

标签: python function exception error-handling try-catch


【解决方案1】:

这是您的代码的修改版本:

def my_fun():
    numCats = input('How many cats do you have?\n')
    try:
        if int(numCats) >= 4:
            return 'That is a lot of cats'
        else:
            return 'That is not that many cats'
    except ValueError:
        return 'Error: you entered a non-numeric value: {0}'.format(numCats)

my_fun()

说明

  • 您需要调用您的函数以使其运行,如上所述。
  • 缩进很重要。这已符合准则。
  • input() 将在输入之前显示的字符串作为参数。
  • 由于用户通过input() 提供输入,因此您的函数不需要参数。
  • 最好使用return 值,如有必要,之后再打印它们。而不是让你的函数 print 字符串和 return 无。
  • 您的错误可以更具描述性,并包含不适当的输入本身。

【讨论】:

  • 他们的缩进没问题?
  • @Chris_Rands,OP 已更新。它最初有 8 个空格。这可能工作正常。但不是传统的。
【解决方案2】:

几个问题:

  1. 请修正缩进。缩进级别不匹配。
  2. 无需接受参数numCats,因为它已更改为用户提供的任何内容。
  3. 您没有调用函数my_fun(),这意味着永远不会有任何输出,因为函数只有在调用时才会运行。

这应该可行:

def my_fun():
    print('How many cats do you have?\n')
    numCats = input()
    try:
        if int(numCats) > 3:
            print('That is a lot of cats.')
        else:
            print('That is not that many cats.')
    except ValueError:
        print("Value error")  

my_fun() ## As the function is called, it will produce output now

【讨论】:

  • 非常有帮助!我认为你对这一切都是正确的!谢谢
  • @Mayra 没问题 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
相关资源
最近更新 更多