draw rectangle with hastags and ask again

Asked

Viewed 282 times

1

Hello, I’m trying to make this code work as follows: you say the width and height and then it completes with the proper "#" and then it would ask again and continue like this until the person closes the program.

However, a small error occurs when finishing the "#" drawing. It occurs that there is one more # between the shown figure and the next question. I took a test and found out that if I take the "=" of line 9 em coluna<=altura the error stops existing but the question that should be asked next does not occur. would someone please explain to me?

def retangulo(x,y):
  linha=1
  coluna=1

  while coluna<=altura:#4
    while linha<=largura:#3
      print("#",end=" ")
      linha = linha +1
    if coluna<=altura:
      print()
      linha=2
      print("#",end=" ")
      coluna = coluna + 1

largura = int(input("coloque a largura: "))
altura = int(input("Coloque a altura: "))

while largura>0 or altura>0:
  if retangulo(largura,altura):
    print(retangulo(largura,altura))
  print()
  print()
  largura = int(input("coloque a largura: "))
  altura = int(input("Coloque a altura: "))

1 answer

0

Because your code works cyclically (asks for the height and width of a rectangle and prints it endlessly), you can simply start a loop while True, that will keep repeating itself endlessly.

In this loop, you will ask the user for the width and height of the rectangle that will be shown, and then call the function retangulo(largura, altura) created by you, which takes as parameters the width and height of the rectangle to be printed.

In this capacity retangulo(largura, altura), we will print # 'width' times. For example, if the width is 5, we will print # # # # #. But within a loop of repetition for, which will determine the amount of times that line will be printed, which is the number of lines (height) of the rectangle, according to the code below.

def retangulo(largura, altura): # Função que recebe como parâmetros a largura e a altura do retângulo a ser impresso.
    for _ in range(altura): # Inicia-se um laço que repetição, que imprimirá uma linha 'altura' vezes.
        print('# ' * largura) # A linha a ser impressa é a string '# ' repetida 'largura' vezes. Podemos fazer isso apenas multiplicando a string pelo valor desejado.

while True: # O laço while True repetirá o código abaixo infinitamente.
    largura = int(input("\nColoque a largura: "))
    altura = int(input("Coloque a altura: "))
    retangulo(largura, altura)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.