Newbie coding question - format error
Sibylle Koczian
nulla.epistola at web.de
Sun Jun 29 10:09:42 EDT 2014
Am 29.06.2014 09:06, schrieb Martin S:
>
> x=int(input('Enter an integer '))
> y=int(input('Enter another integer '))
> z=int(input('Enter a third integer '))
> formatStr='Integer {0}, {1}, {2}, and the sum is {3}.'
> equations=formatStr.format(x,y,z,x+y+z)
> print(equations)
> formatStr2='{0} divided by {1} is {2} with a reminder of {3}'
> equations2=formatStr2.format(x,y,x//y,x%y)
> print(equations2)
>
> And obviously this works.
> But the question is: if I want to keep the results of {2} and {3}
> between the first instance (formatStr) and the second (formatStr2) how
> would I go about it? Apprently using {4} and {5} instead results in a
> index sequence error as in
>
> IndexError: tuple index out of range
>
{0} ... {3} are just placeholders in your format strings, they can't
exist outside of them. And you can't put more placeholders into the
format string than you've got values to put into them. That's what the
IndexError is about.
But nothing forces you to put your calculations into the call to
format(). Instead, give names to the results you want to keep:
mysum = x + y + z
equation_sentence_1 = formatStr.format(x, y, z, mysum)
...
myquotient = x // y
myremainder = x % y
# or, nicer: (myquotient, myremainder) = divmod(x, y)
equation_sentence_2 = formatStr2.format(x, y, myquotient, myremainder)
...
Now you still can do all you want with mysum, myquotient, myremainder.
HTH
Sibylle
BTW: it's better to post here using text, not HTML. Not all newsreaders
and mail clients used for this list cope well with HTML. And it's just
luck that your code doesn't contain indentations, they might not
survive. Moreover code is much more readable with a fixed font which you
get as a by-product using text.
More information about the Python-list
mailing list