Listen to Your Favourite Programming Podcasts and Books on Audible - Here is a Free Trial - Click Here - Offer Limited Time Only
Python 3 Functions - Learn Python Programming Tutorial

Python 3 Functions - Learn Python Programming Tutorial

Marty Jacobs · May 10, 2019 18:59 · 1003 words · 5 minute read

Alt Text!

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 which 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 a 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…

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!

Scope

Scope is the region within a computer program where the program binding will be valid. This is to logical isolate parts of the program to execute in seperation. 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

Default arguments is an argument that assumes a default value if an argument is not provided.

#!/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. 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.

Thanks for reading!