繁体   English   中英

如何打印所有已定义的变量,除了等于0的变量 - Python3

[英]How to print all defined variables except for the ones that are equal to 0 - Python3

注意:我使用的是Python 3

我试图找出如何打印变量中设置的所有其他数字(在本例中为num1num2num3num4 ),除了零。 在过去的2到3天里,我一直在玩我的代码,但还没有找到任何解决方案。 我在互联网上搜索任何教程/代码示例,但仍无济于事。

num1 = 0
num2 = 2
num3 = 3
num4 = 4

if num1 != 0:
    test1 = num1
elif num2 != 0:
    test2 = num2
elif num3 != 0:
    test3 = num3
elif num4 != 0:
    test4 = num4

print(test1, test2, test3, test4)

以下是我在运行上述代码时不断出现的错误:

NameError: name 'test1' is not defined

我确信这是一个非常简单的问题,我只是遗漏了一些东西。

提前致谢。

这里,只有if num1 != 0:的语句为真时才会执行语句test1 = num1 ,这在你的情况下不是。 因此,test1变量甚至没有被创建。

所以,如果你可以为test1,test2,test3和test4创建空容器; 这将解决目的。

代码看起来像这样:

num1 = 0
num2 = 2
num3 = 3
num4 = 4

test1 = test2 = test3 = test4 = 0

if num1 != 0:
    test1 = num1
elif num2 != 0:
    test2 = num2
elif num3 != 0:
    test3 = num3
elif num4 != 0:
    test4 = num4

print(test1, test2, test3, test4)

输出: (0, 2, 0, 0)

一种选择是将所有变量放在列表中是这样的......

numbers = [num1, num2, num3, num4]

然后使用循环打印到不等于零的循环:

for num in numbers:
    if (num != 0):
        print(num)

那是因为变量test ... n在使用时没有指定的值试试这个:

num1 = 0
num2 = 2
num3 = 3
num4 = 4

test1=test2=test3= test4= int()

if num1 != 0:
test1 = num1
elif num2 != 0:
test2 = num2
elif num3 != 0:
test3 = num3
elif num4 != 0:
test4 = num4

print(test1, test2, test3, test4)

打印出来:(0,2,0,0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM