Thread: I'm a Beginner
View Single Post
Old Dec 12th, 2007, 6:29 PM   #26
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,869
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
Re: I'm a Beginner

No it would not. Let's look at what you're trying to do:

1) First Line

For i in b

Commands are case sensitive. For is not a valid command. for is the command you're looking for.

It assigns i to each element in b sequentially. But what's b? You have not defined it at this part of the program. Remember that a program executes one line at a time, and at this point in time, there is no value for b.

Later you do give a value to b: b= range (1,11). If you want to stay consistent with this, your first line becomes:

for i in range (1,11)

Then you need a colon at the end to denote the start of a new block. Everything that proceeds the colon, and is indented, will execute for each element in b.

for i in range(1, 11):
    # Do some stuff here for each element in range(1, 11)

It's important to note... since b is range(1, 11), Python will convert this to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

So the same code could also be written as:

for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    # Do some stuff here for each element in range(1, 11)

But that's not as modifiable.

2) Looking at your Second Line

print '%d*%d=%d' % (i,b,i*b)

You're trying to output i*b and b, but b is a list of elements 0 through 10. That's an invalid operation. You can't multiply numbers by lists.

It looks like you're trying to do something like multiply 1 to 11 by 1 to 13 like a grid. You'll need to understand for loops a bit better before you can do that.

3) Using a for loop

If we go back to my previously posted code, and modify it to print the number each iteration:

for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    print i

You get the output:

1
2
3
4
5
6
7
8
9
10

Which will be the same output for:

for i in range(1, 11):
    print i

If we extend this to make a loop within a loop, you'll get this:

for i in range(1, 11):
    for j in range(1, 11):
        print i, j

Which will output:
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
2 1
2 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
3 1
3 2
3 3
3 4
3 5
3 6
3 7
3 8
3 9
3 10
4 1
4 2
4 3
4 4
4 5
4 6
4 7
4 8
4 9
4 10
5 1
5 2
5 3
5 4
5 5
5 6
5 7
5 8
5 9
5 10
6 1
6 2
6 3
6 4
6 5
6 6
6 7
6 8
6 9
6 10
7 1
7 2
7 3
7 4
7 5
7 6
7 7
7 8
7 9
7 10
8 1
8 2
8 3
8 4
8 5
8 6
8 7
8 8
8 9
8 10
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
9 9
9 10
10 1
10 2
10 3
10 4
10 5
10 6
10 7
10 8
10 9
10 10

You could then modify this to do the multiplication grid you wanted.

Last edited by Sane; Dec 12th, 2007 at 6:50 PM.
Sane is offline   Reply With Quote