- Python Return String From Function
- Create String in Function Body
- Return String With List Comprehension
- Return String with String Concatenation
- String Concatenation of Function Arguments
- Concatenate Arbitrary String Arguments and Return String Result
- Background List Comprehension
- Python return statement
- Python Function without return statement
- Python Return Statement Example
- Python return statement with expression
- Python return boolean
- Python return string
- Python return tuple
- Python function returning another function
- Python function returning outer function
- Python return multiple values
- Summary
- Python return statement
- Python Function without return statement
- Python Return Statement Example
- Python return statement with expression
- Python return boolean
- Python return string
- Python return tuple
- Python function returning another function
- Python function returning outer function
- Python return multiple values
- Summary
Python Return String From Function
A Python function can return any object such as a string. To return a string, create the string object within the function body, assign it to a variable my_string , and return it to the caller of the function using the keyword operation return my_string . Or simply create the string within the return expression like so: return «hello world»
def f(): return 'hello world' f() # hello world
Create String in Function Body
Let’s have a look at another example:
The following code creates a function create_string() that iterates over all numbers 0, 1, 2, …, 9, appends them to the string my_string , and returns the string to the caller of the function:
def create_string(): ''' Function to return string ''' my_string = '' for i in range(10): my_string += str(i) return my_string s = create_string() print(s) # 0123456789
Note that you store the resulting string in the variable s . The local variable my_string that you created within the function body is only visible within the function but not outside of it.
So, if you try to access the name my_string , Python will raise a NameError :
>>> print(my_string) Traceback (most recent call last): File "", line 1, in print(my_string) NameError: name 'my_string' is not defined
To fix this, simply assign the return value of the function — a string — to a new variable and access the content of this new variable:
>>> s = create_string() >>> print(s) 0123456789
There are many other ways to return a string in Python.
Return String With List Comprehension
For example, you can use a list comprehension in combination with the string.join() method instead that is much more concise than the previous code—but creates the same string of digits:
def create_string(): ''' Function to return string ''' return ''.join([str(i) for i in range(10)]) s = create_string() print(s) # 0123456789
For a quick recap on list comprehension, feel free to scroll down to the end of this article.
You can also add some separator strings like so:
def create_string(): ''' Function to return string ''' return ' xxx '.join([str(i) for i in range(10)]) s = create_string() print(s) # 0 xxx 1 xxx 2 xxx 3 xxx 4 xxx 5 xxx 6 xxx 7 xxx 8 xxx 9
Return String with String Concatenation
You can also use a string concatenation and string multiplication statement to create a string dynamically and return it from a function.
Here’s an example of string multiplication:
def create_string(): ''' Function to return string ''' return 'ho' * 10 s = create_string() print(s) # hohohohohohohohohoho
String Concatenation of Function Arguments
Here’s an example of string concatenation that appends all arguments to a given string and returns the result from the function:
def create_string(a, b, c): ''' Function to return string ''' return 'My String: ' + a + b + c s = create_string('python ', 'is ', 'great') print(s) # My String: python is great
Concatenate Arbitrary String Arguments and Return String Result
You can also use dynamic argument lists to be able to add an arbitrary number of string arguments and concatenate all of them:
def create_string(*args): ''' Function to return string ''' return ' '.join(str(x) for x in args) print(create_string('python', 'is', 'great')) # python is great print(create_string(42, 41, 40, 41, 42, 9999, 'hi')) # 42 41 40 41 42 9999 hi
Background List Comprehension
💡 Knowledge: List comprehension is a very useful Python feature that allows you to dynamically create a list by using the syntax [expression context] . You iterate over all elements in a given context “ for i in range(10) “, and apply a certain expression, e.g., the identity expression i , before adding the resulting values to the newly-created list.
In case you need to learn more about list comprehension, feel free to check out my explainer video:
Python return statement
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
The python return statement is used to return values from the function. We can use the return statement in a function only. It can’t be used outside of a Python function.
Python Function without return statement
Every function in Python returns something. If the function doesn’t have any return statement, then it returns None .
def print_something(s): print('Printing::', s) output = print_something('Hi') print(f'A function without return statement returns ')
Output:
Python Return Statement Example
We can perform some operation in a function and return the result to the caller using the return statement.
def add(x, y): result = x + y return result output = add(5, 4) print(f'Output of add(5, 4) function is ')
Output:
Python return statement with expression
We can have expressions also in the return statement. In that case, the expression is evaluated and the result is returned.
def add(x, y): return x + y output = add(5, 4) print(f'Output of add(5, 4) function is ')
Output:
Python return boolean
Let’s look at an example where we will return the boolean value of the argument of a function. We will use bool() function to get the boolean value of the object.
def bool_value(x): return bool(x) print(f'Boolean value returned by bool_value(False) is ') print(f'Boolean value returned by bool_value(True) is ') print(f'Boolean value returned by bool_value("Python") is ')
Output:
Python return string
Let’s look at an example where our function will return the string representation of the argument. We can use the str() function to get the string representation of an object.
def str_value(s): return str(s) print(f'String value returned by str_value(False) is ') print(f'String value returned by str_value(True) is ') print(f'String value returned by str_value(10) is ')
Output:
Python return tuple
Sometimes we want to convert a number of variables into a tuple. Let’s see how to write a function to return a tuple from a variable number of arguments.
def create_tuple(*args): my_list = [] for arg in args: my_list.append(arg * 10) return tuple(my_list) t = create_tuple(1, 2, 3) print(f'Tuple returned by create_tuple(1,2,3) is ')
Output: Further Reading: Python *args and **kwargs
Python function returning another function
We can return a function also from the return statement. This is similar to Currying, which is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.
def get_cuboid_volume(h): def volume(l, b): return l * b * h return volume volume_height_10 = get_cuboid_volume(10) cuboid_volume = volume_height_10(5, 4) print(f'Cuboid(5, 4, 10) volume is ') cuboid_volume = volume_height_10(2, 4) print(f'Cuboid(2, 4, 10) volume is ')
Output:
Python function returning outer function
def outer(x): return x * 10 def my_func(): return outer output_function = my_func() print(type(output_function)) output = output_function(5) print(f'Output is ')
Output:
Python return multiple values
If you want to return multiple values from a function, you can return tuple, list, or dictionary object as per your requirement. However, if you have to return a huge number of values then using sequence is too much resource hogging operation. We can use yield, in this case, to return multiple values one by one.
def multiply_by_five(*args): for arg in args: yield arg * 5 a = multiply_by_five(4, 5, 6, 8) print(a) # showing the values for i in a: print(i)
Output:
Summary
The python return statement is used to return the output from a function. We learned that we can also return a function from another function. Also, expressions are evaluated and then the result is returned from the function. You can checkout complete python script and more Python examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Python return statement
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
The python return statement is used to return values from the function. We can use the return statement in a function only. It can’t be used outside of a Python function.
Python Function without return statement
Every function in Python returns something. If the function doesn’t have any return statement, then it returns None .
def print_something(s): print('Printing::', s) output = print_something('Hi') print(f'A function without return statement returns ')
Output:
Python Return Statement Example
We can perform some operation in a function and return the result to the caller using the return statement.
def add(x, y): result = x + y return result output = add(5, 4) print(f'Output of add(5, 4) function is ')
Output:
Python return statement with expression
We can have expressions also in the return statement. In that case, the expression is evaluated and the result is returned.
def add(x, y): return x + y output = add(5, 4) print(f'Output of add(5, 4) function is ')
Output:
Python return boolean
Let’s look at an example where we will return the boolean value of the argument of a function. We will use bool() function to get the boolean value of the object.
def bool_value(x): return bool(x) print(f'Boolean value returned by bool_value(False) is ') print(f'Boolean value returned by bool_value(True) is ') print(f'Boolean value returned by bool_value("Python") is ')
Output:
Python return string
Let’s look at an example where our function will return the string representation of the argument. We can use the str() function to get the string representation of an object.
def str_value(s): return str(s) print(f'String value returned by str_value(False) is ') print(f'String value returned by str_value(True) is ') print(f'String value returned by str_value(10) is ')
Output:
Python return tuple
Sometimes we want to convert a number of variables into a tuple. Let’s see how to write a function to return a tuple from a variable number of arguments.
def create_tuple(*args): my_list = [] for arg in args: my_list.append(arg * 10) return tuple(my_list) t = create_tuple(1, 2, 3) print(f'Tuple returned by create_tuple(1,2,3) is ')
Output: Further Reading: Python *args and **kwargs
Python function returning another function
We can return a function also from the return statement. This is similar to Currying, which is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.
def get_cuboid_volume(h): def volume(l, b): return l * b * h return volume volume_height_10 = get_cuboid_volume(10) cuboid_volume = volume_height_10(5, 4) print(f'Cuboid(5, 4, 10) volume is ') cuboid_volume = volume_height_10(2, 4) print(f'Cuboid(2, 4, 10) volume is ')
Output:
Python function returning outer function
def outer(x): return x * 10 def my_func(): return outer output_function = my_func() print(type(output_function)) output = output_function(5) print(f'Output is ')
Output:
Python return multiple values
If you want to return multiple values from a function, you can return tuple, list, or dictionary object as per your requirement. However, if you have to return a huge number of values then using sequence is too much resource hogging operation. We can use yield, in this case, to return multiple values one by one.
def multiply_by_five(*args): for arg in args: yield arg * 5 a = multiply_by_five(4, 5, 6, 8) print(a) # showing the values for i in a: print(i)
Output:
Summary
The python return statement is used to return the output from a function. We learned that we can also return a function from another function. Also, expressions are evaluated and then the result is returned from the function. You can checkout complete python script and more Python examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us