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.
函数是创建代码以执行特定任务并为各种输入工作的代码集合。 当我们必须在间隔后执行相同的工作时,该函数将减少代码的长度,时间复杂度等。在这里,我们将使用Python编写一个函数,该函数将由用户给定的正整数作为输入并返回通过反转数字获得的整数 。 在解决此问题之前,我们将学习一些有关该函数以及如何使用Python编程语言创建它的知识。
Syntax to create a function in Python:
在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.
功能块以“ def”关键字和“ function_name”开头。 在括号中,可以带或不带参数。
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中创建一个函数,该函数返回通过反转数字获得的整数。 在解决上述问题之前,假定函数的名称为reverse(n) ,参数n为用户提供的值。 函数reverse(n)返回通过反转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.
在Python中, [::-1]用于反转列表,字符串等 。 它是列表切片的属性。
By using the above code, we can reverse a string that contains only digits, to practice more programs, visit – python programs.
通过使用上面的代码,我们可以反转仅包含数字的字符串,以练习更多程序,请访问– python program 。
翻译自: https://www.includehelp.com/python/print-the-reverse-of-a-string-that-contains-digits.aspx