Sum of 21 and 62 in python

Last update on August 19 2022 21:50:47 [UTC/GMT +8 hours]

Python String: Exercise-62 with Solution

Write a Python program to compute sum of digits of a given string.

Sample Solution:-

Python Code:

def sum_digits_string[str1]:
    sum_digit = 0
    for x in str1:
        if x.isdigit[] == True:
            z = int[x]
            sum_digit = sum_digit + z

    return sum_digit
     
print[sum_digits_string["123abcd45"]]
print[sum_digits_string["abcd1234"]]

Sample Output:

15
10

Pictorial Presentation:

Flowchart:


Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code [and comments] through Disqus.

Previous: Write a Python program to remove duplicate characters of a given string.
Next: Write a Python program to remove leading zeros from an IP address.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Python: Tips of the Day

Summing a sequence of numbers [calculating the sum of zero to ten with skips]:

>>> l = range[0,10,2]
>>> sum[l]
20

  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation

In the program below, we've used an if...else statement in combination with a while loop to calculate the sum of natural numbers up to num.

Source Code

# Sum of natural numbers up to num

num = 16

if num < 0:
   print["Enter a positive number"]
else:
   sum = 0
   # use while loop to iterate until zero
   while[num > 0]:
       sum += num
       num -= 1
   print["The sum is", sum]

Output

The sum is 136

Note: To test the program for a different number, change the value of num.

Initially, the sum is initialized to 0. And, the number is stored in variable num.

Then, we used the while loop to iterate until num becomes zero. In each iteration of the loop, we have added the num to sum and the value of num is decreased by 1.

We could have solved the above problem without using a loop by using the following formula.

n*[n+1]/2

For example, if n = 16, the sum would be [16*17]/2 = 136.

Your turn: Modify the above program to find the sum of natural numbers using the formula below.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a number and the task is to find sum of digits of this number in Python. 
    Examples: 
     

    Input : n = 87 
    Output : 15 
    Input : n = 111 
    Output : 3

     
    Below are the methods to sum of the digits. 
    Method-1: Using str[] and int[] methods.: The str[] method is used to convert the number to string. The int[] method is used to convert the string digit to an integer. 

    Convert the number to string and iterate over each digit in the string and after converting each digit to integer and add to the sum of the digits in each iteration. 

    Python3

    def getSum[n]:

        sum = 0

        for digit in str[n]: 

          sum += int[digit]      

        return sum

    n = 12345

    print[getSum[n]]

    Output:

    15

    Method-2: Using sum[] methods.: The sum[] method is used to sum of numbers in the list.

    Convert the number to string using str[] and strip the string and convert to list of number using strip[] and map[] method resp. Then find the sum using the sum[] method.

    Python3

    def getSum[n]:

        strr = str[n]

        list_of_number = list[map[int, strr.strip[]]]

        return sum[list_of_number]

    n = 12345

    print[getSum[n]]

    Output:

    15

    Method-3: Using General Approach: 

    • Get the number
    • Declare a variable to store the sum and set it to 0
    • Repeat the next two steps till the number is not 0
    • Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
    • Divide the number by 10 with help of ‘//’ operator
    • Print or return the sum

    A. Iterative Approach:

    Python3

    def getSum[n]:

        sum = 0

        while [n != 0]:

            sum = sum + [n % 10]

            n = n//10

        return sum

    n = 12345

    print[getSum[n]]

    Output:

    15

    B. Recursive Approach:

    Python3

    def sumDigits[no]:

        return 0 if no == 0 else int[no % 10] + sumDigits[int[no / 10]] 

    n = 12345

    print[sumDigits[n]]

    Output:

    15

    How do you sum a number in Python?

    sum[] function in Python Python provides an inbuilt function sum[] which sums up the numbers in the list. Syntax: sum[iterable, start] iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

    How do you find the sum of two numbers in Python?

    How to Add Two Numbers in Python.
    ❮ Previous Next ❯.
    Example. x = 5. y = 10. print[x + y] Try it Yourself ».
    Example. x = input["Type a number: "] y = input["Type another number: "] sum = int[x] + int[y] print["The sum is: ", sum] Try it Yourself ».
    ❮ Previous Next ❯.

    How do you add numbers from 1 to 50 in Python?

    Sum=0#variable which holds the sum value. for x in range[1,51]:#For loop which runs from 1 to 50 and access the number. Sum=Sum+x# It add the number. print["The Sum of 1 to 50 number is: ",Sum]#It will prints the sum value of all the numbers.

    How do you find the sum of numbers from 1 to 100 in Python?

    The sum function can be used to calculate the sum of the numbers in the range..
    Pass 1 and 100 + 1 to the range class, e.g. range[1, 100 + 1] ..
    Pass the range object to the sum[] function..
    The sum function will sum the integers from 1 to 100..

    Chủ Đề