Home » Python » Python programs

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?
Submitted by Bipin Kumar, on December 06, 2019

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. 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 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.

Program:

# 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.