How To Return A String In A Function Python

In this tutorial, we will learn how to return a string from a function in Python. Functions are essential building blocks of any programming language and can make your code more efficient and reusable. Returning a string from a function can be useful when you want to manipulate, display or further process the output of a function.

Step 1: Define the function

First, let’s define a simple function that takes a string as an argument and returns the same string as the output.

In this example, our function is called return_string, and it takes one parameter, input_string. The return keyword is used to indicate that the function should return the value of input_string.

Step 2: Call the function and print the returned string

Now let’s call the function by passing a string to it and print the returned value:

When we run this code, the output will be:

Hello, World!

Step 3: Combine the steps

We can combine the function definition and the function call into a single script:

Running this script will produce the same output as before:

Hello, World!

Step 4: Create a more complex example

Let’s create a function that takes a string and a number as arguments and returns a new string containing the input string repeated the specified number of times:

In this example, our function repeat_string takes two parameters: input_string and repetitions. The return statement multiplies the input string by the number of repetitions to create the output string.

When we run this code, the output will be:

Python Python Python 

Full Code

Here is the full code for our two examples:

When we run the full code, the output will be:

Hello, World!
Python Python Python 

Conclusion

In this tutorial, we have learned how to return a string from a function in Python. We’ve demonstrated this by creating simple functions that return a single input string and a function that takes a string and a number as input and returns a new string.