-1

I have a python assignment I cannot figure out. My assignment is to create a text-only chess board using nested loops and generates the following output when run:

a8 b8 c8 d8 e8 f8 g8 h8
a7 b7 c7 d7 e7 f7 g7 h7
a6 b6 c6 d6 e6 f6 g6 h6
a5 b5 c5 d5 e5 f5 g5 h5
a4 b4 c4 d4 e4 f4 g4 h4
a3 b3 c3 d3 e3 f3 g3 h3
a2 b2 c2 d2 e2 f2 g2 h2
a1 b1 c1 d1 e1 f1 g1 h1

So far I have:

for i in range(8, 0, -1):
    for j in range(8, 0, -1):
        print("a", i, end=" ")
        print("b", j, end="")
 print()

Which gives:

a 8 b 8a 8 b 7a 8 b 6a 8 b 5a 8 b 4a 8 b 3a 8 b 2a 8 b 1
a 7 b 8a 7 b 7a 7 b 6a 7 b 5a 7 b 4a 7 b 3a 7 b 2a 7 b 1
a 6 b 8a 6 b 7a 6 b 6a 6 b 5a 6 b 4a 6 b 3a 6 b 2a 6 b 1
a 5 b 8a 5 b 7a 5 b 6a 5 b 5a 5 b 4a 5 b 3a 5 b 2a 5 b 1
a 4 b 8a 4 b 7a 4 b 6a 4 b 5a 4 b 4a 4 b 3a 4 b 2a 4 b 1
a 3 b 8a 3 b 7a 3 b 6a 3 b 5a 3 b 4a 3 b 3a 3 b 2a 3 b 1
a 2 b 8a 2 b 7a 2 b 6a 2 b 5a 2 b 4a 2 b 3a 2 b 2a 2 b 1
a 1 b 8a 1 b 7a 1 b 6a 1 b 5a 1 b 4a 1 b 3a 1 b 2a 1 b 1

I know it should be simple but i just cannot figure it out.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You need one loop from `"a"` to `"h"` and one loop from `1` to `8`. You can do it! See [this](https://stackoverflow.com/questions/538346/iterating-each-character-in-a-string-using-python) – user8408080 Mar 03 '20 at 20:18
  • [This](https://stackoverflow.com/questions/7001144/range-over-character-in-python) could be helpful to iterate over letters. – makozaki Mar 03 '20 at 20:21

1 Answers1

1

Try this

letters = 'abcdefgh'
for i in range(8, 0, -1):
    for letter in letters:
        print(letter + str(i), end = ' ')
    print()

The key here is having the letters variable containing the letters from a to h. With for x in iterable you can iterate over the elements that iterable has. Strings are iterables where each item is a single character (which in python is also a string of one length 1), so it makes iterating over structures easier. If you're wondering, yes, you could also have a numbers = '87654321' variable to do for number in numbers instead of for i in range(8, 0, -1). Hope this helps you in the future with similar problems.

Shinra tensei
  • 1,283
  • 9
  • 21