Python Forum
Sum of digit in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum of digit in a string
#1
I am right now a gr.10 student who is studying basic computer programming, my assignment had the following description: e a program that asks the user to enter a series of single-digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of 2, 5, 1, and 4, and here is what I had come up with:

def value(string):    
    count = 0

    for num in str(string)[0:]:
        if num.isdigit() and int(num) in range(10):
            count += int(num)

    return count


def main():
    user_input_string = input('Enter a string of single digit number: ')
    
print('That string has a total value of: ' + str(value(user_input_string)) + '.')


main()
    
can you pls help me as soon as possible and figure out how to write a proper code in order to enter one digit at a time

(I will add that this is python 3)
Reply
#2
As a helper, you can access the characters in a string using:
>>> num = '123456'
>>> for dig in num:
...     print(int(dig))
...
1
2
3
4
5
6
>>>
also, can add:
>>> sum = 0
>>> for dig in num:
...     sum += int(dig)
...
>>> sum
21
>>>   
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list digit into number Voldyy 2 1,540 Jul-10-2022, 06:13 PM
Last Post: deanhystad
  Frequency in first digit from csv file, NO IMPORT bryan0901 6 2,838 May-28-2020, 09:50 AM
Last Post: bryan0901
  Four-digit number text translation. soz 3 2,689 May-13-2019, 03:02 PM
Last Post: buran
  create three digit numbers Krszt 4 4,488 Dec-09-2018, 03:12 PM
Last Post: ThePhi
  Allow only digit penoxcz 3 3,802 Nov-14-2017, 03:04 PM
Last Post: wavic
  Four digit combinations EHod 4 7,786 Aug-13-2017, 09:14 PM
Last Post: EHod
  create a 20 digit string, and cast to a list then add all the digits as integers nikhilkumar 2 6,386 Jul-19-2017, 04:53 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020