[英]How do I get my main function to work while exceptions check the inputted variable?
我设法让我的异常功能正常工作,但这使得我的主要 function 由于某种原因无法工作。 我真的很想让我的主要 function 工作,因为它应该只接受字母和异常处理输入到 function 时遇到的一些可能的错误。
def string_processor(string):
#The main function,
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
return (countA / len(string))
#finds any errors in the variable placed into the code
try:
string_processor("aaaa")
except AttributeError:
print("Please enter a string instead.")
except TypeError:
print("Please input only 1 string.")
except NameError:
print("This is not a string, please input a string")
else:
print("String contained non-letters or unknown error occured")
出于某种原因,下面的这段代码能够让主要的 function 工作,但代价是只能获得属性错误,而不是其他特定错误,例如 TypeError 和 NameError。
def string_processor(string):
try:
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
return countA / len(string)
#Exceptions
except AttributeError:
print("Please enter a string instead.")
except TypeError:
print("Please input only 1 string.")
else:
print("string contains non-letters or unknown error occured")
string_processor("1,","1")
您的代码存在根本缺陷,因为它使用try-except
运行 function,除非传递给 function 的参数是非string
类型( int
, list
等),否则不会给出错误,即即使输入是11aa2b
, function 将简单地执行而不会引发任何错误。
尝试这样的事情:
def string_processor(string):
countA = 0
assert(string.isalpha())
for c in string:
if c=='a' or c=='A':
countA += 1
return countA
try:
print(string_processor('abA'))
except:
print('Please enter a string.')
问题是当代码没有异常时才会执行else语句。
尝试更换
else:
print("string contains non-letters or unknown error occured")
至:
except Exception:
print("String contained non-letters or unknown error occured")
甚至更好:
except Exception as e:
print(e)
这样,如果您遇到意外的异常,程序将打印它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.