2

I'm learning to use python and I'm stuck on this code.

I want to display rows but instead I'm getting columns. I have tried different variations where, I get a row for the while loop but I still end up getting a column for the for loop.

Start_num = 0
Max_num = 200

while Start_num < 201:
    for Number in range (Max_num, -1, -25):
       print(Start_num, end=' ')
       Start_num += 25
       print(Number)

This is how the output currently looks for this code.

0 200
25 175
50 150
75 125
100 100
125 75
150 50
175 25
200 0

There is got to be a way to get two rows instead of columns, please help.

1
  • as a point of interest, you can refactor your code using two range objects and zip to skip the weirdness of incrementing by-hand. for a, b in zip(range(0, 201, 25), range(200, -1, -25)): print(a, b). This doesn't address how to format that by rows instead of columns, however. Commented Jan 26, 2017 at 23:58

2 Answers 2

5

Try this:

Start_num = 0
Max_num = 200

row1 = []
row2 = []
while Start_num < 201:
    for Number in range (Max_num, -1, -25):
       row1.append(str(Start_num))
       Start_num += 25
       row2.append(str(Number))
print(" ".join(row1))
print(" ".join(row2))

You need to build the rows ahead of time and then print them at the end. The terminal outputs only in text, it has no concept of rows or columns.

Sign up to request clarification or add additional context in comments.

1 Comment

THANK YOU, SOOO MUCH!
2

As a general rule, you can swap rows and columns with the idiom zip(*rows). Your code isn't quite constructed that way, but it would be trivial to change that.

# Your code, re-factored

results = zip(range(0, 201, 25), range(200, -1, -25))
# gives you a zip object that looks something like:
# # [ (0, 200), (25, 175), (50, 150), ..., (200, 0) ]
#
# you could duplicate your output with:
# # for pair in results:
# #    print(*pair)
#
# N.B. this would exhaust the zip object so you couldn't
# use it below without re-calculating results = zip(range(...

swapped_results = zip(*results)
# gives you a zip object that looks something like:
# # [ (0, 25, 50, ..., 200), (200, 175, 150, ..., 0) ]
for row in swapped_results:
    print(*row)
# 0 25 50 75 100 125 150 175 200
# 200 175 150 125 100 75 50 25 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.