简体   繁体   中英

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

I am trying to print the type of the value that is given as input in the try block when an exception is raised so that it gives a clear picture to the user as to what input is actually given and what needs to be given instead using the following code snippet in 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)))

But unable to access the type of variable 'a' in the except block. For example: when the user provides the input as True, I'd want the user to know that the control waited for integer but it received a boolean instead. in python. locals() function did not help. Any insights?

You need to split the input from the int parsing part, like this:

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

In your example, a will never get assigned within the try block if you don't enter an int .

Regarding where the input part should sit (I mean, outside or inside the try block), from a variable assignment perspective that is indifferent, given that in both cases a will be part of the global scope. Given that - for this specific case - input should be benign Exception-wise and won't throw a ValueError anyway, it may as well sit outside the try block.

Just move the input out of the try except block and you are good.

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')

As others wrote, the in put is not assigned to a when the exception is raised.

When you are capturing exception, use a minimal 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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