Skip to main content
 首页 » 编程设计

Python If 语句永远不会计算为真

2025年05月04日13虾米哥

如果我的问题看起来微不足道,我深表歉意。我宁愿在聊天室里问这个问题;但是,目前我的声望太低,所以我无法在 Python 聊天室中询问任何内容。我目前正在为一个类(class)学习 Python,老师给了我们一些练习题来让我们快速上手。我正在构建的函数现在接受一个数字列表并将其转换为一个字符串。我遇到的问题是我的 if 语句从未评估为真。我尝试了几种处理变量的方法,并添加了许多打印语句以查看它们是否应该相等,但无济于事。再次感谢。我保证我只是在研究和尝试了很多方法之后才问,但现在不知所措......这是我的代码:

def nlist2string(nlist): 
    characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] 
    numbers = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25'] 
    newList = [] 
    nListLen = len(nlist)         # var msgLen will be an integer of the length 
 
    print 'Number list before conversion: ', nlist 
 
    index = 0 
    while index < nListLen: 
        print 'Index at: ', nlist[index] 
        num = nlist[index] 
        print 'Is num equal to nlist indexed? ', num 
        newNum = num % 26 
 
        i = 0 
        while i < 26: 
            num1 = newNum 
            num2 = numbers[i] 
            print 'num1 = ', num1 
            print 'num2 = ', num2 
            if (num1 == num2): 
                newList.append(characters[i]) 
                print 'Here is the current newList: ', newList 
            else: 
                print 'They never equal each other.' 
            i = i + 1 
        index = index + 1 
    return newList 
 
    numMessage = [28, 0, 33] 
    convertedNumMsg = nlist2string(numMessage) 
    print 'Number list after conversion: ', convertedNumMsg 

请您参考如下方法:

您正在尝试将整数与字符串进行比较,请尝试将您对 numbers 的定义更改为以下内容:

numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] 

或者,numbers = range(26)。

当前,当比较 num1 和 num2 时,您将进行类似 4 == '4' 的比较,这永远不会是真的:

>>> 4 == '4' 
False 

作为更改创建 numbers 列表方式的替代方法,您可以将 num2 转换为整数或将 num1 转换为字符串比较,所以 num1 == int(num2) 或 str(num1) == num2。