t = int(input())
for _ in range(t):
n = input()
for i in range(len(n)):
first = n[:i]
second = n[i:]
print(type(first))
print(type(int(first)))
Why I am getting ValueError: invalid literal for int() with base 10: ''
Output: output
CodePudding user response:
ValueError: invalid literal for int() with base 10: ''
As the error says, you entered an empty value (''
), that the built-in function int
isn't able to convert.
If you want to check if t
is acceptable (an integer) you can use .isdigit
:
>>> '1'.isdigit()
True
>>> ''.isdigit()
False
>>> 'Hello1'.isdigit()
False
Or maybe use a try
/except
block:
try:
t = int(input())
except ValueError:
print("Error, your input wasn't a number")
As your screenshot shows, the error gets raised at:
print(type(int(first)))
but the reason is the same, you can solve it with the try
/except
block above.
try:
print(type(int(first)))
except ValueError:
pass # Simply do nothing, since an empty element of n was reached
CodePudding user response:
For purposes of debugging, let's just focus on a single iteration and assign a reasonable value to n
that represents the sort of thing you expect the user to input()
. (When people ask you for an "MRE", this is the type of thing they mean -- a small piece of code that you can run to immediately demonstrate the problem.)
n = "12345"
for i in range(len(n)):
first = n[:i]
second = n[i:]
print(type(first))
print(type(int(first)))
It breaks here:
print(type(int(first)))
ValueError: invalid literal for int() with base 10: ''
Why is that? Well, let's do a little more printing:
print(f"first = n[:{i}] = {repr(first)}")
gets us:
first = n[:0] = ''
And indeed, the slice n[:0]
is an empty string, which you can't convert to an int
. What you probably want to do is reduce your range
so that it starts at 1 instead of 0:
n = "12345"
for i in range(1, len(n)):
first = n[:i]
second = n[i:]
print(f"first = n[:{i}] = {repr(first)}")
print(f"second = n[{i}:] = {repr(second)}")
prints:
first = n[:1] = '1'
second = n[1:] = '2345'
first = n[:2] = '12'
second = n[2:] = '345'
first = n[:3] = '123'
second = n[3:] = '45'
first = n[:4] = '1234'
second = n[4:] = '5'