Print the reverse of a string that contains digits in Python

Here, we will learn how to write a function in the Python programming language that returns the integer obtained by reversing the digits of the given integer? By Bipin Kumar Last updated : February 25, 2024

A function is the collection of code that creates to perform a specific task and work for various inputs. When we have to do the same work after an interval then the function reduces the length of code, time complexity, etc.

Problem statement

Here, we will write a function in Python that takes as input a positive integer which will be given by the user and returns the integer obtained by reversing the digits. Before going to solve this problem, we will learn a little bit about the function and how to create it in the Python programming language.

Syntax

Syntax to create a function in Python:

# definition
def function_name(parameters):
	''' function statement that specifies the work 
	of the function i.e body of function.'''
	return(expression)

# function calling
print(functionname(parameters)

The function block begins with the "def" keyword and "function_name". In the parenthesis, it may have an argument or not.

Now, let's start to create a function in Python that returns the integer obtained by reversing the digits. Before going to solve the above problem, assume the name of a function is the reverse(n) and the parameter n which value will be provided by the user. The function reverse(n) returns the integer obtained by reversing the digits in n.

Python program to print the reverse of a string that contains digits

# function definition that will return 
# reverse string/digits 
def reverse(n):
    # to convert the integer value into string
    s=str(n) 
    p=s[::-1]
    return p 

# now, input an integer number
num = int(input('Enter a positive value: '))

# Calling the function and printing the result 
print('The reverse integer:',reverse(num))

Output

RUN 1:
Enter a positive value: 123456
The reverse integer: 654321

RUN 2:
Enter a positive value: 362435
The reverse integer: 534263

In Python, [::-1] is used to reverse list, string, etc. It is a property of slicing of the list.

By using the above code, we can reverse a string that contains only digits, to practice more programs, visit – python programs.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.