簡體   English   中英

Python返回none而不是True或False

[英]Python Returns none instead of True or False

我正在創建一個名為isSiete()的函數,它將接受來自帶有5000個隨機數的txt文件的整數。

如果數字的第二列數字(“十”列)為“7”則返回True,否則返回False。

def isSiete(num):
    numString = str(num)
    numList = list(numString)
    numSum = 0
    for i in numList:
        if ('0' + i)[-2] == '7':
            return True
        else:
            return False

我希望輸出為True但我每次都得到False。 我試過以下測試數字

isSiete(7777)isSiete(4774)isSiete(672)

根本不打擾弦; 將它除以10倍的速度要快一個數量級。

def isSiete(num):
    return num // 10 % 10 == 7

隨着num的大小增加,算法變慢,但當num是17位數時,這仍然更快。

你的('0' + i)[-2]總是等於字符'0'

例如,假設numList == ['A', 'P', 'P', 'L', 'E']假設inumList的元素,例如'P'

然后'0' + i == "0P"

[-2]獲得倒數第二個字符
"0P"[-2] == "0"

請注意, P是什么並不重要。 '0' + i的倒數第二個字符始終為'0'

('0' + i)[-2] == '7'將始終返回False


我鼓勵您了解“模數運算符”( %

x % 10x % 10的余數除以10.例如, 74 % 10 == 4

通常, x % y是除以yx的余數

要從數字中提取特定數字,請執行以下操作:

def extract_digit(number, position):
    """
    position == 1 ......if you want the ones place
    position == 2 ......if you want the tens place
    position == 3 ......if you want the hundredths place
    position == 4 ......if you want the thousanths place
    and so on...
    """ 
    small_places = number % (10**position)
    digit = small_places //(10**(position - 1))
    return digit

例如,假設你想要百位的123456789

123456789 % 1000 == 789      
789 // 100 == 7

作為最終結果,我們有:

def isSiete(num):
    return extract_digit(num, 2) == 7

您可以簡單地使用轉換后的字符串來檢查您的條件,因為python中的字符串可用作字符數組:

def isSiete(num):
    numString = str(num)
    tensPosition = len(numString) - 2

    if tensPosition >= 0 and numString[tensPosition] == '7':
        return True
    else:
        return False

我不確定您是否要求幫助來調試您的代碼,或者您是否希望獲得有關工作解決方案的幫助。

如果你想要一個解決方案:這是一個工作片段,可以幫助你實現你想要的。

def is_siete(num):
    """
    Asserts that the tens of a number is 7. Returns False if not.
    """
    num_as_str = str(num)

    try:

        second_num_as_str = num_as_str[-2]
        second_num_as_int = int(second_num_as_str)

        if second_num_as_int == 7:
            return True

        return False

    except IndexError:
        return False


if __name__ == "__main__":
    print(is_siete(7777))  # True
    print(is_siete(4774))  # True
    print(is_siete(672))  # True
    print(is_siete(17))  # False
    print(is_siete(7))  # False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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