Python Basics: Functions and Variable Scopes

By StartxLabs
Date 22-04-21
Python Basics: Functions and  Variable Scopes
" Python Basics: Functions and Variable Scopes"

 

Python is a general-purpose, high-level programming language that has many applications in web development, data science, software development, and more. It was initially released in the year 1991. Programming in Python involves simple syntax and it works on different platforms such as Windows, Mac, Linux, etc. In this article, we will discuss the Python functions.

 

Python Functions

A function is a set of related statements written to perform a specific task when it is called. It can take parameters and return a result. It is efficient to use several functions inside a program to perform specific tasks rather than merely writing a large program that performs the entire tasks. Functions are reusable and make the program easy to understand.

 

Syntax of Python Functions

A simple python function appears like

 

def func_name(parameters):

/* function statements */

return result

 

The syntax of a Python function can be defined as follows:

  • The def keyword is used to denote the start of a function header

  • Followed by def, the function name should be written according to the rules of writing identifiers in Python

  • A semicolon should be added at the end of the function header.

  • A function can take one or more parameters as arguments.

  • The statements inside the function should follow the proper indentation as shown above.

  • The docstring (document string) specified inside " " "    " " "  (triplr quotes) can be used inside the function to define the purpose of the function. Though optional, it is a good practice to use docstring in your function while writing a program.

 

For example

 

def my_name(name):

" " " This function displays my name" " "

print("My name is" +name)

 

Function call

A function can be called in any part of the program or inside another function, by passing appropriate parameters to it.

>>>my_name('John')

My name is John

 

If you want to print the docstring of the function, you can print it by using,

 

>>>print(my_name._doc_)

 

This function displays my name

 

Return Statement

The 'return' statement is placed at the end of the function that returns either a data of a specific type or the evaluated result of an expression. If there is no return statement specified as in the above example function, it returns nothing or to be more precise, a none object is returned.

 

def sum(num1, num2):

" " " This function adds two numbers " " "

return num1+num2

print(sum(2,3))

 

 

Scope of variables and Lifetime

The availability of a variable whether inside or outside of a function is called its scope. A variable declared inside a function has recognition only inside the function and has no scope outside the function. Such variables are called the local variable. A variable declared on the python program (outside a function) is called a global variable and has scope on the entire code and also inside the functions. You can also make a local variable global by adding a keyword "global" before the variable name.

 

Lifetime is the period of a variable that has its existence in memory. Variables declared within the function get destroyed when the function completes its execution. However, the global variables persist as long as the entire program is in execution.

 

We can see an example for local and global variables

 

def func1():

a=5 //local variable

return a

b=10 //global variable

c=func1()+b //function call

print("Value=" +c)

 

Output

 

15

def func1():

a=5 //local variable

return a

b=10 //global variable

c=func1()+b+a //function call

print("Value=" +c)

 

If you try executing this function it will show an error message like "name 'a' is not defined" as we used the variable  outside its scope.

 

There is also another variable called non-local variables that are used within the nested functions. The non-local variables are declared using the 'nonlocal' keyword.

 

There are two types of functions available in Python. They are:

 

  • Built-in functions: Functions that are already available in Python. There are 68 built-in functions available in the most recent version of python, Python 3. For example, bin() returns the binary value of a number, ascii() which returns the Unicode value of a character.

  • User-defined: Functions written by the user.

 

Types of Function Arguments

 

The values passed to the function as parameters are called the function arguments. There are two types of arguments. They are

 

  • Fixed arguments: The number of arguments passed during the function call should be equal to the number of arguments that has been declared to a function during its declaration.

 

For example,

def func1(num1,num2):

return num1+num2

func1(4) /* throws an error as the number of parameters during the function call is not equal to the number of parameters in the declaration */

 

 

  • Variable arguments: There is also another way of declaring variables other than fixed arguments. Variables arguments can be passed using 3 methods. They are:

    • Default arguments by using '=' operator.

 

def func1(num1=5,num2):

return num1+num2

func1(4)

func1(4,10)

Output

9

14

 

The function func1 has two arguments, one with the default value and another without any default value. It is mandatory to pass value to the num2 during every function call but passing a value to num1 is optional as it already has a default value and both the function calls will not throw any error here.

 

  • Keyword Arguments: Keyword arguments are called with the syntax key=value during the function and the order of the arguments is not important here. You can pass the arguments in any order. They are represented as kwargs in Python.

 

def func1(num1,num2):

return num1-num2

func1(num1=7,num2=6)

func1(num2=10,num1=17)

 

Output

 

1

7

 

  • Arbitrary Arguments: When we don't know the exact number of arguments we need to pass to a function during a function declaration, we can assign them during the function call using the '*' keyword.

 

def students(*stud_names):

print("The students are:")

for name in stud_names

print(name)

students("John","Mary","Harry")

 

Output

 

The students are:

John

Mary

Harry

 

Here we don't know the number of arguments we are going to pass during the function call, so we use a for loop for retrieval of the values of arguments.

 

Python Recursive Functions

 

A recursive function is a function which calls itself during execution.

 

for example,

def factorial(num):
  if num == 1:
    return 1
  else:
    return (num * factorial(num-1))

number = 5
print("The factorial of", number, "is", factorial(number))

 

Sometimes it is hard to write a function only using iterations. There we can use recursive functions which are comparatively easier than iterative functions. However, sometimes for complex operations, recursive logic may be hard to understand.

 

Anonymous Function (Lambda Functions)

 

So far we have seen functions declared with a name followed by the def keyword. It is also possible to declare functions without a function name by using the lambda keyword and such functions are called the anonymous functions or the lambda functions. They are also used with some of the python built-in functions such as filter() and map().

 

The syntax of an anonymous function is

 

         lambda arguments: expression

 

Arguments can be of any number, but there should be only one expression

 

int = lambda a: a + 5

print(int(10))

 

Output

 

15

 

In this article, we've learned about the functions in python, how to declare them, how to define them, the variables' scope, their lifetime, types of arguments, and also the anonymous functions.

 

"We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected] or see careers at Startxlabs."

subscribe to startxlabs

startxlabs