Home > Software engineering >  Can anyone explain why this code on python is not working?
Can anyone explain why this code on python is not working?

Time:12-03

def n(a):
    a = str(a)
    if "0" in a:
        b = str((a).replace("0", ''))
        a = b[::-1]
        a = a[::-1]
        a = int(a)
        return a
    else:
        a = a[::-1]
        a = a[::-1]
        a = int(a)
        return a 


N = int(input())
des = 10**9   7
summa = 0

for a in range():
    print(n(a))
    b = n(a)
    summa = summa   b
    summa = summa % des
    print(summa)

gives such an error : 'invalid literal for int() with base 10: '' '

If I pass the value to the variable a without the for i in loop, then everything works

I just need to understand what is wrong with the code. I'm new to programming and can't figure it out right away

CodePudding user response:

The input function waits for user input. If none is given, it will return an empty string, i.e., ''. As a result, you are casting '' to an integer. This is not possible and results in the error you mention.

int('')` # returns `ValueError: invalid literal for int() with base 10: ''

You can also see this already in the end of the error. That's what the '' mean at the end of the error. That's what being passed to int()

I'm guesting that you might be copy-pasting the code above directly into a terminal. This results in Python not waiting for any actual input for input.

If you first only run this line

N = int(input())

and then hit enter, it will wait for user input. Then you can copy the rest of the code. The rest of the code also contains some issues. Specifically, range should have some input, like range(N)

CodePudding user response:

The error you are seeing is because you are trying to convert an empty string to an integer using the int() function. This error is happening because you are using a range() function with no arguments in the for loop, which will create an empty range and cause the for loop to not execute at all.

To fix this error, you need to pass the correct arguments to the range() function in the for loop.

  • Related