1

I want to try and make my print function automatically substitute the variable 'a' 'b' and 'c' with one of the values assigned to those variables in my tests. How would I do this? My ideal output would look like this Equation: 1x**2 + 4x + 4 One root. 2.0

import math def quadraticRoots(a,b,c): print('Equation: ax**2 + bx + c') # (this is what I am trying and it doesn't work) discriminant = b**2 - 4 * a * c if discriminant > 0: root1 = float(-b + math.sqrt(b**2 - 4 * a * c))/ (2 * a) root2 = float(-b - math.sqrt(b**2 - 4 * a * c))/ (2 * a) print('Two roots.') print(root1) print(root2) elif discriminant == 0: root1 = float(-b + math.sqrt(b**2 - 4 * a * c))/ (2 * a) print('One root.') print(root1) elif discriminant < 0: print('No roots.') def test(): quadraticRoots(1,0,0) quadraticRoots(2,-11,-21) quadraticRoots(4,1,4) quadraticRoots(1,2,8) quadraticRoots(3,-11,19) quadraticRoots(1,4,4) quadraticRoots(16,-11,64) quadraticRoots(1,18,81) quadraticRoots(1,7,42) quadraticRoots(5,10,5) test() 

2 Answers 2

4

Try the following:

print('Equation: {0}x**2 + {1}x + {2}'.format(a,b,c)) 
Sign up to request clarification or add additional context in comments.

5 Comments

Note that when you're accessing positional arguments in order, you can omit the numbers from your format string, and just use {}s. You only need the numbers if you're doing something complicated, like repeating them or using them in a different order than the arguments are provided.
Today I've learned. I didn't know that you can use {} only :)
Me too, did not know that. +1 to Blckknght's comment for teaching something cool :)
{0:2.1}. The 2 is the total number of digits while the 1 is the number of decimal digits (precision).
You can also use keyword instead of positional arguments to format print('Equation: {a}x**2 + {b}x + {c}'.format(a=a, b=b, c=c)), which looks pretty close to the original equation.
1

Are you stating that

 print('Equation: ax**2 + bx + c') 

does not print the equation with values for a , b and c

print ('equation: ' + str(a) + 'x**2 + ' + str(b) + 'x + ' + str(c)) 

the problem is that you are asking it to print a literal but you want it to print based on your values. CAVEAT I think you must be using a 3+ flavor of python and I work in 2.7

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.