Python Tutorial
Python - Introduction Python - Syntax Python - Variable Python - Number Python - Casting Python - String Python - Operators Python - Conditions Python - Loops Python - List Python - Tuple Python - Set Python - Dictionary Python - Function Python - Module Python - Date & Time Python - Input Output Python - Error & Exception Python - File Handling
Python OOP
OOP - Introduction OOP - Class Members OOP - Constructor Destructor OOP - Data Hiding OOP - Inheritance OOP - Overriding OOP - Overloading

Python Function

Function is a group of related statements that perform a specific task.

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Calling a Function

To call a function, use the function name followed by parenthesis:

Function Parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses.

You can add as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Pass by Reference vs Value

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

Function Arguments

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

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Flexiable arguments / varargs

Required Arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows:

Keyword Arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways:

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. The following example gives an idea on default arguments, it prints default gender if it is not passed:

Flexible arguments

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

Unpacking Arguments

Unpacking arguments is a way to a pass collection data types (list, set, tuple, dictionary) to set instead of individual elements.

The return Statement

To let a function return a value, use the return statement:

The Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
  • An anonymous function cannot be a direct call to print because lambda requires an expression.
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
  • Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons.

The syntax of lambda functions contains only a single statement, which is as follows:

lambda [arg1 [,arg2,.....argn]]:expression

The power of lambda is better shown when you generate anonymous functions at run-time, as shown in the following example:

Here we see the defined function, myfunc, which creates an anonymous function that doubles some on-the-fly variable i with a just-in-time variable n representing our multiplier.

We then create two variables doubler and tripler, which are assigned to the result of myfunc passing in 2 and 3 respectively. They are assigned to the generated lambda functions.

Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:

  • Global variables
  • Local variables

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

  • If a local and a global variable have the same name, the local variable shadows the global variable.
  • Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
  • Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
  • Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
  • The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

Python Built-in global variables

Python has several built-in global variables that you can use in your script regardless of scope:

Use globals() function to list all built-in global variables:

Function Callback

A callback function is a function passed as a parameter to another function.

Nested Functions

Python allows you to nest functions, i.e. function inside function.

Python Closure

A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.

Python Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available.

They are listed here in alphabetical order:

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
enumerate() Takes a collection (e.g a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Goes to the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
@staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() call parent method
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ peroperty of an object
zip() Returns an iterator, from two or more iterators