Python Nested Loops To Print Rectangle With Asterisks

Question:

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!

Answers:

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.

Answered By: mhawke

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('')
Answered By: CodrinC

If you remove the
num_rows = 2
num_cols = 3
It will limit it to the correct variables if you are using zybooks

Answered By: Lauren W

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()
Answered By: Zybooks Guy

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()
Answered By: Terrence Alexander

Try this:

num_rows = int(input())
num_cols = int(input())

for i in range(num_rows):
print(‘‘, end=’ ‘)
for j in range(num_cols-1):
i
=j
print(‘*’, end=’ ‘)
print()

Answered By: user19583617
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.