I am trying to create a simple program that reads a string of 4 digits, makes sure it is indeed 4 digits, makes sure there are no non-digits, then separates the first two digits from the last two and adds them together. I can make it all work but I still got this error:
ValueError: invalid literal for int() with base 10:
This only happens when I try a string such as ‘456f’.
What can I change to fix this?
Code:
s = input('please type a 4-digit integer \n')
valid = True
for c in s:
if len(s)!= 4:
valid = False
if not c.isdigit():
print (c, 'is not a valid input')
number = int(s)
firstOne = number // 100
secondOne = number % 100
sum = firstOne + secondOne
x = '/'
if valid == True:
print('your integer is ' + str(number), x, 'first two digits are ' + str(firstOne), x, 'second two digits are ' + str(secondOne), x, 'sum of two new numbers is ' + str(sum))
else:
print(len(s), 'is an invalid amount of digits')
Let’s focus on this code:
The first thing to say is that the
len()check should be moved outside the character loop.The next comment to make is that whilst you are detecting non-digits, you continue executing code as if nothing is wrong. You presumably intend to set
validtoFalse.Now, the main part of the problem. You need to skip the conversion to
intwhen invalid input is detected.If you want to continue with such an approach your code would look like this:
Having said all of that, I’d probably reorganise the code quite a bit to deal with the errors as soon as they are detected. Code is much easier to understand if you can organise your error handling that way.
Now, that’s a start in the right direction, but you can continue in this vein making the code better and better. Sven’s answer gives you an excellent illustration of where such a process would ultimately lead.