#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....
CodePudding user response:
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))
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
ri = input("please enter some digits")
if ri.isnumeric() == True:
print("Digit sum: " str(sum([int(x) for x in ri])))
else:
raise ValueError("That was no valid number!")
For this solution, the length of the input does not matter.
CodePudding user response:
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