Making functions in python

Python Functions – How to Define and Call a Function

Kolade Chris

Kolade Chris

Python Functions – How to Define and Call a Function

In programming, a function is a reusable block of code that executes a certain functionality when it is called.

Functions are integral parts of every programming language because they help make your code more modular and reusable.

In this article, I will show you how to define a function in Python and call it, so you can break down the code of your Python applications into smaller chunks.

I will also show you how arguments and the return keyword works in Python functions.

Basic Syntax for Defining a Function in Python

In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon.

The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

def functionName(): # What to make the function do 

Basic Examples of a Function in Python

Following the basic syntax above, an example of a basic Python function printing “Hello World” to the terminal looks like this:

def myfunction(): print("Hello World") 

To call this function, write the name of the function followed by parentheses:

Next, run your code in the terminal by typing python filename.py to show what you want the function to do:

sss-1

Another basic example of subtractig 2 numbers looks like this:

def subtractNum(): print(34 - 4) subtractNum() # Output: 30 

Arguments in Python Functions

While defining a function in Python, you can pass argument(s) into the function by putting them inside the parenthesis.

The basic syntax for doing this looks as shown below:

def functionName(arg1, arg2): # What to do with function 

When the function is called, then you need to specify a value for the arguments:

functionName(valueForArg1, valueForArg2) 

Here’s an example of arguments in a Python function:

def addNum(num1, num2): print(num1 + num2) addNum(2, 4) # Output: 6 
  • I passed 2 arguments into the function named addNum
  • I told it to print the sum of the 2 arguments to the terminal
  • I then called it with the values for the 2 arguments specified

N.B.: You can specify as many arguments as you want.

How to Use the Return Keyword in Python

In Python, you can use the return keyword to exit a function so it goes back to where it was called. That is, send something out of the function.

The return statement can contain an expression to execute once the function is called.

The example below demonstrates how the return keyword works in Python:

def multiplyNum(num1): return num1 * 8 result = multiplyNum(8) print(result) # Output: 64 

What’s the code above doing?

  • I defined a function named multiplyNum and passed it num1 as an argument
  • Inside the function, I used the return keyword to specify that I want num1 to be multiplied by 8
  • After that, I called the function, passed 8 into it as the value for the num1 argument, and assigned the function call to a variable I named result
  • With the result variable, I was able to print what I intended to do with the function to the terminal

Conclusion

In this article, you learned how to define and call functions in Python. You also learned how to pass arguments into a function and use the return keyword, so you can be more creative with the functions you write.

If you find this article helpful, don’t hesitate to share it with your friends and family.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

How to create function in Python

A function is a block of code that performs some specific task and returns back to the caller. It has a unique name.

They are helpful when need to perform the same task with different-different values or require to use the same block of code in other places within the program.

If any changes require in the future then only need to update the function code and it will automatically make changes where the function it been called.

How to create function in Python

Contents

1. Defining a function

To create function def keyword is use in Python. Define a unique name for the function and in parenthesis, you can specify your parameters.

Function block starts with colon(:) symbol.

def function-name(paramenter): # statement
def callMe(): print("Function is called")

In the above example, I have created a callMe() function which not take any arguments. It prints text on the screen when it is called.

2. Calling a function

Specify the function name and specify the parameters in parenthesis () if its takes. After completing the task it returns back to the program.

def function-name(parameter): # defining function # statement function-name(parameter) # calling function
def callMe(): print("Function is called") callMe() callMe()
Function is called Function is called

3. Function with parameter

Specify the parameter in the function if you want to perform the task with different-different parameters.

def function-name(parameter): # statement function-name(parameter)
def checkevenOrodd(num): if num%2 == 0: print("Even number") else: print("Odd number") checkevenOrodd(2) checkevenOrodd(5) checkevenOrodd(8)
Even number Odd number Even number

4. F unction with return

Use return statement to return value from the function to the caller.

def function-name(paramenter): # statement return value
def maxlist(list1): max = list1[0] for l in list1: if l > max: max = l return max list1 = [1,55,23,2] list2 = [4,24,78,6,21] print("max value in list1 is ",maxlist(list1)) print("max value in list2 is ",maxlist(list2))

Above I create function maxlist() which returns max value from the list.

max value in list1 is 55 max value in list2 is 78

5. Default value

Default parameter automatically supplies value even if you don’t supply value while calling the function. Default argument declaration starts from right to left.

def function-name(variable=value,variable=value. ): # statement
def displayInfo(fname,lname="Singh",age=22): print("first name : ",fname,", last name : ",lname,", age : ",age) displayInfo("Yogesh") displayInfo("Vishal",age=24) # Changing age default value displayInfo("Mohit","Sharma")

Above I specify the default value in lname and age variable. If these variable values not defined while calling then it will use the default set value.

first name : Yogesh , last name = Singh , age : 22 first name : Vishal , last name = Singh , age : 24 first name : Mohit , last name = Sharma , age : 22

6. Multiple parameters

For handling an unknown amount of items to function we use a asterisk (*) symbol in function. It holds as many values in a single argument.

def function-name(*argument): # statement
def display(name,*friends): print("name : ",name) print("friends : ",friends) display("Yogesh singh","Sonarika","Vishal","Vijay") display("Jiten singh","Mohit","Ajay","Abhilash","Ganesh","Aditya")

I defined asterisk (*) on the second argument. When the function is called then the first parameter goes to name variable and all other parameters goes to friends variable.

It converts the friends argument into a tuple.

name : Yogesh singh friends : ('Sonarika','Vishal','Vijay') name : Jiten singh friends : ('Mohit','Ajay','Abhilash','Ganesh','Aditya')

Источник

Читайте также:  Encoding php xml utf 8
Оцените статью