我的代码有什么问题吗?

时间:2013-09-01 12:05:09

标签: python

def isbn10(x):
    y = [int(i) for i in x]
    a = y[0] * 10 + y[1] * 9 + y[2] * 8 + y[3] * 7 + y[4] * 6 + y[5] * 5 + y[6] * 4 + y[7] * 3 + y[8] * 2
    checkno = a % 11
    checkno = 11 - checkno
    if checkno == 10:
        checkno = "X"
    if checkno == prompt[9]:
        print("Your ISBN10 number is correct.")
    else:
        print("Your check number is wrong. It should be " + prompt[0:9] + checkno)


def isbn13(x):
    y = [int(i) for i in x]
    even = y[1] + y[3] + y[5] + y[7] + y[9] + y[11]
    odd = y[0] + y[2] + y[4] + y[6] + y[8] + y[10]
    even = even * 3
    total = even + odd
    checksum = total % 10
    checksum = 10 - checkno
    if checksum == prompt[-1]:
        print("Your ISBN13 number is correct.")
    else:
        print("Your check number is wrong. It should be " + prompt[0:-2] + checkno)
    #ok...


def main():
    prompt = input("Please type in your ISBN number.\n")
    prompt = str(prompt)

    if len(prompt) == 10:
        isbn10(prompt)
    elif len(prompt) == 13:
        isbn13(prompt)
    else:
        print("Your ISBN number is invalid")


while True:
    main()
    if input('Continue? [y/n]') == 'n':
        break

当我运行程序时......:

请输入您的ISBN号。 9876543210

Traceback (most recent call last):
  File "C:\Users\yc\Desktop\Computing\computing\python\Python ISBN\isbn_checker.py", line 29, in <module>
    isbn10(prompt)
  File "C:\Users\yc\Desktop\Computing\computing\python\Python ISBN\isbn_checker.py", line 11, in isbn10
    print("Your check number is wrong. It should be " + prompt[0:9] + checkno)
TypeError: cannot concatenate 'str' and 'int' objects

2 个答案:

答案 0 :(得分:1)

在这种情况下,

checkno是一个整数,你试图用字符串连接它。

checkno替换为str(checkno)

print("Your check number is wrong. It should be " + prompt[0:9] + str(checkno))

或者,更好地使用format()而不是连接:

print("Your check number is wrong. It should be {}{}".format(prompt[0:9], checkno))

此外:

  • checkno变量未在isbn13()函数
  • 中定义
  • 程序中没有main()函数
  • 代码难以阅读和理解。其中一个原因是它根本不遵循PEP-8样式

答案 1 :(得分:0)

print("Your check number is wrong. It should be " + prompt[0:9] + checkno)
TypeError: cannot concatenate 'str' and 'int' objects

实际上是非常自我解释,你甚至读过错误信息吗?

首先不要在同一个变量中存储不同类型的信息。

避免与Python中的+连接使用格式化构建。

print("Your check number is wrong. It should be %s%d" % (prompt[0:9],checkno) )