Python Program to Get Sum of digits of a Number codigence

Python Program to Get Sum of digits of a Number codigence


Python Program to Get Sum of digits of a Number codigence

  • Python Program to get Sum of digits of a Number using For Loop.
  • Sum of digits Number in Python using While Loop.

Overview of Sum of digits Number in Python

Sum of digits of a number is the simply the digits sum of the number.For Example Sum of digits of 12345 id 15.

Python Program to get Sum of digits of a Number using For Loop

  • Define a function to get Sum of digits.
  • Let's have a function named 'sum_of_digits' and take the argument 'no' for number to get sum of digits.
  • Now Inside the Function,
  • copy the value of no into a temporary variable,say dup_no.
  • Now initialize a variable,say 'sum' to zero.This will store the Sum of digits of the number.
  • Using for loop get the Sum of digits of number.
  • Call the function to get sum of digits and print the Final results.
python
#python program to get digit sum #using for loop def sum_of_digits(no: int): dup_no = no sum = 0 for i in range(len(str(no))): digit = dup_no % 10 sum+=digit dup_no//=10 return sum print(f"sum of digits of 12345 = {sum_of_digits(12345)}")

Output

plaintext
sum of digits of 12345 = 15

Python Program to get Sum of digits Number using While Loop

  • Define a function to get Sum of digits.
  • Let's have a function named 'sum_of_digits' and take the argument 'no' for number to get sum of digits.
  • Now Inside the Function,
  • copy the value of no into a temporary variable,say dup_no.
  • Now initialize a variable,say 'rev_no' to zero.This will store the Sum of digits of the number.
  • Using while loop get the Sum of digits of number.
  • Call the function to get sum of digits and print the Final results.
python
#using while loop def sum_of_digits(no: int): dup_no = no sum = 0 while dup_no != 0: digit = dup_no % 10 sum+=digit dup_no//=10 return sum print(f"sum of digits of 12345 = {sum_of_digits(12345)}")

Output

plaintext
sum of digits of 12345 = 15

Conclusion

Python allows us to calculate Sum of digits of a number quickly and effectively through its multiple features.