[Tutor] For Loops and nested loops

Lie Ryan lie.1296 at gmail.com
Sat Aug 16 19:39:40 CEST 2008


On Sat, 2008-08-16 at 18:07 +0200, tutor-request at python.org wrote:
> Message: 1
> Date: Sat, 16 Aug 2008 06:33:42 +0100
> From: Umesh Singhal <umeshsinghal at hotmail.co.uk>
> Subject: [Tutor] For Loops and nested loops
> To: <tutor at python.org>
> Message-ID: <BAY117-W2038EBB1B32FC8CD7FD730826C0 at phx.gbl>
> Content-Type: text/plain; charset="windows-1252"
> 
> 
> Hi im still relatively new to python and i am designing a
> multiplication table that enables a user to input the size of the
> times table unfortunately ive stumbled on the nested loops this is
> what i have right now:
> 
> a=raw_input('please enter a number')
> b=int(a)
> n=b+1
> for row in range(1, n):
>      for col in range(1, n):
>              print "%3d " % (row * col),
>      print
> 
> the input which comes out is:
>   1    2    3    4    5 
>   2    4    6    8   10 
>   3    6    9   12   15 
>   4    8   12   16   20 
>   5   10   15   20   25
> 
> however i need something more on the lines of:
> | 2 3 4 5
> ==================
> 2 | 4 6 8 10
> 3 | 6 9 12 15
> 4 | 8 12 16 20
> 5 | 10 15 20 25
> 
> does anyone know what i need the third nested for loop to be ? to make
> it like the above example. Pleasee help me !! 

You don't need to use third nested loop, your two nested loop is enough.

First, however, you need to think first, how you'd generate the output.
Following your thinking pattern, I'd do it like this:

#1
| 2 3 4 5

#2
| 2 3 4 5
==================
2 |
 
#3
| 2 3 4 5
==================
2 | 4

#4
| 2 3 4 5
==================
2 | 4 6

#5
| 2 3 4 5
==================
2 | 4 6 8

#6
| 2 3 4 5
==================
2 | 4 6 8 10


#7
| 2 3 4 5
==================
2 | 4 6 8 10
3 | 

#8 etc

Do you see how you could generate the table headings?



More information about the Tutor mailing list