pythonpython-3.xloopswhile-loop

Hackerrank doesn't accept my code. Why?


So the task is to read an integer N For all non-negative integers I < N, print The output format should print N lines, one corresponding to each i.

For example, the user input is 5 so the output should be... 0 1 4 9 16

Here is my solution.

# The first two lines of code were default and already there.
if __name__ == '__main__':
    n = int(input())

# Everything below is my code.
for i in range(0,5):
    while i < 5:
        print(i ** 2)
        i += 1
        break

So although this works in Python 3.7, it does not work in Hackerrank because if you were to input an number higher than 5, let's say 7, Hackerrank would output... 0 1 4 9 16 25 36

Python would've just stopped after outputting the number 16.

How can I fix this in Hackerrank? Here is the link if you want to see the problem yourself. https://www.hackerrank.com/challenges/python-loops/problem


Solution

  • Firstly, You should not write in range(0,5) if you want to iterate through n numbers.

    Secondly, You do not need to write another while function. You use for loop or while loop for this question.

    Change

    for i in range(0,5):
        while i < 5:
            print(i ** 2)
            i += 1
            break
    

    to

    for i in range(0,n):
        print(i ** 2)