-2

I have this line of code:

print ("(x %s)(x %s)") % (var_p1, var_p2)

But it does not work, I am new to programming and I don't know what I have done wrong. Any experts out there with a simple answer?

I wanted it to randomly select an equation for a parabola. e.g. (x-3)(x+1) However, it comes up with the error message:

Traceback (most recent call last): 
"File "E:/Python34/MyFiles/Math Study Buddy.py", line 26 in <module> 
print ("(x %s)(x %s)") % (var_p1, var_p2) 
TypeError: unsupported operand type (s) for %: 'NoneType' and 'tuple'
ShaunNZ
  • 77
  • 2
  • 9

3 Answers3

3

As you are in python 3 you need to put the variables inside the parenthesis after your string:

>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)

Note that in python 3 print is a function and you need to pass the string as its argument.So you can not put your variables outside the function!

For more detail read printf-style String Formatting

Note

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.

Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

you don't need to use 'x' to substitude variables here. This will fix:

print ("(%s)(%s)") % (var_p1, var_p2)

also, .format is better than %

see: Python string formatting: % vs. .format

Community
  • 1
  • 1
Sapocaly
  • 11
  • 3
  • as mentioned, in python 3 you want aparenthesis around the whole thing you want to print. I'm using python2.7 here, so you may want to change a little bit. – Sapocaly Apr 24 '15 at 09:18
0

You can use str.format

>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2))) 
(x test)(x test2)
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42