簡體   English   中英

為什么收到此錯誤“ IndexError:字符串索引超出范圍”

[英]Why am I getting this Error “IndexError: string index out of range”

我們被要求編寫一個驗證GTIN-8代碼的程序。 評估如下:

  1. 將前7個數字交替乘以3再乘以1

  2. 加起來

  3. 用等於或大於10的倍數減去該數字

  4. 結果數字是第八位

這是我的代碼:

def validgtin():  

    gtin = input("Enter the 8 digits of GTIN-8 product code: ")   
    valid = False
    while valid == False:
        if gtin.isdigit():               
            gtin = str(gtin)
            if len(gtin) == 8:          
                valid = True
            else:
                print("That is not correct, enter 8 digits, try again: ")       
                gtin = input("Enter the 8 digits of GTIN-8 product code: ")
        else:
            print("That is not correct, type in numbers, try again: ")
            gtin = input("Enter the 8 digits of GTIN-8 product code: ")     


    sumdigit =  3*(int(gtin[0])) + 1*(int(gtin[1])) + 3*(int(gtin[2])) + 1*(int(gtin[3])) + 3*(int(gtin[4])) + 1*(int(gtin[5])) + 3*(int(gtin[6]))  #sum of the digits

    gtin = str(gtin)  

    valid1 = False
    while not valid1:
        if sumdigit%10 == 0:    
            eightdigit = 0
        else:
            eightdigit = (((sumdigit + 10)//10)*10) - sumdigit  

        if eightdigit == (gtin[7]):
            valid1 = True
            print("Your GTIN-8 product code is valid.")

        else:
            print("Your GTIN-8 product code is not valid.")
            gtin = input("Enter the 8 digits of GTIN-8 product code: ")


    return

validgtin()

當我運行此代碼並輸入無效的GTIN-8代碼時,它表示該代碼無效,並提示我輸入新的GTIN-8代碼

輸入新的有效的GTIN-8代碼后,它仍然表示無效

之后,這會發生:

Traceback (most recent call last):



File "C:\Users\Yash Dwivedi\Documents\Year 10\GCSE Computing\Assignment\Task 1 v2.py", line 29, in validgtin
    if eightdigit == (gtin[7]):
IndexError: string index out of range

我不明白為什么我會感謝您的幫助。

我建議創建一個“ is_valid_gtin”函數,該函數僅在沒有I / O的情況下檢查GTIN是否有效。 然后一個簡單的“ main()”來檢查代碼:

def is_valid_gtin(gtin):
    if len(gtin) != 8 or not gtin.isdigit():
        return False
    sum = 0
    for i in list(gtin)[0:6:2]:
        sum += 3*int(i)
    for i in list(gtin)[1:6:2]:
        sum += int(i)
    checksum = (10 - sum % 10) % 10
    return checksum == int(gtin[7])


def main():
    while (True):
        gtin = input("Enter the 8 digits of GTIN-8 product code: ")
        if is_valid_gtin(gtin):
            print("Your GTIN-8 product code is valid.")
            break
        else:
            print("That is not correct, try again.")

if __name__ == '__main__':
    main()

這是我的快速實施。 遺憾的是,我沒有任何測試數據來檢查其是否正確!

def _round_up_ten(number):
    if number % 10 == 0:
        return number
    return 10 * (1 + (number / 10))


def validate_gtin(gtin):
    if not gtin.isdigit() or len(gtin) != 8:
        raise ValueError("GTIN must be an 8-digit number")

    digits = [int(digit) for digit in gtin[:-1]]
    check_digit = int(gtin[-1])

    multiplied_digits = (
        digits[0] * 3
        + digits[1]
        + digits[2] * 3
        + digits[3]
        + digits[4] * 3
        + digits[5]
        + digits[6] * 3
    )

    expected_check_digit = _round_up_ten(multiplied_digits) - multiplied_digits

    if check_digit!= expected_check_digit:
        raise ValueError("Incorrect check digit ({}) (expected {})".format(check_digit, expected_check_digit))

錯誤在行

if eightdigit == (gtin[7]):

eightdigit是一個整數,但gtin[7]是一個字符串。 因此,此比較始終是錯誤的-因此,您處於無限循環中(只要輸入至少包含8個字符的字符串)。 您感到沮喪,然后只需按Enter鍵-它將空字符串(缺少第八個字符)傳遞給您的代碼,從而觸發索引超出范圍錯誤。

因此,您將需要:

if eightdigit == int(gtin[7]):

來修復該特定錯誤,盡管這仍然會給您帶來邏輯錯誤-因為代碼底部的循環無法驗證輸入,並且您正在嘗試根據先前輸入計算出的校驗位來檢查新的候選gtins 。 您可能應該遵循@JacquesSupik的絕妙想法,並重構代碼,以使驗證邏輯與I / O邏輯分離。

暫無
暫無

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

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