Try/Except 错误处理无法识别 ValueError

在以下脚本中:


# shows multiplication table of a number upto that number

import time

while True:

    num = input("Enter number: ")

    try:

        def mult():

            for i in range(1, int(num)+1):

                print(str(i) + " x " + num + " = " + str(i * int(num)))

    except ValueError:

        print("Please enter a number")

        continue


    mult()

    time.sleep(2)

如果输入的不是整数值,我希望显示“请输入数字” ,因为在内部找到了。numValueErrorint(num)mult()


但是,try/except 块似乎不起作用,因为在输入非数字字符串时,它会显示 Python 的 Traceback 错误:


Enter number: forty five

Traceback (most recent call last):

  File "...", line 13, in <module>

    mult()

  File "...", line 7, in mult

    for i in range(1, int(num)+1):

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

为什么错误处理不起作用?


白衣染霜花
浏览 177回答 2
2回答

白板的微信

您可以删除 mult() 函数定义,因为它似乎不是特别重要(如果重要请纠正我)。您的代码将如下所示:import timewhile True:&nbsp; &nbsp; num = input("Enter number: ")&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; for i in range(1, int(num)+1):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(str(i) + " x " + num + " = " + str(i * int(num)))&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("Please enter a number")&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; time.sleep(2)这最初不起作用的原因是因为您的 try 语句围绕着一个定义,而不是围绕着 mult() 函数的实际调用。这意味着当它运行时,它试图定义一个名为 的函数mult,并且运行良好。然而,当它真正调用第 13 行的函数时,由于没有 try 语句而导致它中断。

慕无忌1623718

为什么要在 try 中定义 mult?尝试将 try 放入函数中。现在您正在尝试检查是否可以创建函数 mult。成功后你尝试调用它(你会遇到问题的地方)。`# shows multiplication table of a number upto that numberimport timewhile True:&nbsp; &nbsp; num = input("Enter number: ")&nbsp; &nbsp; def mult():&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for i in range(1, int(num)+1):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(str(i) + " x " + num + " = " + str(i * int(num)))&nbsp; &nbsp; &nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Please enter a number")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continuemult()time.sleep(2)`这应该有效,另外请注意,如果你想在你的函数中输入一个值,应该这样做:def mult(data)调用:mult('数据')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python