简体   繁体   中英

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

Note: I am using Python 3

I am trying to figure out how to print all other numbers that are set in the variables (in this case num1 , num2 , num3 and num4 ) except for zeros. I have been playing around with my code for the last 2 to 3 days and have not found any solution yet. I searched on the internet for any tutorials / code examples but still to no avail.

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)

Here is the error that I keep on getting when I run the code above:

NameError: name 'test1' is not defined

I am sure that this is a pretty simple problem and that I am just missing something.

Thanks in advance.

Here, the statement test1 = num1 would only get executed if the statement if num1 != 0: is true, which in your case is not. So, the test1 variable is not even getting created.

So, if you can create empty containers for test1, test2, test3 and test4; that would solve the purpose.

The code would look something like this:

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)

Output: (0, 2, 0, 0)

One option is to place all of the variables in a list is so...

numbers = [num1, num2, num3, num4]

Then use a loop to print to ones not equal to zero:

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

That's because the variables test...n have no assigned values at the time of usage Try this:

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)

Prints out : (0,2,0,0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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