Craig Gardner Craig Gardner - 2 days ago 3
Python Question

How to print text with the value of a variable

I have written a small function to check which of two values is closest to zero. The issue I am having is with the print statement at the end: I want it to print the text followed by whichever value it determines is the closest.

def closestcheck(ylow, yhigh, ylist, xlist):
ynew = (ylow + yhigh) / 2
#The following 2 prints are purely to check the calculations are correct
print(ynew)
print(ylow,yhigh)
if ynew > 0:
print('The closest value of theta is' % ylow)
else:
print('The closest value of theta is' % yhigh)

closestcheck(y0[-1],y0[-2],y0,x0)


It will print the text but not the number


6.13910823576e-07

-3.46867223283e-06 4.69649387998e-06

The closest value of theta is


This specific syntax has worked in other cases but not here, I'm unsure as to why. An explanation of why this isn't working and how to fix it would be much appreciated, thank you!

wim wim
Answer

You're trying to use string templating, but you didn't specify where in the template to fill in the variable.

if ynew>0:
    print('The closest value of theta is %f' % ylow)
else:
    print('The closest value of theta is %f' % yhigh)

While you're at it, string templating with % kind of smells like grandma's linen cupboard these days. Recommended to use this instead:

y_closest = ylow if ynew > 0 else yhigh
print('The closest value of theta is {y}'.format(y=y_closest))
Comments