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

标签 python if-statement equality

如果我的问题看起来微不足道,我深表歉意。我宁愿在聊天室里问这个问题;但是,目前我的声望太低,所以我无法在 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)

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

>>> 4 == '4'
False

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

关于Python If 语句永远不会计算为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15709288/

相关文章:

Python 不能根据两个整数的值给字符串赋值

javascript - int和string、array比较的逻辑是什么?

c# - 强制 VB.NET 生成与 C# 相同的字符串比较表达式?

php - 我想为多个变量 If 条件速记添加值

R 循环太长

python - 在 matplotlib 中绘制二进制时间线

python - 如何使用 MySQLdb 在 django 中创建回滚按钮?

c# - 在 C# 中比较两个字符串数组

python - 如何从 Python 代码中获取类和定义图?

python - Python 的 set() 在 C 中是否有等价物?