Python Functions

What are Functions?

A function is a block of code that performs a specific task. Functions are used to break up code into manageable pieces and to avoid repetition. Python comes with built-in functions like print() and len(), but you can also define your own.

Example of a built-in function:

Python

Tutorials dojo strip

Defining a Function

You define a function in Python using the def keyword, followed by the function name, parentheses ( ), and a colon :. Inside the function, you write the block of code that will run when the function is called.

Syntax:

Python

Example:

Python

To call a function (i.e., execute the code within it), you simply use its name followed by parentheses:

Python

Arguments and Parameters

Functions can accept arguments, which allow you to pass data into the function. When defining a function, the variables listed in the parentheses are called parameters. When calling the function, the actual values passed in are called arguments.

Example:

Python

 

Positional Arguments: 

The arguments are passed in the order in which the parameters are defined.

Python

 

Keyword Arguments: 

You specify which argument corresponds to which parameter, regardless of their order.

Python

 

Default Parameters: 

You can set default values for parameters. If no argument is provided when the function is called, the default value will be used.

Python

return Statement

The return statement allows a function to send a value back to the caller. This lets the function pass data back to the part of the program that called it. Once a return statement is executed, the function terminates.

Example:

Python

A function without a return statement will return `None` by default.

Local vs Global Scope

The scope of a variable refers to the region of the code where that variable can be accessed. Variables defined inside a function are said to be in the local scope and can only be accessed within that function. Variables defined outside any function are in the global scope and can be accessed anywhere in the code.

Example:

Python

You can modify a global variable inside a function by using the global keyword, though it’s generally better practice to avoid this in most cases.

Example:

Python

Importing Modules

Modules are files containing Python code, which can include functions, variables, and classes. You can import a module into your script using the `import` keyword, which gives you access to its functionality.

Example:

Python

You can also import specific functions or objects from a module:

Python

To give an imported module a custom name (an alias):

Python

Modules make it easy to reuse code across different programs, and Python comes with a large standard library of built-in modules.

Tutorials dojo strip