Skip to main content
Noble Desktop/2 min read

Composing a Function in Python

Python Workflow

1

Set Up venv

python -m venv .venv — isolated environment per project.

2

Install Dependencies

pip install -r requirements.txt — pin versions for reproducibility.

3

Write & Test

Write functions; test with pytest as you go.

4

Run & Deploy

python script.py locally, deploy to your platform of choice.

Master Python at Noble Desktop

Noble Desktop's Python Programming Immersive covers AI APIs, data analysis, and modern Python development.

In this video, we're going to look at how to compose your own function in Python

Video Transcription

Hi, my name is Art and I teach Python at Noble Desktop. Today I'm going to show you how to compose your own function.

A function is a block of reusable code, something we can use over and over again. Let's create our first function.

Start with the keyword 'def', which stands for 'define', and then come up with a name for the function. The name should reflect the purpose of the function, so I'm going to call mine 'add'. This function takes two arguments (a and b). I want to define a as 6 and b as 7. Then I want to do a total of a plus b.

Now we usually print stuff, as humans we want to see what's going on. But in this case, we will use the 'return' operator, because a function always returns something. So I'm going to 'return' total.

Now I have this function, but nothing is going on because I need to call it to invoke the function. So I'm going to use the function name 'add'. You see I'm calling this function and I'm getting the result.

Keep in mind that 'return' should be the last statement within the function, nothing can be done after 'return'. Also, if I want to save the result of the function, I need to assign it to a variable, like 'variable_one' and 'variable_two'.

Now, these variables will hold the result from the function.

In my next video, I'll show you how to call a function within a function. See you in my next video!

Video Transcript6 sections

1Full Video Transcript

2Introduction to Python Functions

Hi, my name is Arthurin and I teach Python. Today I'm going to show you how you could compose your own function—a Python function. What is a function? A function is a block of reusable code, which means something that we could use over and over again.