简体   繁体   中英

I need to do an n x n block in Python to display "*" for that block

size = int(input("please enter an integer:"))
for row in range(size*1):
    print("*", end="")
print()
for column in range(1* size):
    print("*", end="")
print()

This is my code so far and I need it to print: for 2

**
**

and for 7

*******
*******
*******
*******
*******
*******
*******

I have gotten it to print

**
**

for 2 but for 7 I just get

*******
*******

The natural way to write this in many languages would use a nested loop. However, it is much easier in Python:

for i in range(size):
    print('*' * size)

You need to nest the for loops since you want the number of lines to be equal to the number of columns:

size = int(input("please enter an integer:"))
for row in range(size):
    for col in range(size):
        print('*', end="")
    print()

PS: You don't really have to mulitply by 1 in range .

You need to nest the two loops to achieve what you desire.

You can do it the following three lines with two tricks:

  • You can generate a string of n '*' with the command "*" * size , therefore you need a single loop
  • The for loop does not need an index, that is not used, so you can use _

The code looks like this:

size = int(input("please enter an integer:"))
for _ in range(size):
    print("*" * size)

Another way is to simply multiply strings - no loops:


size = int(input("please enter an integer:"))
print((('*'*size)+'\n')*size)

enjoy :D :D :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM