# Functions - 1

**Definition:** A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

**Here are simple rules to define a function in Python:**&#x20;

* Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
* Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
* The first statement of a function can be an optional statement - the documentation string of the function or docstring.
* The code block within every function starts with a colon (:) and is indented.
* The statement return \[expression] exits a function, optionally passing back an expression to the caller.
* A return statement with no arguments is the same as return None.

**SYNTAX :**

```python
def functionname( parameters ):
    "function_docstring"
    function_suite
    return [expression]
```

Example -1:

```python
def printme( str ):
    "This prints a passed string into this function"
    print(str)
    return 

printme("Python") #calling
```

Output: Python

**Calling a Function :**&#x20;

1. Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
2. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.

Example -2:

```python
#Function definition is here
def printme( str ):
    "This prints a passed string into this function"
    print(str)
    return;
    
#Now calling printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
```

Output

I'm first call to user defined function!

Again second call to the same function

**Pass by Reference vs Pass by Value:**

**Let's understand this concept in C++ programming**

Example-3:

```python
#include <iostream>
using namespace std;

void func(int *x)
{
cout << "In func x=" << *x << " address of x=" << x <<  endl;

*x=4;
return;
}

void func1(int x){
cout << "In func1 x=" << x << " address of x=" << &x <<  endl;
x=5;
cout << x << endl;
return;
}

int main() {
// your code goes here
int x = 3;
func(&x);  //pass by reference in c++
cout << "In main after func x=" << x << " address of x=" << &x << endl;

func1(x);  //pass by value in c++
cout << "In main after func1 x=" << x << " address of x=" << &x << endl;
return 0;
}


```

Output:

![Output in C++](https://2666241650-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSc84l98ozg0PCtzUMg%2F-M5M4yUc4J860o_dCjDC%2F-M5MAyswCqiHdeO1pYD8%2Fimage.png?alt=media\&token=d5233647-c789-499a-aecd-40c2c398faf0)

All parameters (arguments) in the Python language are passed by reference.

* If you change what a parameter refers to within a function, the change also reflects back in the calling function if the address is same like in some cases of list and dictionary (when complete list is not changed as shown in below example)

Example-4:

```python
def ref_demo(x):
    x[1] = 4
    print("Within Function: x=",x," id=",id(x))
    
x = [12,3,6]
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))
```

Output:

x= \[12, 3, 6] id= 2689911761288

Within Function: x= \[12, 4, 6] id= 2689911761288

Outside Function: x= \[12, 4, 6] id= 2689911761288

* If you change what a parameter refers to within a function, the change doesn't reflects back in the calling function if the address is different like in case of number, string, tuple, and some cases of list and dictionary

Example-5 (A):

```python
def ref_demo(x):
    x = [1,5,2]
    print("Within Function: x=",x," id=",id(x))
    
x = [12,3,6]
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))
```

x= \[12, 3, 6] id= 2689911760072

Within Function: x= \[1, 5, 2] id= 2689911760584

Outside Function: x= \[12, 3, 6] id= 2689911760072

Example-5 (B):

```python
def ref_demo(x):
    x[0] = 1
    x[1] = 11
    x[2] = 111
    print("Within Function: x=",x," id=",id(x))
    
x = [12,3,6]
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))
```

x= \[12, 3, 6] id= 2480079932808&#x20;

Within Function: x= \[1, 11, 111] id= 2480079932808&#x20;

Outside Function: x= \[1, 11, 111] id= 2480079932808

Example-6:

```python
def ref_demo(x):
    x = 8
    print("Within Function: x=",x," id=",id(x))
    
x = 7
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))
```

x= 7 id= 140707894174288&#x20;

Within Function: x= 8 id= 140707894174320&#x20;

Outside Function: x= 7 id= 140707894174288

Example 7 :

```python
#!/usr/bin/python3
#Function definition is here
def changeme( mylist ): 
    "This changes a passed list into this function"
    print("Values inside the function before change: ", mylist)
    mylist[2]=50
    print("Values inside the function after change: ", mylist)
    return

#Now you can call changeme function
mylist = [10,20,30]
changeme(mylist)
print("Values outside the function: ", mylist)
```

Output: Values inside the function before change: \[10, 20, 30]

Values inside the function after change: \[10, 20, 50]

Values outside the function: \[10, 20, 50]

Example 8 :

```python
#!/usr/bin/python3
#Function definition is here
def changeme( mylist ):
    "This changes a passed list into this function"
    mylist = [1,2,3,4] # This would assi new reference in mylist
    print ("Values inside the function: ", mylist)
    return
#Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print("Values outside the function: ", mylist)
```

Output: Values inside the function: \[1, 2, 3, 4]

Values outside the function: \[10, 20, 30]

### **Function Arguments:**&#x20;

You can call a function by using the following types of formal arguments −

1. Required arguments

2. Keyword arguments

3. Default arguments

4. Variable-length arguments

5. **Required Arguments :-**

Required arguments are the arguments passed to a function in correct positional order.

The number of arguments in the function call should match exactly with the function definition.

Example 9 :

```python
#!/usr/bin/python3
#Function definition is here
def printme( str ):
    "This prints a passed string into this function"
    print (str)
    return
#Now you can call printme function
printme("Python")
```

Output: Python

**2. Keyword arguments**

Keyword arguments are related to the function calls.

When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

Example 10 :

```python
#Function definition
def printme( str ):
    "This prints a passed string into this function"
    print(str)
    return;

#calling printme function
printme( str = "Python is Awesome")
```

Output: Python is Awesome

**3. Default arguments:**

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Example 11 :

```python
#!/usr/bin/python3
#Function definition is here
def printinfo( name, age = 35 ):
    "This prints a passed info into this function"
    print("Name: ", name)
    print("Age ", age)
    return
#Now you can call printinfo function
printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )
```

Output:

Name: miki

Age 50

Name: miki

Age 35

**4. Variable-length arguments:**

You may need to process a function for more arguments than you specified while defining the function.

These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Values passed&#x20;

Example 12 :

```python
#Function definition
def printinfo( arg1, *vartuple ):
    "This prints a variable passed arguments"
    print("Output is: ")
    print(arg1)
    print(type(vartuple))
    print(vartuple)
    for var in vartuple:
        print(var)
        print(type(var))
    return;

#Calling Function
printinfo(10)
printinfo(3,754,75)
x = [2,4,3]
y = [12,4,3]
z = [45,65]
printinfo(x,y,z)
```

Output is:&#x20;

10

\<class 'tuple'>

&#x20;()&#x20;

Output is:&#x20;

3

\<class 'tuple'>

(754, 75)&#x20;

754

\<class 'int'>

75

\<class 'int'>

&#x20;Output is:&#x20;

\[2, 4, 3]

\<class 'tuple'>

&#x20;(\[12, 4, 3], \[45, 65])&#x20;

\[12, 4, 3]

\<class 'list'>

&#x20;\[45, 65]

\<class 'list'>

When using (\*) symbol while passing more than one argument, values are passed as tuple

Example-13:

```python
#Function definition
def printinfo( arg1, *abc ):
    "This prints a variable passed arguments"
    print("Output is: ")
    print(arg1)
    print(type(abc))
    for var in abc:
        print(var)
    return;

#Calling Function
printinfo("mikki")
printinfo(70, 60, 50)
```

Output:

Output is: mikki

\<class 'tuple'>

&#x20;Output is:&#x20;

70

&#x20;60

&#x20;50


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-python.gitbook.io/python-programming/functions-in-python/functions-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
