簡體   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