Formatted string literals (: ) are used to show the sign of a number ( or -). e.g:
a = 2
b = -5
print(f"{a b: }")
output: -3
or
a = 2
b = 5
print(f"{a b: }")
output: 7
If the output is 0, it is given as 0.
Is there a way in which if the sum of a and b is 0, the output should return nothing (I'm not sure what that would mean), or maybe output an empty string?
Example: Gn = c (a-b)
If a is 3 and b is 3 as well, the output should be Gn = c. Not Gn=c 0
I have tried to apply some conditional statement wrt 0, to return an empty string instead but Formatted string literals (: ) only work on integers.
CodePudding user response:
Is there a way in which if the sum of a and b is 0, the output should return nothing (I'm not sure what that would mean), or maybe output an empty string?
Make a format helper. Non-zero is considered True, so you can return an empty string if the number is false:
def fmt(i):
return f'{i: }' if i else ''
a = 1
for b in range(3):
print(f'result: {fmt(a-b)}')
Output:
result: 1
result:
result: -1
CodePudding user response:
I'm not sure I'm totally following, but in your case, maybe just do the computation and branch on that:
c = 1
a = 2
b = 3
a_minus_b = a - b
if a_minus_b:
print(f"Gn = {c} ({a} - {b})")
else:
print(f"Gn = {c}")
Of course this could be done more fancily (if less readably), e.g.
print(f"Gn = {c} ({a} - {b})" if a_minus_b else f"Gn = {c}")
or
print(f"Gn = {c}" f" ({a} - {b})" if a_minus_b else "")
CodePudding user response:
You could insert a conditional statement to check sum of both variables, and if if the sum is zero you can print an empty string literals or else you can print the actual value.
a = 2
b = -3
if a b == 0:
print(f"")
else:
print(f"{a b: }")