-2
#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....

TahaAvadi
  • 11
  • 2

5 Answers5

0
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
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
0
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))
sat
  • 91
  • 8
0
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.

9001_db
  • 81
  • 10
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 04 '22 at 16:14
0

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
user99999
  • 310
  • 1
  • 13
-1

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
caf9
  • 19
  • 6