Reputation: 11
I am having trouble solving the following question:
Write a program that draws “modular rectangles” like the ones below. The user specifies the width and height of the rectangle, and the entries start at 0 and increase typewriter fashion from left to right and top to bottom, but are all done mod 10. Example: Below are examples of a 3 x 5 rectangular:
The following code is what I have tried to solve the problem: I know it's bad but I still don't know how to print the 5 till 9 numbers on top of each other.
width = int(input("Enter the width of the rectangle:"))
height = int(input("Enter the height of the rectangle:"))
for x in range(0, width, 1):
for y in range(0, height, 1):
print(y, end = ' ')
print()
Thank you all in advance.
Upvotes: 0
Views: 2476
Reputation: 147166
You're on the right track, but you have a few issues. Firstly you need to iterate y
before x
, since you process the columns for each row, not rows for each column. Secondly, you need to compute how many values you have output, which you can do with (y*width+x)
. To output a single digit, take that value modulo 10. Finally range(0, width, 1)
is just the same as range(width)
. Putting it all together:
width = 5
height = 3
for y in range(height):
for x in range(width):
print((y*width+x)%10, end=' ')
print()
Output:
0 1 2 3 4
5 6 7 8 9
0 1 2 3 4
Upvotes: 1