Workaround
As commented, a simpler solution is to use the multiplication of strings in Python:
# Lê o tamanho do retângulo:
largura = int(input("digite a largura:"))
altura = int(input("digite a altura:"))
# Imprime a borda superior:
print('#' * largura)
# Imprime bordas laterais:
for _ in range(altura-2):
print('#' + ' ' * (largura-2) + '#')
# Imprime borda inferior:
print('#' * largura)
Running the program:
>>> digite a largura: 10
>>> digite a altura: 5
##########
# #
# #
# #
##########
See working on Repl.it.
Your solution
I analyzed your code and the main problem is that you change the value of altura
to walk the lines. This makes your logic much more complex than it needs to be, as the program won’t know what the original rectangle height is. To get around this, control the line to be displayed with another variable.
# Aqui substitui de linha para largura:
largura = int(input("digite a largura:"))
altura = int(input("digite a altura:"))
# Defini a variável linha para controlar a linha a ser exibida
linha = 1
# Enquanto houver linha a ser exibida:
while linha <= altura:
print("#", end = "")
coluna = 2
# Substituído linha por largura também
while coluna < largura:
# Se for a primeira linha, a última ou a última coluna
if linha == 1 or linha == altura or coluna == largura:
print("#",end="")
else:
print(end = " ")
coluna = coluna + 1
print("#")
# Incrementa a variável linha ao invés de decrementar altura
linha = linha + 1
Note that, thus, the variable altura
remains unchanged and therefore its original reference is not lost. Running the program:
>>> digite a largura: 10
>>> digite a altura: 5
##########
# #
# #
# #
##########
You have the expected exit.
See working on Repl.it.
Being Python, look for solutions pythonic. Tip: Do
'#' * 10
returns to string##########
and make'#' + '_' * 8 + '#'
returns#________#
(replaces the white space with_
because of the formatting here of the comment). This would greatly decrease the complexity of your program.– Woss
I understand... but I need to automate for any width and height.
– Marcos Vinicius