long = int(input("longueur : "))
larg = int(input("largeur : "))
for i in range(larg):
if i == 0 or i == larg - 1:
for j in range(long):
print("* ", end="")
print()
else:
for j in range(long):
if j == 0 or j == long - 1:
print("* ", end="")
else:
print(end=" ")
print()
I was trying to achieve a rectangle shape through symbols .
I started learning Python recently and I'm searching for a faster/cleaner way to do this .
the output requested is:
* * * *
* *
* * * *
CodePudding user response:
Here is a clean and simple approach...
length = int(input("length: "))
width = int(input("width: "))
for i in range(length):
print("* " * width)
CodePudding user response:
Well, you could use multiply with your multiplication signs:
rows = 3
columns = 5
print(('* ' * columns '\n') * rows, end = '')
Output:
* * * * *
* * * * *
* * * * *
If you want to print a hollow rectangle, it's a little more complicated as you need different rows in the middle. For example:
for r in range(rows):
if r == 0 or r == rows - 1:
print('* ' * columns)
else:
print('* ' ' ' * (columns - 2) '* ')
Output:
* * * * *
* *
* * * * *
CodePudding user response:
You can try the good old basic for loop
rows = 3
columns = 3
for i in range(rows):
for j in range(columns):
print('*', end=' ')
print()
will give
* * *
* * *
* * *
as per your updated question for hollow
for i in range(1, rows 1):
for j in range(1, columns 1):
if i == 1 or i == rows or j == 1 or j == columns:
print("*", end=" ")
else:
print(" ", end=" ")
print()
will give
* * *
* *
* * *
CodePudding user response:
You need to use a loop to iterate through each row. If the row is first or last then fill it with column * '*'
. If the row is the middle one then add an '*'
, fill with appropriate spaces and finally add an '*'
.
Here's how you can do it:
long = int(input("longueur : "))
larg = int(input("largeur : "))
for i in range(long):
if (i == 0) or (i == long - 1): # Checking if it is first or last row
print('* ' * larg) # Printing entire row without gap
else: # For middle rows
print('* ' ' ' *(larg - 2) '*') # Printing middle rows with gap in between.
Output:
longueur : 3
largeur : 4
* * * *
* *
* * * *
longueur : 4
largeur : 7
* * * * * * *
* *
* *
* * * * * * *