Hi in this article you will learn about a python script to calculate Two things first is sum of digits of numbers and next is to calculate the reverse of a number.
I will be performing modulus, addition and division of the given number by 10 in order to get the last digit of the number and keep adding it to the sum and reverse variable.
Let's use the while loop to calculate the sum and reverse of a number.
Write A Python Script To Display The Sum And Reverse Of The Given Number
Take a variable name number and ask a user to enter a number using the input function call convert it into an integer. Take to more variables named as total and reverse, total is used to store the sum of all the digits of a number, reverse is used to store the reverse of a number
number = int(input("Enter a Number : "))
total = 0
reverse = 0
Use the while loop until the number becomes 0, try to get the last digit of a number by modulating it with 10.
To find the sum of digits just at the last digit to the total
To find the reverse of the number multiply the reverse variable by 10 and add the last digit
Now take out the last digit from the number by performing that true division by 10
while number != 0:
last_digit = number % 10
total = total + last_digit
reverse = reverse * 10 + last_digit
number = number // 10
Use the print function call to print the sum of the digits of a number, again use the print function called to bring the reverse of a number.
print("sum of digits of number is : ", total)
print("reverse of number is : ", reverse)
Complete Python Program
==========================
number = int(input("Enter a Number : "))
total = 0
reverse = 0
while number != 0:
last_digit = number % 10
total = total + last_digit
reverse = reverse * 10 + last_digit
number = number // 10
print("sum of digits of number is : ", total)
print("reverse of number is : ", reverse)
Output 1
===============
Enter a Number : 13579
sum of digits of number is : 25
reverse of number is : 97531
Output 2
==============
Enter a Number : 12345
sum of digits of number is : 15
reverse of number is : 54321
Output 3
==============
Enter a Number : 99998
sum of digits of number is : 44
reverse of number is : 89999
Conclusion
===================
The script users input function called to ask the user to enter the number. It will use a looping construct to iterate all the digits of a number. Also the script uses print function call to print the some and reverse of a number to standard output
The above python script will use a while loop to iterate all the digits present in the number and perform Modulus Addition and Division (MAD) to get the sum and reverse of a number.
Execute the above python script by providing a random integer as the input to the Python program.
Comment it down below if you have any queries regarding the above python script.
0 Comments