簡體   English   中英

如何找出放置“try”功能的問題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM