☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 3 : Processing : Functions : Programmer-Defined Functions

Programmer-Defined Functions

Subscribe Contact


Contents

Overview

So far, our programs have contained all their code in one overall block in one Python (.py) file. That's ok when programs are small; however as programming problems grow more complex, trying to manage hundreds or thousands of lines of code in one large block becomes challenging. Also, more extensive programs tend to have segments that are repeated unnecessarily. One way we can improve this is through writing functions.

We can visualize the difference between the programs we've been writing with all of the code in one place versus programs that are made more modular by writing and using functions:



Figure 1: Program with one large code block


Figure 2: Program with modular functions

We have already used some functions, some built into Python, such as print(), len(), etc. These functions contain code to perform a task, such as printing to the screen or returning the length of an object. We don't know how they work internally and don't need to know, we just learn how to use them and interact with them, and that's it. We can write and use functions like any built-in functions.

Goals of Writing Functions

When writing functions, there are specific goals we try to achieve, as outlined here:


Goal Description
Abstraction In programming, we hide or abstract the details and implementation of programming tasks inside functions. In doing so, programmers can use functions to the benefit of their programming tasks without the need to fully understand all of the details of implementing those functions.
Modularity As depicted in the image above, rather than a single large block of code, functions allow us to modularize our code so that related functionality is kept together. In addition, modularity can dramatically improve the maintainability of the code.
Reusability Well-designed functions can often be used throughout a software system and even across many systems. The ability to call a function from many points in a system, or multiple systems, is reusability.
Reduce Complexity Again, referring to the image above, the program comprised of one large block of code can be challenging to maintain. Imagine a single Python file with 2 million lines of code. Its complexity would be very high, and it would be difficult to maintain. Functions allow us to create building blocks that are individually much smaller and easier to maintain, thereby reducing complexity by consolidating functionality into those blocks. This approach allows programmers to focus on one task at a time.
Reduce Redundancy A program with a single large block of code also suffers from redundancy. If a particular task is needed many times throughout that extensive program, the code to accomplish that task is often repeated many times. By moving that task into a function, the implementation code is only needed once, and then that function can be called as many times as needed throughout the program.
Testability Testing a single large block of code can be very difficult because of the complexity and scope of the number of lines of code. If a system is modularized with functions, each function can be tested individually, and any problems can be mitigated in that function without affecting other code in the system.
Team Development As software systems grow, development is often spread out across many programmers rather than relying on one person. Functions are very beneficial in team development because programmers can each focus on their tasks in the system. In this kind of development environment, communication is essential so that everyone on the team knows about the joint development efforts.
Code Sharing In addition to the goals and features of functions outlined above, functions can be shared with other developers within a company or worldwide. Python is widely supported by many developers across the world and its core development and the development of functions are encouraged for sharing across the Python community.


Types of Functions

In Python, there are different types of functions. As mentioned above, Python has built-in functions available for our use and provide many features to simplify our programming tasks. We can call these functions from anywhere in our code. Calling a function means instructing the computer to run (execute) that function. As Python programmers, in addition to using the built-in functions, we can also create Void and Value-Return Functions to achieve the goals outlined above. These two types of functions provide different approaches to modular code.

Void Functions allow us to write code that performs a specific task and then terminates, with no return interaction between the Void Function and the calling program. An example of a void function might be a function that prints a standardized header at the top of all output for a program. Calling that function would cause the header to print, and there is nothing to return to the calling program.

Value-Return Functions allow us to write code that accepts values (arguments), performs actions on those values, and can return resulting values to the calling program. An example of a value-return function might be a function that calculates employee bonuses based on a set of values our calling program passes to the function; the function performs the calculations based on business rules and then returns a result (the bonus amount) to the calling program.

We will explore both Void Functions and Value-Return Functions throughout the rest of this page.

Coding Standards for Functions

There are some rules in Python for naming functions and also there are common conventions that many developers follow to improve consistency. The rules are similar to naming variables, for example, function names cannot include spaces, the first character of the name must be an alphabetic letter or an underscore (_), and the rest of the name of a function can only contain alphabetic characters, digits 0 thru 9 or underscores, function names are case-sensitive and you cannot name functions the same as any Python keyword.

Common conventions for naming functions, like variables, suggest using descriptive names that relate to the purpose of the function. For example, naming a function x, while valid from the rules perspective, is not descriptive. Instead, use a name that helps the reader identify the purpose of the function, like print_header, calculate_interest, update_tax_record, etc.

Creating & Calling a Void Function

Creating a Void Function

The general form for creating a Void Function is as follows:

def function_name([var_1, var_2, ... var_n]):
    statement_1
    statement_2
    .
    .
    statement_n

Code Details:

Calling a Void Function

The general form for calling a Void Function is as follows:

function_name()

Code Details:

Concept: Arguments & Parameters

These two terms are often used interchangeably. However, they are not the same. Arguments are the values we pass to a function, while parameters are the values the function receives. The confusion is often caused by the thought that the value is the same number, string, etc. But, we use the two terms to differentiate our perspective for the coding of either the calling program code or the function coding.


Example 1

In this example, we write a function to print a report header. This is a simple example of a Void Function that we could use any number of times in a program without writing the code for the header more than once. It is also an excellent example of how to make something that will remain consistent, that is, it will always print the same header information in the same format.

# Functions
def print_header():
    print("\n" + "-" * 80)
    print("S u m m a r y  R e p o r t")
    print("\n" + "-" * 80)

# Main (calling) Program
print_header()

Output

----------------------------------------
S u m m a r y  R e p o r t
----------------------------------------

Code & Output Details:

  • Code Line 2: Function definition (def) of a Void Function called print_header().
  • Code Lines 3 thru 5: Lines of code inside the Void Function.
  • Code Line 8: In the Main Program, the function is called by the function name and a set of parentheses.

Functions create modular units of code separate from the main program, as depicted in the diagram below. The print_header() function is called from the main program, its code is executed, and program flow returns to the main program on the next line after the print_header() function call.



Example 2

In this example, we write a flexible function that will print dashes to create a horizontal line. The number of dashes is adjustable by using a parameter specified in the function signature, so the programmer can call this function and limit the number of dashes they want to print on the screen.

# Functions
def print_line(num_dashes):
    print("-" * num_dashes)

# Main (calling) Program
print_line(10)
print_line(20)
print_line(40)
print_line(80)

Output


----------
--------------------
----------------------------------------
--------------------------------------------------------------------------------

Code & Output Details:


Example 3

This example is an enhancement of Example 2 above. This function also prints characters to the screen to make a horizontal line and the number of characters that are printed is based on a parameter provided by the calling program. The enhancement is that in addition to the number of character parameters, we've added a second parameter to allow the calling program to specify what character to print and how many times to print that character. Compare the code for this example and Example 2 to see how we have enhanced this function.

# Functions
def print_line(print_char, num_chars):
    print(print_char * num_chars)

# Main (calling) Program
print_line("-", 10)
print_line("~", 20)
print_line(".", 40)
print_line("=", 80)

Output

----------
~~~~~~~~~~~~~~~~~~~~
........................................
================================================================================

Code & Output Details:

Example 4

This example combines our print header and print lines functions above to demonstrate that we can call functions from main programs and other functions. This means functions can call functions. In this example, our main program calls the print_header() function, which calls the print_line() function. This is a good example of the use of functions, that is, it demonstrates that many functions each doing their tasks can be combined to complete more complex work. This concept is widely used in software development.

# Functions
def print_line(print_char, num_chars):
    print(print_char * num_chars)

def print_header():
    print()
    print_line("-", 40)
    print("S u m m a r y  R e p o r t")
    print_line("-", 40)
    print()

# Main (calling) Program
print_header()

Output

----------------------------------------
S u m m a r y  R e p o r t
----------------------------------------

Functions can be called from the main program or any other function as well, as shown in this example:



Code & Output Details:

Creating & Calling a Value Function

Creating a Value Function

The general form for creating a Value Function is as follows. Notice that it looks the same as the Void Function with the addition of a return statement.

def function_name([var_1, var_2, ... var_n]):
    statement_1
    statement_2
    .
    .
    statement_n
    return return_var

Code Details:

Calling a Value Function

Here are a couple of examples of general forms for calling a Value Function:

General Form 1:

[local_var] = function_name([var_1, var_2, ... var_n])

General Form 1 Code Details:

General Form 2:

print(["string"] + [cast_function(]function_name([var_1, var_2, ... var_n])[)] + ["string"])

General Form 2 Code Details:

Example 1

In this example, we write a Value Function to calculate a simple math formula. This is an example of a Value Function that we could use any number of times in a program without writing the code for the calculation more than once. The function will return the result of the calculation to the calling program, which we can then use as needed.

# Function
def calc_formula(n):
    # Formula: n * n**3
    ret_value = n * n**3
    return ret_value

# Main (calling) Program
formula_value = calc_formula(4)
print("The result of the formula "
"calculation is " + str(formula_value))
print("We could have put the function "
"call directly in a print statement "
"like this: " + str(calc_formula(4)))

Output

The result of the formula calculation is 256
We could have put the function call directly in a print statement like this: 256

Code & Output Details:

Example 2

In this example, we combine three Value Functions to format several strings together and return a single formatted string to the calling program. Notice that the three functions are format_phone(), print_line() and customer_card(). The customer_card() function is the primary function and the only one called from the main program. The other two functions are called by the customer_card() function.

See the Execution Flow section below for more information about how the execution of this program works. Also, work through the Code & Output Details below for a line-by-line explanation of the program and its output.

# Functions
def format_phone(phone_no):
    formatted_phone_no = ""
    if len(phone_no) != 10:
        formatted_phone_no = "Invalid Phone Number"
    else:
        formatted_phone_no = "(" + phone_no[:3] + ")" + phone_no[3:6] + "-" + phone_no[6:]
    return formatted_phone_no


