[Tutor] printing puzzlement

alan.gauld@bt.com alan.gauld@bt.com
Mon, 12 Aug 2002 11:26:18 +0100


> As seen in the C++ code snippet here, calculations are 
> performed in the middle of the display of each line of 
> output. Does anyone  know of a good way to reproduce 
> similar behavior in a Python program?

The same way the C++ programmer would have done it if 
[s]he'd had any sense - using a string buffer and then 
writing the full string out!

In Pythons case use a format string and some variables 
to hold the intermediate values...

> 	// Display the amortization schedule
> 	for (int index = 0; index < numPayments; index++)
> 	{
> 		cout << setw(5) << right << (index + 1);
> 		cout << setw(12) << right << fixed << 
> setprecision(2) << principle;
> 		cout << setw(9) << right << fixed << amtPayment;

buff = "%5d%12.2d%9d" % (index+1,principle, amtPayment)

> 		float interest = (float (int (principle * 
> monthRate * 100) ) ) / 100.0;
> 		cout << setw(11) << right << fixed << interest;
> 		principle = principle + interest - amtPayment;
> 		cout << setw(12) << right << fixed << principle;

buff = buff + "%11d%12d" % (interest, principle)

> 		cout << endl;

print buff

The types and precisions might need frigging but 
you hopefully get the idea I'm suggesting.

Alan g.