0

Can you explain what this python code means.

     for v in m.getVars():
           print('%s %g' % (v.varName, v.x))  

The output for the print is

     x 3
     y 5

The '3' and '5' are values of '(v.varName, v.x)' I don't get how it knows to print 'x' and 'y' and what other uses are there for '%' other than finding the remainder.

Brian
  • 25,523
  • 18
  • 82
  • 173
  • It is format string. `%s` is a placeholder for string and `%g` probably an integer. (I'm not sure about it). Parameters after last `%` would be placed instead of placeholders. – Mehraban Jun 23 '14 at 18:24
  • 1
    From the docs, @SAM is correct https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting – CDspace Jun 23 '14 at 18:32
  • It's an overloaded binary operator that when applied to a string is known as [string interpolation](https://docs.python.org/2/reference/expressions.html?highlight=interpolation#binary-arithmetic-operations). – martineau Jun 23 '14 at 18:33
  • 3
    [What does % do to strings in Python?](http://stackoverflow.com/q/1238306/1258041) – Lev Levitsky Jun 23 '14 at 18:36

2 Answers2

1

The command

for v in m.getVars():

Assigns the list of all Var objects in model m to variable v.

You can then query various attributes of the individual variables in the list.

For example, to obtain the variable name and solution value for the first variable in list v, you would issue the following command

print v.varName, v.x

You can type help(v) to get a list of all methods on a Var object

As others mentioned % is just place holders To understand how your code works, inspect the model m

Ravi Yenugu
  • 3,895
  • 5
  • 40
  • 58
0

It is a way to simplify strings when contain many variables. In python, as you see, you made a string in your print statement which reflects the variables v.varName and v.x. When a percent sign is used in a string, it will be matched, in order, with the parameters you give it.

There are specific letters used for each TYPE of variable. In your case you used "s" and "g" representing a string and a number. Of course numbers are turned into strings if you are creating a string (like in this case).

Example:

x = 20
y = "hello"
z = "some guy"

resulting_string = "%s, my name is %s. I am %g years old" % (y, z, x)

print resulting_string

The result will be:

hello, my name is some guy. I am 20 years old

Notice that the order in the variables section is what gives the correct ordering.

ZekeDroid
  • 7,089
  • 5
  • 33
  • 59