发生错误是因为如果KeyboardInterrupt
引发 a ,则变量targ
永远不会被初始化。
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
Please enter target:
Cancelled
>>> targ
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
targ
NameError: name 'targ' is not defined
当它不发生时,
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
Please enter target: abc
>>> targ
'abc'
targ
如果未引发异常,您可以更改代码以打印,通过在try
语句中打印它,请参阅以下演示。
try:
targ = raw_input("Please enter target: ")
print targ
except KeyboardInterrupt:
print "Cancelled"
Please enter target: abc
abc
try:
targ = raw_input("Please enter target: ")
print targ
except KeyboardInterrupt:
print "Cancelled"
Please enter target:
Cancelled