Question

my_age = 35 
my_height = 74 
my_weight = 180 

print "If I add %d, %d, and %d I get %d." % (
  my_age, my_height, my_weight, my_age + my_height + my_weight)

The output of this code is:

If I add 35, 74, and 180 I get 289.

I don't really understand how this works, the way it interprets it would be:

print "If I add %d, %d, and %d I get %d." % (
  35, 74, 180, 35 + 74 + 180)

Could someone explain? Why is my_age in there twice?

Was it helpful?

Solution

my_age + my_height + my_weight expression yields an integer (the sum that gets printed). If you want to print pluses:

my_age = 35 
my_height = 74 
my_weight = 180 

print("{a} + {b} + {c} = {sum}".format(a=my_age, b=my_height, c=my_weight, 
                                       sum=(my_age + my_height + my_weight)))

Why is my_age in there twice?

It occurs once to be printed and the second time as the part of the sum as well as my_height and my_weight variables.

sum gets its value from the expression to the right of it (the expression in parens). In this case it is the sum of my_age, my_height, and my_weigh.

If it is hard to understand then open Python console and type:

>>> my_age = 35 
>>> my_height = 74 
>>> my_weight = 180 
>>> my_age
35
>>> my_age + my_height
109
>>> my_age + my_height + my_weight
289

+ operator computes the sum of its operands in Python. Once you've got the result e.g., 289; it doesn't remember that you used other numbers to get it. 289 is an ordinary number. To illustrate:

>>> (1 + 1) == (4 - 2) == 2
True

In this case the result 2 is produced using 3 methods: sum, difference, and directly via Python literal.

OTHER TIPS

You can also use a dictionary to store all information needed about the person, and use the unpacking feature of python to extract assign all keys to it's respective value in the format syntax.

Please be aware I calculated the sum of the person as well in the dictionary.

person = dict()
person['my_age'] = 35
person['my_height'] = 74
person['my_weight'] = 180
person['sum'] = person['my_age'] + \
                            person['my_height'] +\ 
                            person['my_weight']

print "{my_age} + {my_height} + {my_weight} = {sum}".format(**a)
>> 35 + 74 + 180 = 289
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top