Python 3 functions - learn Python programming tutorial
ADVERTISEMENT
Table of Contents
- Introduction
- Python functions
- Defining a Python 3 function
- Function syntax
- How to use a Python 3 function
- Function scope
- Local variables vs. Global variables
- Return statement
- Default arguments
- Keyword arguments
- Python 3 resources
- What you will learn
- Summary
- Next Steps
Introduction
In this article, we'll present a tutorial for learning about functions in Python 3.
Python functions
What is a function? A function is a block of code used to perform a specific task. It can be a collection of many tasks strung together to perform a single task. It is a block of code that can be re-used elsewhere inside a Software application, helping to build the application, brick by brick, function by function. Python programming language provides the capabilities to build software applications using functions. Through using Python you can build your own functions or use the Python 3 standard library which contains pre-written functions. These functions can help you build your software faster without the reliance on having to build everything from scratch.
Defining a Python 3 function
How do we define a function using the latest version of Python?
- Create your python application
- Define a function using the 'def' syntax
- Write the details of your function
- Make sure the indentation is correct
- Call your function
- Run your application
This seems long-winded, but it actually becomes second nature after writing a function for yourself. You will be creating Python functions in no time at all. Once you get the hang of the syntax and can see how to use a function in python programming, you will understand. This brings us to...
Function syntax
Let's create your python application by opening a text file and saving it as myfunction.py
.
Next, we want to define a function using the def
syntax. Let's create a function that prints the words, "Hello World" to the screen.
How to use a Python 3 function
Inside your myfunction.py
file, define a function using the following:
def hello_world():
print("Hello World!")
Note, that we have written the implementation of the function above by using the print
function, this is supplied by the Python standard library. We specify what we will print to the screen, which is, "Hello World!". And it looks like the indentation is correct!
We shall proceed.
Next, call your function inside your python file by invoking the function.
def hello_world():
print("Hello World!")
hello_world()
Last, but not least, run your application by running the file myfunction.py
via python to see the end result.
You should see on your screen/terminal the following.
Hello World!
Function scope
The scope is the region within a computer program where the program binding will be valid. This is too logical to isolate parts of the program to execute in separation. If we take our example from above,
def hello_world():
print("Hello World!")
hello_world()
You will notice the print statement is within the hello_world function scope. All code indented inside the function scope will be executed when the function is called. You will also notice, we called the function out of its own function scope, at the top level of the program.
def hello_world():
print("Hello World!")
hello_world() <--- Top level function call
Local variables vs. Global variables
Local variables are every variable defined inside a function. Declaring a variable inside the function scope will render it to be used by only the inner workings of the function. Defining a global variable will allow the variable to be used anywhere in the application. So, any function can use/manipulate the global variable.
Return statement
A return
is a common keyword used in the python programming language and it is used by functions to return an end result. For example, a function which adds the variables a
and b
will likely return a combined variable, let's call it c
. This can be displayed as the following function...
def add_variables(a, b):
c = a + b
return c
add_variables()
Default arguments
a default argument is an argument that assumes a default value if no argument is provided when the function is called.
#!/usr/bin/python3
def print_numbers( a = 1, b ):
"This prints a passed info into this function"
print ("a: ", a)
print ("b ", b)
return
printnumbers( a = 2, b = 2 )
printnumbers( b = 2 )
You should see on your screen/terminal the following:
a: 2
b: 2
The latest function call printnumbers( a = 2, b = 2 )
will override the argument a = 1
:
a: 1
b: 2
As a
is initialized to 1
in the default arguments and only b
has been declared in the function parameter, a's value will default to 1.
Keyword arguments
Keyword arguments allow you to identify arguments when calling a function, inside the function parameter. They allow you to skip arguments so you if you don't have access to some data it will not break your function. The order does not matter in keyword arguments. So you don't have to worry about the specific ordering of your arguments.
#!/usr/bin/python3
def add_variables( a, b ):
c = a + b
"This prints the result of adding a and b"
print (c)
return c
add_variables( a = 1, b = 2)
You should see on your screen/terminal the following:
3
Python 3 resources
The best resource to learn Python 3 is "Learn Python 3 The Hard Way". This book offers a simple introduction to the python programming language. You bring the discipline, commitment, and persistence; the author supplies everything else.
What you will learn
- Install a complete Python environment
- Organize and write code
- Fix and break code
- Variables
- Strings
- Interacting with users
- Files
- Looping and logic
- Data structures using lists and dictionaries
- Designing programs
- Object-oriented programming
- Inheritance and compositions
- Modules, classes, and objects
- Python packages
- Automated testing
- Basic game development
- Basic web development
There are also several online courses that you can sign up for which provide python assignments to improve your programming skills. The top-rated course is The complete Python Masterclass on Udemy. This course will advance your python skills through a guided program.
Another great resource to learn python programming is through Youtube. We don't often recommend Youtube, however, it seems helps to visually see someone explain and write python code. Here is a video on Python functions.
Here are the top 5 best books for learning the Python programming language. These books cover the Python programming language more broadly, taking you from beginner to expert.
Summary
In this article, we discussed how functions work in Python 3.
Next Steps
If you're interested in learning more about the basics of Python, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.
Final Notes
Recommended product: Coding Essentials Guidebook for Developers