首页 > 解决方案 > python:检查一个变量是否有值

问题描述

我是 python 新手,正在使用 while 循环。我有一个场景,我需要检查一个变量是否有一个与之关联的值或字符串,并找到这个我不应该在 python 中使用内置函数。我尝试在 while 循环中使用以下内容,但它的抛出错误如下所示:

代码:

li = [1,2,3,4,5,"string1", "string2"]

print ("Test of List")

i = 0

while (li[i] != ""):
    print (li[i])
    i = i + 1

print ("Val of i :",i)

输出:

Test of List

1

2

3

4

5

string1

string2

Traceback (most recent call last):

  File "C:\Users\sesubra2\Desktop\python_codes.py", line 71, in <module>

    while (li[i] != ""):

IndexError: list index out of range

标签: pythonwhile-loop

解决方案


li = [1, 2, 3, 4, 5, "string1", "string2"]

print ("Test of List")

i = 0

while (i < len(li)):
    if(li[i] != ""):
        print (li[i])
    i = i + 1

print ("Val of i :", i )

原因是您的 while 语句是错误的。试试看

如果你仍然喜欢你的逻辑,试试看

def checkValiable(array, i):

    while (array[i] != ""):
        print (li[i])
        i = i + 1

    if(i < len(array) - 1):
        del array[i];
        checkValiable(array, i - 1)
        return

    print ("Val of i :", i)
    return array

li = [1, 2, 3, 4, 5,"", "string1", "string2"]


print ("Test of List")

i = 0
li.append("")

checkValiable(li, i)

推荐阅读