Python script that generates a main diagonal character square

Asked

Viewed 88 times

1

I am trying to make a program that given a value, generates a "square" of n rows and n columns that has characters : in the main diagonal positions and the characters + in other positions.

For example, n = 5:

:++++
+:+++
++:++
+++:+
++++:

The logic is correct, however, I’m having trouble formatting the square. Can someone please help me?

n = 0
i = 0
j = 0

n = int(input("Digite um número: "))

if n > 0:
    print("Desenho")
    for i in range(1, n):
        for j in range(1, n):
            if i != j:
                print("+", end="")
            else:
                print(":", end="")
                print()
else:
    print("Numero menor ou igual a zero, programa abortado!")

1 answer

1


The print() that makes the line break should be outside the else - in fact it must be outside the for internal also, as you should only change line after you have printed all of her characters.

In addition, a range does not include the final value, so range(1, n) goes from 1 to n - 1, ie the loop will make one iteration less. In this case, just omit the first parameter, doing only range(n), that the start will be zero:

n = int(input("Digite um número: "))
if n > 0:
    print("Desenho")
    for i in range(n):
        for j in range(n):
            if i != j:
                print("+", end="")
            else:
                print(":", end="")
        print() # fora do else, dentro do for externo 

Also note that you do not need to declare all variables at the beginning, assigning any value that will be dropped right away. Create them only when you need them.

  • It worked fine, thank you very much!!!

  • @Matheusguerreiro If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in response if it has found it useful

Browser other questions tagged

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