python if子句不起作用

2024-10-05 10:53:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来查找ISBN号码中丢失的数字。你必须找到前9个数字中11个的余数,像这样相乘:第一个*10,第二个*9,第三个*8,等等。如果余数等于第10位,则ISBN是正确的。你知道吗

我有一些代码,在问号的空格中放一个0,然后在0所在的数字中找到索引,然后将索引加1*到总数中,然后按11进行修改。然后,如果11的余数不等于第10个数字,它将尝试2*索引,并一直运行,直到找到正确的数字。但是,完成最后一部分的代码块没有触发,我也不知道为什么。你知道吗

def calculate_missing(x):
    tally=1
    for item in x:
        if item=='?':
            break
        elif item!='?':
            tally+=1
    if tally==10:
        without=str(x).replace('?','')
        if isbncalculate(without)==10:
            return 'x'
        elif isbncalculate(without)==11:
            return '0'
        else:
            return isbncalculate(without)
        #these just find the missing digit if it is the final digit.
    multiply=11-tally
    x=x.replace('?','0')
    lastdig=x[9]
    x=x.replace(x[9],'')
    time=10
    newnum=0
    for item in str(x):
        item=int(item)
        item*=time
        newnum+=int(item)
        time-=1
    otherthing=6
    if lastdig=='x' or lastdig=='X':
        lastdig=10
    elif lastdig=='0':
        lastdig='11'
    final=newnum+(otherthing*multiply)
    answer=final%11
    for item in range(0,10):
        if answer==lastdig:
            #this code won't trigger!
            return otherthing
        else:
            otherthing+=1

最后几行是我正在努力解决的问题。如果我输入calculate_missing('567?545653'),它应该返回6,但是它只返回nothing。你知道吗


Tags: inforreturniftime数字itemreplace
1条回答
网友
1楼 · 发布于 2024-10-05 10:53:05

替换:

if answer==lastdig:

使用:

if answer==int(lastdig):

即使answerlastdig都相等,但answer是一个整数lastdig是一个字符串。因此,要么在比较时将answer转换为字符串,要么将lastdig转换为整数。这将解决问题。你知道吗

相关问题 更多 >

    热门问题