[ 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)
<p>Here is the error that I keep on getting when I run the code above:</p>
<pre class="lang-none prettyprint-override"><code>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.
Answer 1
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)
Answer 2
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)
Answer 3
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)