0
Summing digit
n = str(input()) x=len(n) length =0 while x >0: y = n[x-1] length+=int(y) x-=1 print(length)
3 Antworten
+ 1
Hey Ammar,
If you would like to sum multiple digits from input, you can try the following:
user_input = input() # Take an input from the user
print(sum([int(x) for x in user_input.split(",")])) # print the Sum
Example input: 1, 2, 3, 4, 5
Example output: 15
In case you're not aware of what list comprehension is you can check out this article:
https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/python_lists_comprehension.asp
To make it more beginner-friendly, I will use for loop instead of list comprehension:
user_input = input()
result = 0
for digit in user_input.split(","): # Loops through the numbers
result += int(digit) # Add the digits to the result
print(result)
+ 2
Ammar Saleh Goli I understood that your code take the input exp: 45 and output 4+5=9 but the question title mislead me .
0
Hi guys, I just left the code to see if the same result can be achieved in another way.