sum up a numeric string (1111 = 1+1+1+1=4)

Question:

#Develop a program that reads a four-digit integer from the user and displays the sum of the digits in the number. For example, if the user enters 3141 then your program should display 3+1+4+1=9.

ri = input("please enter four digits")
if len(ri) == 4 and ri.isnumeric() == True:
    print(ri[0]+ri[1]+ri[2]+ri[3])
else:
    print("Error: should be four digits!")

How do I do this? Haven’t seen something like this before I’m sure, and as you can see my code fails….

Asked By: TahaAvadi

||

Answers:

Edit for better answer

input_string = input("Enter numbers")
output_string = ""
sum = 0
count = 0
for n in input_string:
    if count < len(input_string)-1:
        output_string += str(n) + "+"
    else:
        output_string += str(n) + "="
    sum += int(n)
    count += 1
output_string += str(sum)

print (output_string)

Output:

1+1+1+1=4
Answered By: caf9
ri = input("please enter four digits: ")
if len(ri) == 4 and ri.isnumeric():
    print(f'{ri}={"+".join(ri)}={sum(map(int, ri))}')
else:
    print("Error: should be four digits!")
please enter four digits: 3141
3141=3+1+4+1=9
Answered By: Алексей Р
ri = input("please enter four digits: ")
res = 0
for n in ri:
    res += int(n)
print (ri[0]+"+"+ri[1]+"+"+ri[2]+"+"+ri[3]+"="+str(res))
Answered By: sat
ri = input("please enter some digits: ")
try:
    print("Digit sum: " + str(sum([int(x) for x in ri])))
except:
    raise ValueError("That was no valid number!")

For this solution, the length of the input does not matter.

Answered By: 9001_db

Here is a one-liner for that. The length of the input doesn’t matter to this one. Its up to you what to specify for the length or to take the length check away completely.

ri = input('please enter four digits:')
if len(ri) == 4 and ri.isnumeric():
    print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))
else:
    print('Error: should be four digits')

Output:

please enter four digits: 3149
3+1+4+9 = 17
Answered By: user99999