'Python Nested Loops To Print Rectangle With Asterisks
Write nested loops to print a rectangle. Sample output for given program:
3 stars : ***
3 stars : ***
I tried it and ended up with this:
num_rows = 2
num_cols = 3
'''IDK WHAT TO PUT HERE'''
print('*', end=' ')
print('')
Any help would be appreciated! Thanks!
Solution 1:[1]
Here you go! Try this!
num_rows = 2
num_cols = 3
for i in range(num_rows):
print('*', end=' ')
for j in range(num_cols-1):
i*=j
print('*', end=' ')
print('')
Solution 2:[2]
You're trying to learn, I think, so a here is a hint to push you in the right direction.
You need to use a nested for
loop. Use the range()
builtin to produce an iterable sequence.
The outer for loop should iterate over the number of rows. The inner (nested) for loop should iterate over the columns.
Solution 3:[3]
Sorry for resurrecting this thread, but i'm going through the same Zybooks course and the answer is actually a lot simpler than what was voted correct here.
num_rows = 2
num_cols = 3
for i in range(num_rows):
for i in range(num_cols):
print('*', end=' ')
print()
Solution 4:[4]
If you remove the num_rows = 2 num_cols = 3 It will limit it to the correct variables if you are using zybooks
Solution 5:[5]
I just recently came across this in a exam I had, here is another way.
for i in range(0,9,1):
for i in range(0,21,1):
print('X', end='')
print()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CodrinC |
Solution 2 | mhawke |
Solution 3 | Zybooks Guy |
Solution 4 | Lauren W |
Solution 5 | Terrence Alexander |