Reputation: 35
i have a code like this...
if A == 0:
A = "no"
if B == 0:
B = "no"
if C == 0:
C = "no"
if D == 0:
D = "no"
if E == 0:
E = "no"
if G == 0:
G = "no"
how to make this simple?
Thank you for answering! Hv a nice day and stay home!
Upvotes: 2
Views: 79
Reputation: 33335
If those variables were in a list or dictionary then you could loop through them. But since they're just separate variables with no organization, there's not a lot you can do.
You could simplify the code a little by making a function:
def zero_to_no(val):
if val == 0:
return "no"
else:
return val
Then your main code would be:
A = zero_to_no(A)
B = zero_to_no(B)
# etc.
Upvotes: 2
Reputation: 73460
You should use a list
:
lst = [A, B, C, D, E, G]
A, B, C, D, E, G = (x or "no" for x in lst)
# A, B, C, D, E, G = ("no" if x == 0 else x for x in lst)
Maybe (probably) you don't need all the individual variables at all.
Upvotes: 1
Reputation: 10430
Try this:
def convert(a):
if a == 0:
return "no"
return a # or anything you want
a = convert(a)
print(a)
li = [1, 2, 3, 0, 0, 12, "abcd" ]
print([convert(i) for i in li])
Outputs:
no
[1, 2, 3, 'no', 'no', 12, 'abcd']
Other way to write the same function in Python:
def convert(a):
return 'no' if a == 0 else a# or anything you want
However, if they are saved in a list, then using list comprehension makes more sense:
li = [1, 2, 3, 0, 0, 12, "abcd" ]
print(["no" if x == 0 else x for x in li])
Upvotes: 1
Reputation: 17322
you should use a dictionary to store your variables so you can change the value of your variables using a dictionary comprehension:
my_vars = {'a' : 0, 'b' : 1, 'c': 0, 'd': 0, 'e': 0, 'g': 8}
my_vars = {k: 'no' if v == 0 else v for k, v in my_vars.items()}
Upvotes: 1
Reputation: 13387
I would do:
func=lambda *y: ['no' if x==0 else x for x in y]
A, B, C, D, E, G=func(A, B, C, D, E, G)
Upvotes: 0
Reputation: 1
I am not sure what you want to achieve exactly, but this should work for you:
def is_not_0(val):
if val == 0:
return "no"
return "yes"
A = is_not_0(A)
Upvotes: 0