СHRISTMAS
WHEEL OF FORTUNE

Tap the button and win a guaranteed prize right now!

By registering, you are signing up to receiving e-mails.
DF
February 27 2023
Updated June 7 2023

How to create functions in Python 3

Linux Ubuntu

Introduction

A function in Python is a block of instructions that takes input, executes instructions, and returns input information. Blocks of code defined as a function can be reused.
Python has built-in functions:

  • print() —displays information;
  • int() — converts a string or numeric data type to an integer data type;
  • len() — returns the length of the value.

In this tutorial, we will look at creating new functions for use in our project.

Preparation before work

Need to prepare system for work, install the latest Python 3 and deploy virtual environment.

Function definition

Let's consider the usual code such as for displaying information. Let's create a test_hello.py file and add a function in our virtual environment. A function is defined using the def() keyword:

def hello():

If you are using the Vim text editor, after creating the function, Vim redirects to the second line using automatic tabulation.

Let's add the following piece of code to output information to the console.

def hello():
print("Hello, Dear, User!")

Call the function at the end of the code hello().

def hello():
print("Hello, Dear, User!")

hello()

Let's run the code and get the result:

python3 test_hello.py
The result of the written function
Screen 1 - The result of the written function

Functions come in different complexity, the simplest one was discussed above.

Consider the function below, which will use if-else conditional statements to iterate over vowels in strings.

# Creating the names function()
def names():
# Name input variable
name = str(input('Enter your name: '))
# Checking for vowels
if set('aeiou').intersection(name.lower()):
print('Your name has vowels!')
else:
print('Your name does not contain vowels')

# Iterate by name
for letter in name:
print(letter)

# Function call
names()

So, we created the names() function and used if-else conditional statements and a for statement in it.

Working with parameters

Up to this point, we have considered functions without the use of parameters, then we will define the function and its parameters.

Parameters are objects within our function that point to an argument that the function can take.

Consider code with three parameters i, j and k and create a function to add them all together in different configurations. Then their sums will be printed in the add() function. Call the function to get the result.

Let's write the following piece of code in a new TestAdd.py file:

def add(i, j, k):
q = i + j
w = i + k
e = j + k
print(q, w, e)

add(20, 25, 30)

We passed the data to the parameters, i.e. 20 - for parameter i, 25 - for parameter j, 30 - for parameter k. The program performs the following mathematical operations:

q = 20 + 25
w = 20 + 30
e = 25 + 30

Let's run the program and get our result in the form:

45 50 55

When we passed 20, 25, and 30 as parameters to the add() function, we got the expected result.

Key Arguments

Parameters can be called not only in order, but also using key arguments at the time when the called function identifies the arguments by the name of the parameter.

Let's create a file called TestInfo. Let's define the info() function and assign parameters. Let's add a print() statement to display information. At the end of the code, we call the info function using the parameters and their values ​​defined inside the info() function call.

#Function with parameters
def info(name, age):
print("Name: " + name)
print("Age: " + str(age))

Next, consider assigning values ​​to parameters.

# Function definition with parameters
def info(name, age):
print("Name: " + name)
print("Age: " + str(age))

#Calling a function with parameters above
info("ServerSpace", 25)

#Calling a Function Using Key Arguments
info(name="Team", age=35)

Let's run the code and get the result:

Result obtained using parameters and key arguments
Screen 2 - Result obtained using parameters and key arguments

In the following code, consider specifying the age parameter at the beginning of the info() function call. After defining the function, we call the print() statement to print information about the name and age.

At the end of the code, we call the info function, first specifying the age, then the name. But before that, we get the result about the name, then about the age inside the info () function. The reason is that the order in which the print() statement is called has not changed:

# Function definition with parameters
def info(name, age):
print("Name: " + name)
print("Age: " + str(age))

#Calling a Function Using Key Arguments
info(age=40, name="ServerSpaceTeam")

The result of calling parameters in reverse
Screen 3 - The result of calling parameters in reverse

Assigning Key Arguments

Copy the file TestInfo.py and change the name to TestInfoValue.py

