In this simple python program, we have to reverse a number. It is a beginner-level python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this simple python program, we need to reverse a number. Reversing a number means we are printing the number in reverse order. For example, if we have a number 12345, we have to print that as 54321 using python.
To solve this beginner python problem on a number, we are using the Mod operator by 10 to take the last digit of the number. Then we calculate the reverse by taking the reverse variable * 10 + the digit that we extracted from the previous step. Finally, divide the number by 10 removing the last digit, and take the next digit in the next iteration of the
while loop. The while loop in python will continue until the number is equal to zero. Then print the number using
STEP 1: Enter the number using the input method and convert that string to an integer using the python programming language.
STEP 2: Initialize a variable as zero to store the reversed number.
STEP 3: Use a
while loop until the number is greater than zero. This loop will continue to get the whole number reversed.
STEP 4: Extract the digit from the number using the Mod operator in python.
STEP 5: Calculate the reverse using the formula rev*10 + digit. (multiplying with 10 to get the digit in the proper position.)
STEP 6: Split the number and remove the last digit by dividing the number by 10.
STEP 7: printing the result as a reversed number using print statements in python language basics.
n=int(input("Enter number: ")) rev=0 while(n>0): dig=n rev=rev*10+dig n=n//10 print("Reverse of the number:",rev)
Enter number:12345 Reverse of the number: 54321