Draw a rectangle using repetition structures in Python

4

I have to solve the following Python activity:

I need to write a program that prints a rectangle with full borders and half open:

>>> digite a largura: 10
>>> digite a altura: 3
##########
#        #
##########

But my program is doing like this:

>>> digite a largura: 10
>>> digite a altura: 3
#        #
#        #
##########

How to fix?

My code:

linha = int(input("digite a largura:"))
altura = int(input("digite a altura:"))

while  altura > 0:
   print("#", end = "")
   coluna = 2
   while coluna < linha: 
    if altura == 1 or coluna == linha:
        print("#",end="")
    else:
        print(end = " ")
    coluna = coluna + 1
   print("#")
   altura = altura - 1
    
asked by anonymous 20.04.2017 / 23:40

2 answers

3

Workaround

As discussed, a simpler solution is to use the strings multiplication 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 at Repl.it .

Your solution

I've looked at your code, and the main problem is that you change the value of altura to scroll the lines. This leaves your logic far more complex than it needs to be, because the program will not know the original height of the rectangle. To work 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

Notice that, therefore, the altura variable remains unchanged, so its original reference is not lost. Running the program:

>>> digite a largura: 10
>>> digite a altura: 5
##########
#        #
#        #
#        #
##########

You have the expected output.

See working at Repl.it .

    
21.04.2017 / 00:06
-1

Be a = height and w = width:

print(w*"#" + "\n"                                        #####
    + (a-2)*("#" + (w-2)*" " + "#\n")                     #   #   
    + w*"#")                                              #####
    
13.09.2017 / 18:10