azaz azaz - 5 months ago 15
Python Question

What is the logical error in the for loop?

This is the question:


Use the debugging tool, IDLE Debugger to correct a logical error in a
Python program. The program should generate a pattern of rows of
asterisks in even columns and dollars in odd columns, where the number
of row and column is input by the user. The expected output is:

asterickdollar


So where the error at? I couldnt figure it out the logical error.
The code is:

row = col = int(input("Enter number of row and column: "))
for row in range(row):
for col in range(col):
if row % 2 == 0 and col % 2 == 1:
print('*', end='')
elif row % 2 == 1 and col % 2 == 0:
print('$', end='')
else:
print(' ', end='')

print()


For the above code output

Answer

You should store the number the user inputs in a different variable than the ones you use to iterate. This worked:

num = int(input("Enter number of row and column: "))
for row in range(num):
    for col in range(num):
        if row % 2 == 0 and col % 2 == 1:
            print('*', end='')
        elif row % 2 == 1 and col % 2 == 0:
            print('$', end='')
        else:
            print(' ', end='')

    print()