def create_line(print_char, num_chars):
    return "\n" + (print_char * num_chars) + "\n"


def customer_card(fn, ln, addr1, addr2, city, st, zip, phone):
    card = ""
    card = card + create_line("-", 40)
    card = card + fn + " " + ln + "\n"
    card = card + addr1 + "\n"
    if addr2 != "":
        card = card + addr2 + "\n"
    card = card + city + ", " + st + " " + zip + "\n"
    card = card + format_phone(phone)
    card = card + create_line("-", 40)
    return card


# Main Program
first_name = input("Enter customer first name: ")
last_name = input("Enter customer last name: ")
address1 = input("Enter customer Address Line 1: ")
address2 = input("Enter customer Address Line 2: ")
city = input("Enter customer City: ")
state = input("Enter customer State: ")
zip_code = input("Enter customer Zip Code: ")
phone_number = input("Enter customer phone number (digits only): ")

print(customer_card(first_name, last_name, address1, address2, city, state, zip_code, phone_number))

Sample Run & Output

Enter your first name: Bob
Enter customer last name: Smith
Enter customer Address Line 1: 1234 Nowhere Street
Enter customer Address Line 2: Apt 9999999999
Enter customer City: Noplace
Enter customer State: UT
Enter customer Zip Code: 84999
Enter customer phone number (digits only): 1112223333

----------------------------------------
Bob Smith
1234 Nowhere Street
Apt 9999999999
Noplace, UT 84999
(111)222-3333
----------------------------------------

Code & Output Details:

Execution Path

As a reminder, the execution path is the path through a program that the Python interpreter takes based on our code. So, a program with just a set of print statements, with no decisions or loops, would be a straight execution path from line 1 through the last line of the program. As our programs become more complex, with decisions and loops, and now with functions, it can become increasingly challenging to understand the execution path.

The following list outlines the execution path of Example 2 above. Study the list of steps and the subsequent diagram of the code, along with the code, sample run, output, and code details provided above.

The diagram below can be confusing at first. Still, if you follow the code details above while reading through the execution path steps above, the diagram depicts how the execution path operates in this example.

Practice Problems

Problem 1

Write a Python program with a main program that prompts the user for their full name (stored in one variable). Also, implement the print_line() Void Function is shown in the examples above. Write a new function that will print the user's name between two lines (see sample output below). Pass the user's name to the new function as a parameter. In the new function, call the print_line() function, print the user's name and then call the print_line() function again.

Sample Run & Output:

Please enter your full name: Bob Smith

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Full Name: Bob Smith
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



Problem 2

Write a Python program that calls a Void Function from inside of a for loop so that the function is used repeatedly. In the main program, declare three variables, and use one as a for loop index variable. In each iteration, set the other two variables as multiples of the index value. Then, call a function inside the loop and pass the three variables to that function. Print well-formatted output lines in the function that show what adding the three values together produces (see the sample output below).

Sample Run & Output:


0 + 0 + 0 = 0
1 + 2 + 4 = 7
2 + 4 + 8 = 14
3 + 6 + 12 = 21
4 + 8 + 16 = 28
5 + 10 + 20 = 35
6 + 12 + 24 = 42
7 + 14 + 28 = 49
8 + 16 + 32 = 56
9 + 18 + 36 = 63
10 + 20 + 40 = 70
11 + 22 + 44 = 77
12 + 24 + 48 = 84
13 + 26 + 52 = 91
14 + 28 + 56 = 98
15 + 30 + 60 = 105
16 + 32 + 64 = 112
17 + 34 + 68 = 119
18 + 36 + 72 = 126
19 + 38 + 76 = 133



Problem 3

Write a Python program that prompts the user for two numbers and then displays the result of adding, subtracting, multiplying, and dividing those two numbers. Write this program with functions as follows:

  • Your main program should declare a list to store the user-entered values.
  • Your main program should call a Void Function to display user instructions.
  • Your main program should then call a Value Function that prompts the user for two numbers and return their entries as a list (store the return list in the list declared above).
  • Your main program should then call a Void Function to manage the calculations. Pass the list to this function.
  • The calculations function should call four individual Void Functions, one for each type of calculation as listed above.
  • The calculations function should pass the list to each of the four functions.
  • The four individual functions should calculate their value using the user-entered numbers in the list and print an output line indicating the calculation result.
  • All of the program's output should be well-formatted, as shown below.

Sample Run & Output:


=============================================
This program asks you for two numbers
and then displays the results of adding,
subtracting, multiplying and dividing
those two numbers.
=============================================
Enter your first number:  2
Enter your second number: 4
=============================================
Results:
=============================================
2 + 4 = 6
2 - 4 = -2
2 * 4 = 8
2 / 4 = 0.5
=============================================
Thank you!




 





© 2023 John Gordon
Cascade Street Publishing, LLC