cp TestInfo.py TestInfoValue.py

By default, the age parameter is assigned the value "1". If you call the info function without specifying the value of the age parameter, we get the result Age = 1. Consider the options for calling the info function with the value of the age parameter and using the key argument:

# Function definition with parameters
def info(name, age=1):
print("Name: " + name)
print("Age: " + str(age))

#Calling a Function with a Key Argument and Without a Key Argument
info(name="ServerSpace")
info(name="Team", age=15)

Result of the executed code using the default value
Screen 4 - Result of the executed code using the default value

We have considered two kinds of calling the info() function. In the first case, we specified a value for the name parameter and did not specify a value for the age parameter, and when displaying information, the age parameter was assigned a default value of "1". In the second case, values ​​were specified for both parameters, but the default value of the age parameter was not displayed.

Returning values

Data from parameters can be passed to a function. The value of a parameter can be returned using the return statement.

When using return without an argument, we get a result with a value of None.

Let's create a TestSquare.py file and define the testsquare function with the i parameter. Let's add a variable j in which we raise the parameter i to the third power. We use return to return the value obtained as a result of the operation inside the j variable. Using the result variable, we assign the value 5 to the i parameter in the testsquare function. At the end of the code, we use the print() statement to print the result information. This will return the value of the operation 5 ** 3. Using "**" in Python denotes exponentiation:

def testsquare(i):
j = i ** 3
return j

result = testsquare(5)
print(result)

After running the code and get the output:

Returning a function with return
Screen 5 - Returning a function with return

If we comment out the return j line, we get the result:

Returning None value
Screen 6 - Returning None value

Consider returning a function with return in TestAdd.py:

def add(i, j, k):
q = i + j
w = i + k
e = j + k
return q, w, e

result = add(20,25,30)
print(result)

Let's run the code and get the result:

The result of the return of the function
Screen 7 - The result of the return of the function

We get the value (45, 50, 55) as a tuple, because when the return function was called, the variables were specified separated by commas.

Using main() as a function

The main() function puts the components of the program into one function, while the main() function does not have to be called in the program.

Consider using main() in a regular program, let's create a TestMain.py file. Let's define the TestMain function and add a print() statement to print text. Let's define a main() function and add a print() statement. At the bottom of the code, add TestMain() and main() to call functions and display text. Let's write the code, run it and get the result:

def TestMain():
print("Hello, Dear, User!")

def main():
print("This is test text")

TestMain()
main()

The result of the above code
Screen 8 - The result of the above code

In Python, you can use the following '__main__' construct, which will run top-level code.

The whole structure looks like this:

if __name__ == '__main__':

Consider a program using the '__main__' construct. The logic of the program is that the code parses the entered value into the name variable and matches it with vowels. If the name contains vowels, the result will be returned
"Your name has vowels":

#Declaring a global variable and for entering a name
name = str(input('Your name: '))

# Function to check vowels
def vowel():

if set('aeiou').intersection(name.lower()):
print('Your name has vowels!')
else:
print('Your name has no vowels!')

# Iteration of letters in a name
def print_letters():
for letter in name:
print(letter)

# Main function definition
def main():
has_vowel()
print_letters()

# Executing the main function
if __name__ == '__main__':
main()

You can also specify two functions has_vowel() and print_letters() at the end, the result will be the same:

if __name__ == '__main__':
has_vowel()
print_letters()
The result of the executed code
Screen 9 - The result of the executed code

Conclusions

As a result, we can say that functions are objects that take arguments and return a value.

For more information about writing a module in Python, we suggest looking in our guide.

Here we looked at possibilities such as:

  • definition of functions;
  • work with function parameters;
  • key arguments;
  • returning values ​​with return;
  • using main() as a function.
Vote:
5 out of 5
Аverage rating : 5
Rated by: 1
33145 North Miami, FL 2520 Coral Way apt 2-135
+1 302 425-97-76
700 300
ITGLOBAL.COM CORP
700 300
We use cookies to make your experience on the Serverspace better. By continuing to browse our website, you agree to our
Use of Cookies and Privacy Policy.