繁体   English   中英

如何访问 Python 的 catch 块中的 try 块中存在的变量值

[英]How to access variable value present from try block in the catch block in Python

我试图在引发异常时打印在 try 块中作为输入给出的值的类型,以便它向用户提供关于实际给出的输入以及需要给出什么而不是使用Python 中的以下代码片段 -

a = None
try:
    a = int(input('Enter a number'))
    print(a)

except ValueError:
    print('Control waited for Integer , but got a {}'.format(type(a)))

但无法访问 except 块中的变量“a”的类型。 例如:当用户提供输入为 True 时,我希望用户知道控件等待 integer 但它收到了 boolean 代替。 在 python 中。 locals() function 没有帮助。 有什么见解吗?

您需要从int解析部分拆分input ,如下所示:

a = input('Enter a number ') # a gets assigned, no matter what
a = int(a) # if not an int, will throw the Exception, but a keeps the value assigned in the previous line

在您的示例中,如果您不输入int ,则不会在try块中分配a

关于input部分应该放在哪里(我的意思是,在try块之外或内部),从变量赋值的角度来看,这是无关紧要的,因为在这两种情况下, a都将是全局scope 的一部分。 鉴于 - 对于这种特定情况 - input应该是良性的 Exception-wise 并且无论如何都不会抛出ValueError ,它也可能位于try块之外。

只需将输入移出 try except 块,就可以了。

a = input("Enter, a number")
try:
    a = int(a)
    print(a)

except ValueError:
    print('Control waited for Integer but {a} cannot be casted to int')

正如其他人所写,当引发异常时,输入未分配给a

当您捕获异常时,请使用最小的try bloc;

a = input('Enter a number')
try:
    a = int(a)
except ValueError:
    print('Control waited for Integer , but got a {}'.format(type(a)))
print(a)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM