Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #73731

Re: Newbie coding question - format error

From Sibylle Koczian <nulla.epistola@web.de>
Subject Re: Newbie coding question - format error
Date 2014-06-29 16:09 +0200
References <CAHXoDSAFHbPcU+gwvJPsairQMJmFEf1B6Sn2gw3_OHT1_EPw8A@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.11326.1404051003.18130.python-list@python.org> (permalink)

Show all headers | View raw


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.



Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: Newbie coding question - format error Sibylle Koczian <nulla.epistola@web.de> - 2014-06-29 16:09 +0200
  Re: Newbie coding question - format error Roy Smith <roy@panix.com> - 2014-06-29 10:47 -0400

csiph-web