[英]How do I figure out my issue with placing the "try" function?
所以我一直在努力找出我的异常代码有什么问题,即只接受字符串,但只要括号之间有非字符串输入,它也会显示文本,这取决于我放置“try”和 except 函数的位置。
我在这里的第一个代码“尝试”是在返回之前,输入的任何字符串都将被接受到函数中,但是只要在底括号之间输入非字符串,除了函数将不起作用。
''' def string_processor(字符串):
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
try:
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except IndexError:
print("Please enter a string with quotation marks ")
else:
print("Please only enter a string")
字符串处理器(“000”)
'''
我输入的第二个代码“try:”可以整理出一些东西,例如 AttributeErrors,但只能在括号之间输入带有字母的字符串,并且函数中省略了任何包含非数字的字符串。
''' def string_processor(字符串):
尝试:
countA = 0 if (string.isalpha()): for c in string: if c == "a": countA = countA + 1
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except SyntaxError:
print("Please enter a string with quotation marks ")
else:
print("Please only put letters in your string")
字符串处理器(“000”)
'''
我请求帮助解决这个问题,以便我的程序可以获取任何类型的字符串,并将处理除函数之外的任何非字符串值。
我理解你的问题可能是错误的。 但这里是我的建议来解决你的问题。
首先,我无法理解您的代码,因为那里无法访问 else 语句,所以我稍微更改了它,但没有任何显着变化。
def string_processor(string):
# This is a bad way to check the types and the value
try:
if string.isalpha():
# If string has a type "string" and contains only letters
return string.count('a')/len(string)
elif string.isnumeric():
# If string has numbers only
print("Please enter a string instead")
except:
if isinstance(string, list):
# If type of the "string" is actually a list
print('This is not a string, this is a list')
elif type(string) == tuple:
# If type of the "string" is actually a tuple
print('This is not a string, this is a tuple')
else:
# If none of the above worked
print('It is definitely not a pure string')
a = string_processor(234)
正如我所评论的,这不是实现解决方案的好方法,更好的方法可能是:
def string_processor_another(value):
# It is better to RAISE exceptions, not to print them
if not isinstance(value, str):
raise TypeError('This must be a string')
# So if we come to this step we can be sure that we work with strings, so we can use the methods
if value.isalpha():
# If string has a type "string" and contains only letters
return value.count('a')/len(value)
elif value.isnumeric():
# If string has numbers only
print("Please enter a string instead")
b = string_processor_another(234)
如果您要添加一些额外的逻辑或者您想要更简洁的代码,我建议您以 oop 方式进行
class StringProcessor:
def __init__(self, string):
self.__check_for_str(string)
self.string = string
@staticmethod
def __check_for_str(string):
return isinstance(string, str)
# Here you can add short functions to make all of your logic statements
def check_is_numeric(self):
print(self.string.isnumeric())
def check_is_alpha(self):
print(self.string.isalpha())
sp = StringProcessor('1234')
sp.check_is_numeric() # True
sp.check_is_alpha() # False
希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.