Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Sum of digits with average

Hello everyone i am a new to programming and i have a small problem in the code, i need to get the average of the sum i already made the sum of digits and here is the code:

num = int(input("Enter a number\n"))
r = 0
m = 0
while num != 0:
    m = num % 10
    r = r + m
    num = int(num / 10)
print(f"The sum of all digits is {result} and the average is")

i need the average but i dont know how to get it( for example in the num i added 5555, 5+5+5+5 = 20) how would i get the average and thanks

i tried to do r / m but also didnt work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is the short solution:

num = input("Enter a number\n")
s = sum([int(x) for x in num])
a = s / len(num)

print(f"The sum of all digits is {s} and the average is {a}")

Also, this is the fixed version of your code:

num = int(input("Enter a number\n"))
r = 0
m = 0
t = 0
while num != 0:
    m = num % 10
    r = r + m
    num = int(num / 10)
    t = t + 1
print(f"The sum of all digits is {r} and the average is {r/t}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading