0

I expected the following code to throw an error as the variable ival(local variable) is being used outside of its scope i.e., in if condition. I didn't encounter any issues/errors why? Please explain the reason.

rawstr=input('Enter a number')
try:
    ival=int(rawstr)
except:
    ival=-1
if ival>0:
    print('Nice work')
else:
    print('Not a Number')

I expected a traceback error saying ival is not defined.

quamrana
  • 37,849
  • 12
  • 53
  • 71
Gopi B
  • 21
  • 6
  • `try` does not introduce scope. `ival` is just a global like `rawstr`. – quamrana Jul 24 '19 at 07:22
  • The variable `ival` is local for the function, not only for the `try` part. See here: https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules – ZiGaelle Jul 24 '19 at 07:26

0 Answers0