3loosh
3loosh

Reputation: 21

For loop a square pattern of numbers

In this question I had to create a program that prompts the user for a number and then prompt again for how many rows to create. Something like:

1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4

This is what I came up with and I have tried many different ways to get the same result but it didn't work.

num=int(input("Enter a number between 1 and 10: "))
rows=int(input("Enter how many rows to of numbers: "))
for i in range(num):
    print(i,end=" ")
for x in range(rows):
    print (x)

This is the output I came up with:

Enter a number between 1 and 10: 6
Enter how many rows to of numbers: 4
0 1 2 3 4 5 0
1
2
3

Upvotes: 0

Views: 2965

Answers (3)

toto p
toto p

Reputation: 1

rows = 5
side = int(input("Please Enter any Side of a Square  : "))
for i in range(side):
    for j in range(side):
        if(i == 0 or i == side - 1 or j == 0 or j == side - 1):
            print(i, end = '  ')
        else:
            print(i, end = '  ')
    print()

Upvotes: 0

Jonas
Jonas

Reputation: 1593

Simple solution: Just use nested for loops:

num = int(input("Enter a number between 1 and 10: "))
rows = int(input("Enter how many rows to of numbers: "))
for i in range(num):
    print ('\n')
    for x in range(rows):
        print (i + 1)

The code above will go through the range 0 to num, printing first a new line and then printing the current number rows times.

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

You may simply do it like:

num = 5
rows = 4
for i in range(1, num+1):
    print('{} '.format(i) * rows)

Output:

1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 
5 5 5 5 

Explanation: When you multiply a str with some number say n, new string is returned with original string repeated n times. Doing this you will eliminate your nested loop

Upvotes: 1

Related Questions