Tutorials
Hands-On Python
Hands-On Python
  • Hands-On Python Tutorial For Real-World Business Analytics Problems
  • Preface
    • Section I. A Note From The Author
    • Section II. Tutorial Overview
    • Section III. What Is The Preflight Checklist?
    • Section IV. Supplimentery Material
  • Preflight Checklist
    • Section V. Select Your Difficulty Setting
    • Section VI. Download Anaconda
    • Section VII. Download PyCharm (Optional)
    • Section VIII. Download SQL Server Developer Edition
    • Section IX. Configure Database Environment
    • Section X. Download The Source Code
    • Section XI. Starting JupyterLab
    • Section XII. How To Get Help With This Tutorial
  • Language Basics
    • Lesson 1. Obligatory Hello World
    • Lesson 2. Code Comments
    • Lesson 3. Data Types
    • Lesson 4. Variables
    • Lesson 5. String Concatenation
    • Lesson 6. Arithmetic Operators
    • Lesson 7. Making Decisions
    • Lesson 8. Control Flow With if-elif-else
    • Lesson 9. Control Flow With while
    • Lesson 10. Data Structures Part I: List
    • Lesson 11. Data Structures Part II: Tuples
    • Lesson 12. Data Structures Part III: Dictionaries
    • Lesson 13. Looping With for
    • Lesson 14. Functions
    • Lesson 15. Importing Modules
    • Lesson 16. Python Programming Standards
  • Advanced Topics
    • Lesson 17. Functional Programing With map
    • Lesson 18. Generators
    • Lesson 19. Comprehensions
    • Lesson 20. Basic File Operations
    • Lesson 21. Working With Data In Numpy
    • Lesson 22. Working With Data In Pandas
    • Lesson 23. Working With JSON
    • Lesson 24. Making File Request Over HTTP And SFTP
    • Lesson 25. Interacting With Databases
    • Lesson 26. Saving Objects With Pickle
    • Lesson 27. Error Handling
    • Lesson 28. Bringing It All Together
  • Solutions To Real World Problems
    • Lesson 29. Download A Zip File Over HTTP
    • Lesson 30. Looping Over Files In A Directory
    • Lesson 31. Convert Comma Delmited Files To Pipe Delimited
    • Lesson 32. Combining Multiple CSVs Into One File
    • Lesson 33. Load Large CSVs Into Data Warehouse Staging Tables
    • Lesson 34. Efficiently Write Large Database Query Results To Disk
    • Lesson 35. Working With SFTP In The Real World
    • Lesson 36. Executing Python From SQL Server Agent
Powered by GitBook
On this page
  • Function Syntax
  • Examples
  • Now you try it!
  1. Language Basics

Lesson 14. Functions

In this tutorial, we are not going to get into object-oriented programming. It is a complex topic that deserves a tutorial dedicated to that subject.

When you are learning business analytics you can get pretty far just writing functions without having to go full blown objected oriented, so let’s focus on that.

After a while, you will start to notice that you write the same block of code over and over. It might be the case that other blocks of code use this code, so you cut and paste the lines into other blocks. This is a classic example of code that needs to be turned into a function.

In software engineering, we have a concept called DRY. Don’t repeat yourself. In other words, do not do the thing I just described.

Modern programming languages have all kinds of tools and techniques that you can use to follow the DRY principle. The function is the most common and easiest to implement.

Any block of code that you can write that is valid Python syntax can be placed inside of a function. There are practical limitations here, but, again, we will cover that in a more advanced tutorial.

You can design your function in a manner such that it just does stuff without any outside input and the function does not produce any output. However, most likely, your function needs to do different things based on information passed to it by the line of code that activated it.

You pass in information to functions through function parameters which are frequently referred to as arguments. You can send back output using the return keyword.

When you are writing Python as a series of scripts and not as an object-oriented program, the code executes from top to bottom. That means functions HAVE to be defined before they can be used.

Function Syntax

def function_name(arg1, arg2,...,argN):
    #do stuff
    #return stuff
    
#call the function
function_name(arg1, arg2,...,argN)

Examples

Example #1 Hello World! Part II. This Time It’s Personal!

We are going to pull out this old dog and teach it a new trick! Instead of saying hello to every human on the planet, most of whom are jerks, and don’t deserve a hello, we’re going to personalize our greeting by passing in an argument.

The argument will be the name of a specific person. That string value will be assigned to the variable we use as a name of the argument in the function. That variable can be referenced in the function.

def hello_world(name):
    print('Hello ' + name + '!')

hello_world('Bob')

Example #2 Passing In More Than One Argument

Passing in arguments to functions can get CRAZY in Python. You can do all kinds of things like set up default values, or assign arguments based on position or keyword.

As a new Python engineer who is only just using the built-in functionality of Python, you will find this kind of flexibility to be useful when you are calling the native functions of Python or Python modules. It is less fun when you are the person that has to implement things that others will use.

Before that happens, there are a thousand things that have to happen in order. We are on number eight. Developing modules is number six hundred and ninety-two so we’re going to keep it simple here.

The example below has three arguments. You pass in the arguments based on their position in the function call. In other words, the first argument in the function all will get assigned to the first argument in the function definition and so on.

def viper(greeting, temperature, units):
    print(greeting + 'The temperature is ' + temperature + ' ' + units + '.')

viper('Good morning gentlemen.', '110', 'degrees')

Example #3 Returning Values

Ok here is where I stop screwing around and grim up. Returning values is where functions start to earn their pay. While you can make a function do whatever, usually what you want done is the function to do some repetitive work on some arguments.

Below is a trivial example. As we move through this tutorial, you will start to see the value of functions returning values.

def divide(numerator, denominator):
    quotient = numerator / denominator
    return int(quotient)

print(divide(10,5))yy

Now you try it!

Don't copy and past. Type the code yourself!

PreviousLesson 13. Looping With forNextLesson 15. Importing Modules

Last updated 3 years ago