In this tutorial, you will learn to write a Python Program To Reverse a Number Using For Loop.
To understand this program you should have an understanding of the following topics:
Python Program To Reverse a Number Using For Loop
num = int(input("Enter a number: "))
num_str = str(num)
reverse_str = ""
for i in range(len(num_str)-1, -1, -1):
reverse_str += num_str[i]
reverse_num = int(reverse_str)
print("The reversed number is:", reverse_num)
Output
Enter a number: 456789nThe reversed number is: 987654
In this program, we first prompt the user to input a number.
We then convert the number to a string using str(num) and store it in a variable called num_str.
We then declare an empty string called reverse_str.
We use a for loop to iterate over the characters of num_str in reverse order.
We use the range() function to generate a sequence of indices that start at the last index of num_str and go down to the first index.
Inside the loop, we append each character of num_str to reverse_str in reverse order by using the += operator.
Once the loop finishes, we have the reverse of the number as a string.
We convert it back to an integer using int(reverse_str) and store it in a variable called reverse_num.
Finally, we print out the value of reverse_num, which is the reversed number.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.