Search code examples
pythonfor-loopnested-loops

Printing a X using * in Python


I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *

I have been experimenting over the past couple days and have had little success. This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing.

num=int(input("Please type in an odd integer.")) if num%2==0: print("Your number is incorrect")


Solution

  • This should do it:

    Python 2

    N = 5
    
    for i in range(N):
        for j in range(N):
            if (i == j) or ((N - j -1) == i):
                print '*',
            else:
                print ' ',
        print ''
    

    Python 3

    N = 5
    
    for i in range(N):
        for j in range(N):
            if (i == j) or ((N - j -1) == i):
                print('*', end = '')
            else:
                print(' ', end = '')
        print('')
    

    (thanks to Blckknght for Python 3 knowledge)

    You're looping through all the rows in the outer loop, then all the columns or cells in the inner. The if clause checks whether you're on a diagonal. The comma after the print statement ensures you don't get a new line every print. The 3rd print gives you a new line once you're finished with that row.

    If this is helpful / works for you; try making a Y using the same approach and post your code in the comments below. That way you could develop your understanding a bit more.