1  Python Basics

Hello, welcome to the crash course on Python basics! This section will get you very quickly introduced to Python in order for you to follow along with the book.

There are numerous Python tutorials that will help you fully understand the programming language. Some resources I personally have found very helpful (general python learning, various topics):

None of the links above deal with accounting but will provide depth in explanations of the code you will see here.

1.1 Variables

Variables are names to store data. If you have a long variable name, use underscores (_) to keep the words together. For long numbers you can use the underscore to act like a comma, but do not use a comma like you would in Excel.

Some simple rules for variable names:

  • variables can’t start with a dot or have a dot in the name (.)
  • variables can’t start with a number or special character
Show the code
variable_one = "variable string"

variable_1 = 1
variable1 = 1

Variables are essential in programming, you make a variable in order for you to use again and again. Variables are limited in where they can be accessed (used) in a program based on the function scope (scope ?) but allows for reprodicibility within your program.

1.2 Strings

Strings are typically letters but anything can be a string, as a string is anything inside ” ” or ’ ’ quotation marks. Strings are stored inside a variable which you get to name whatever you want. Note: some words are reserved and cannot be used; while, if, break, else, etc. If you use a reserved word you get an error and will not be able to run your code.

Show the code
stringy = "pasta noodles"

chartered_accountant = "Jane Doe"

string_number = "899"

Everything that is inside ” ” is considered a data type of string, this is important to remember as you can get errors or get output you are not expecting if you call (use) some functions on a string data type variable meant for a numerical data type.

Show the code
a = "5"
b = "10"

y = a + b

The output for y is not 15, as that is numerical addition, instead you will get concatenation of strings a and b, resulting in “510”.

1.3 Numbers (int and float)

Accounting mainly deals with numbers with decimals, known as floats (floating point decimal numbers) and integers (numbers without decimals). Using these data types is easy to do, just create a variable and store the numerical value to that variable.

Show the code
x = 6754
y = 122.78

z = x + y 
z
6876.78

The value of z is 6876.78. In a Python file (.py) you will need to use the print() function to see the answer, but using a Jupyter Notebook, you can simply add x and y and get the output printed.

1.4 String formatting

To print out the variables and calculations, you need to use the print() function. String formatting allows for reusable code and simpler code to write. Learning it now will help build the skill. Formatting uses the syntax f" " inside a print function with { } to store the variable name.

For rounding numbers when you want to only show numeric values that have limited decimal places you use the .format() function without using the f”” inside the print function.

  • inside the {:.2f} means 2 decimal places format, the number can be 1 or more
  • for output numberical values that are long, you can use {:,} which means to add commas to the numbers
Show the code
accountant_name = "Jane Doe"
office_expenses = 105_900.7688128

print(f" Hello Python Accountant {accountant_name} ")
print(" The office budget is ${:.2f}".format( office_expenses ))
print(" The office budget is ${:,}".format( office_expenses ))
 Hello Python Accountant Jane Doe 
 The office budget is $105900.77
 The office budget is $105,900.7688128

1.5 Lists

Python lists are very useful and are also known as arrays (when using the NumPy library).

  • can store various data items, duplicates are allowed which is important to know.

  • Lists can be empty and the values can be changed (mutable).

IMPORTANT TO KNOW :

  • every list, dictionary, set and string all start at 0 zero not 1, start counting at 0 or use n - 1 to get the correct index value.
Show the code
accounting_list = ['shareholders equity',233, True,"liabilities", 99]

print( accounting_list )
['shareholders equity', 233, True, 'liabilities', 99]

1.5.1 Array slicing

To get specific elements in the array list you can use slicing. To get the 2nd item (element) from the list, remember n - 1 for index number.

Show the code
accounting_list[1]
233

To get the last element in the array list, you can use -1, which means the 1st one from the end. If you wanted the second last element, -2, and so forth.

Show the code
accounting_list[-1]
99

1.5.2 Change element in list

Say we want to change ‘liabilities’ to ‘purchases’, we use the index of element we want to change and assign the new variable.

Show the code
accounting_list[3] = "purchases"
accounting_list
['shareholders equity', 233, True, 'purchases', 99]

1.5.3 Get more than 1 element

If you are interested in only a few or specific elements in a list you can specify the indexes of the elements of the list. In this example, we want the first to the second elements.

Show the code
accounting_list[0:3]
['shareholders equity', 233, True]

1.5.4 List length

Knowing how long a list is, how many elements that are inside the list object is very useful to know for using in for loops.

Show the code
len( accounting_list )
5

1.5.5 Add elements to list

Python lists can be modified by adding to the list array. Since we store all of the elements into a variable we can use the name of the list and call functions on that variable such as .append() to add to an existing list.

In this example we just want to add ‘income_sheets’ to the list. Note: if you call this function more than once, Python will keep adding this one variable to the list.

Show the code
accounting_list.append("income_sheets")
accounting_list
['shareholders equity', 233, True, 'purchases', 99, 'income_sheets']

1.5.6 Join lists

If you have one list array and want to join or merge them together, you can use .extend() function.

Show the code
sheet1 = ["Accounts payable","debts receivable","credit payable"]
sheet2 = ["balance sheet","assets & liabilities"]

sheet1.extend(sheet2)

print( sheet1 )
['Accounts payable', 'debts receivable', 'credit payable', 'balance sheet', 'assets & liabilities']

1.5.7 Delete element

You can delete an element from a list array, using the pop() function which by default removes the very last element in an array, but if you provide the index number it will remove that element.

In this example we will remove the element “True” from index 2. Note: Python will keep deleting elements from your list if this function is called repeatedly.

Show the code
accounting_list.pop(2)
accounting_list
['shareholders equity', 233, 'purchases', 99, 'income_sheets']

1.5.8 List for loops

for loops are functions that will iterate over a Python object such as a list or dictionary, dataframe or even a string. For loops are important to know and are essential for becoming efficient in programming.

If you have a list of assets and quickly want to print them out to see what they are or perform a math function for loops are what to use.

In this example we want to loop through the numbers 0 to 4, and print out each number. The range() by default understands what the start and end of the range is but could be explicitly defined. If you wanted 1 to 5, range(1,6).

  • Note: “for x in something”, the x can be named just about anything (just not a reserved word in Python).
Show the code
for x in range(5):
    print(x)
0
1
2
3
4

Say we have a list of a client’s assets, and we want it iterate through the list and print them. We want to know the length of the list in order to tell the for loop to stop at the end of the list, this serves 2 purposes: 1) you can modify the list (add or delete elements) and the for loop will keep working, and 2) by knowing the length of the list prevents errors when looping through a list and tries to find an element index that does not exist.

  • range( len( list_name ))
  • index of the loop is needed, hence client_assets[items] which goes through the list array and prints the index location value
Show the code
client_assets = ['boat','house','fancy car','comic book collection','stocks']

for items in range( len( client_assets )):
    print( client_assets[items] )
boat
house
fancy car
comic book collection
stocks

Using for loops is going to be something you will need to understand and get comfortable with in order to make your accounting more efficient.

While loops will be purposefully ignored as they are very easy to mess up and crash your program. You may wish to learn them on your own but I caution you not to unless you have experience coding in Python.

1.5.9 List sorting

You can sort or reverse a list, simply by calling .sort() function and .reverse() on the list variable name.

Show the code
common_assets = ['z item','investments','cash','inventory','supplies']

dividends_paid = [100,1001.1,1020,101,300,301,90,9]

common_assets.sort()
dividends_paid.sort()

print( common_assets )
print( dividends_paid )


# reverse
dividends_paid.reverse()
print( dividends_paid )
['cash', 'inventory', 'investments', 'supplies', 'z item']
[9, 90, 100, 101, 300, 301, 1001.1, 1020]
[1020, 1001.1, 301, 300, 101, 100, 90, 9]

1.6 Tuples

Tuples store data but are immutable and tuples index each element. Say we want to store 3 holiday gift ideas for the office.

Show the code
gifts = ('Subway sandwich gift card',"Starbucks coffee gift card", "Apple iTunes gift card")

print( gifts[2:3])
('Apple iTunes gift card',)

and to loop through the tuple

Show the code
for xmas in gifts:
  print(xmas)
Subway sandwich gift card
Starbucks coffee gift card
Apple iTunes gift card

1.7 Sets

Sets and dictionaries both use { }, but sets are immutable, but elements can be added or dropped. Sets are unordered and not indexed. Sets do not allow duplicates to exist in the set.

In this example we have taxes filed each year, then we append a year after we made our set.

Show the code
taxes_years = {2015, 2016, 2017, 2018}

taxes_years.add(2009)
print(taxes_years)
{2016, 2017, 2018, 2009, 2015}

to remove a tax year

Show the code
taxes_years.remove(2009)
taxes_years
{2015, 2016, 2017, 2018}

we can loop through the set

Show the code
for year in taxes_years:
  print(f"finished with taxes for {year}")
finished with taxes for 2016
finished with taxes for 2017
finished with taxes for 2018
finished with taxes for 2015

1.8 Dictionaries

This book will use data dictionaries extensively, as they are very versatile, easy to use and modify. If you later want to make a data dictionary a dataframe, you can with the help of the Pandas library. Once you have a dataframe created or converted from a data dictionary you can save it as a CSV or other formats.

Data dictionaries are ordered, mutable and have keys and value pairs (‘key’ : ‘value’).

  • dictionaries do not allow duplicates of keys
  • dictionaries are not indexed, grab elements by key or value
  • it is good practice to Pascal_Case or CamelCase your keys (also with everything) as it will help with tab-auto complete and grabbing the key you want

In this example we have some financial information of assets.

Show the code
all_assets = {
  "cash": 3098772.89,
  'inventory': 7886.23,
  "supplies": 56234.56,
  "prepaid_expenses": 14521
}

1.8.1 select key

In this example we want to get the value for cash, so we slice the dictionary and use the key name to get the value.

Show the code
all_assets['cash']
3098772.89

1.8.2 dictionary length

Find out how many elements are in a data dictionary

Show the code
len(all_assets)
4

1.8.3 all items

If you wanted to print out all the items in a dictionary, use .items() function

Show the code
all_assets.items()
dict_items([('cash', 3098772.89), ('inventory', 7886.23), ('supplies', 56234.56), ('prepaid_expenses', 14521)])

1.8.4 dictionary keys

If you want to know the keys for the dictionary in order to use them for a function, use the .keys() function.

Show the code
all_assets.keys()
dict_keys(['cash', 'inventory', 'supplies', 'prepaid_expenses'])

1.8.5 modify a key

If the key has a value that needs to be changed, you can use the slice and key name method and assign a new value.

In this example we will give a new value for the property key.

Show the code
all_assets['property'] = 788655
all_assets.items()
dict_items([('cash', 3098772.89), ('inventory', 7886.23), ('supplies', 56234.56), ('prepaid_expenses', 14521), ('property', 788655)])

1.8.6 dictionary values

If you just wanted to see the values stored in a dictionary, use the .values() function.

Show the code
all_assets.values()
dict_values([3098772.89, 7886.23, 56234.56, 14521, 788655])

1.8.7 check dictionary

If we had a large dictionary and quickly wanted to check if a specific key exists inside the dictionary, we can use a if statement with in dictionary_name.

In this example we will search if “supplies” exists in the all_assets.

Show the code
if "supplies" in all_assets:
  print(" 'supplies' was found in the dictionary" )
 'supplies' was found in the dictionary

1.8.8 dictionary for loops

As mentioned previously, for loops are very much part of programming, you want to iterate over a list or some data object and do some sort of action along the process. We can iterate over a data dictionary to see what a specific client has for assets and by type.

In this example we will loop through all assets and show that the client is Dunder Mifflin’s assets by type of category.

Show the code
for DunderMifflin in all_assets:
  print(f"Dunder Mifflin assets $ { all_assets[ DunderMifflin]} [{DunderMifflin}]")
Dunder Mifflin assets $ 3098772.89 [cash]
Dunder Mifflin assets $ 7886.23 [inventory]
Dunder Mifflin assets $ 56234.56 [supplies]
Dunder Mifflin assets $ 14521 [prepaid_expenses]
Dunder Mifflin assets $ 788655 [property]

1.8.9 dictionary copy

Once you have a data dictionary, you can make a copy as to make sure you have a safe copy from any deletions or whatever may be the case. You can make copies for a client each quarter and only need to modify a few items instead of starting from scratch. To make a copy of a dictionary, use the .copy() function.

In this example we will make a copy of all_assets and with the new copy we will create a new element and append it to the dictionary.

Show the code
print(f" Original: {all_assets}\n")

assets_2 = all_assets.copy()

print(f" Copy: {assets_2}\n")

assets_2['yacht'] = 1086777

print("....", assets_2, '\n')
 Original: {'cash': 3098772.89, 'inventory': 7886.23, 'supplies': 56234.56, 'prepaid_expenses': 14521, 'property': 788655}

 Copy: {'cash': 3098772.89, 'inventory': 7886.23, 'supplies': 56234.56, 'prepaid_expenses': 14521, 'property': 788655}

.... {'cash': 3098772.89, 'inventory': 7886.23, 'supplies': 56234.56, 'prepaid_expenses': 14521, 'property': 788655, 'yacht': 1086777} 

1.9 Conditionals

You are already familiar with conditionals in everyday life, if x then y. We a;ready used an if statement to check if “supplies” was in the data dictionary. Knowing conditional statements such as If-Else statements are a core part of programming.

  • Equals: a == b
  • not equal: a != b
  • less than: a < b
  • less than or equal to: a <= b
  • greater than: a > b
  • greater than or equal to: a >= b

Note: If-Else statements are where indentation matters.

Show the code
revenue = 110
expenses = 120

if revenue > expenses:
  print("you have money")
else:
  print("expenses !")
expenses !

There is a way to add to this simple example, we can add an elif which means else-if. The condition block of code will check if revenue is greater than expenses else if another condition is true do something, else neither conditions were true.

Conditionals can be as long as needed, however using a bunch of if statements is not advised, as the computer will check only for the specific condition that makes it true and breaks out of the code block. Using an If-Elif-Else block ensures that all qualifying conditions are checked.

Show the code
revenue = 110
expenses = 110

if revenue > expenses:
  print("you got money")
elif revenue == expenses:
  print("breakeven point")
else:
  print("those expenses!")
breakeven point

1.10 Functions

Functions are so important to know! Functions will help you be more efficient and more productive.

If you are doing a task more than 3 times, it is wise to make that task into a function. Accounting has so many mundane routine calculations that learning to make functions will make accounting faster.

  • In Python, a function starts with def followed by a function name you provide, () then a : and your code is indented underneath the ‘def function_name():

  • Inside the function_name( arguments ) . These arguments are what you pass into the function, you can pass in an array or a dictionary . You do not have to pass in anything.

Note: in many Python documentation guides you will see ‘func’ for naming a function, along with ‘foo’ and ‘bar’

Let us create a simple function that prints out a message.

Show the code
#-------------------- function block
def my_function():
  
  print("Hi, my first function!")
  
#-------------------- 

#- outside of the function block
#- call your function by typing the name of it
my_function()
Hi, my first function!

Indentation matters when dealing with conditionals and functions, you will get errors if your code is not properly indented.

1.10.1 Function with argument

Once you get the handle of how functions work and how to call them, next is to pass in the function a argument, a data object or a string that is then used by the function. Just like in math textbooks f(x) you pass in x as a number then the “f” function makes a calculation.

In this example we will pass in job in the function “()” where function arguments go.

Show the code
def my_function( job ):
  print(f"your job is {job}")
  

# call the function and pass in a argument
my_function("Accounting")
your job is Accounting

As the function exists you could pass in a number or another data type object, you will want to make your functions explicitly define what data type is expected for the argument as to avoid errors.

1.10.2 function net income

This function will be calculating the net income, but this time the arguments in the function will be explicitly defined as int meaning integer data types. Passing in a float would still work as it is type numeric.

  • you can enforce data types into your arguments so if you want only numeric values and not strings to be entered into your function, use arg_name : int , arg_name : float. This helps reduce code errors.

  • if you type: net_income(expenses= “900”, revenue=78) == ERRORS

Show the code
def net_income(revenue: int, expenses: int):
    # formula for net income
    net = revenue - expenses
    
    print(f"Net (loss) income = $ {net}")
    
    
#-- outside function block
net_income(revenue= 187568, expenses= 167812)
Net (loss) income = $ 19756

When calling the function you do not have to type the argument, just the value it is expecting, however it is good to type what arguments you are using for a function.

1.10.3 Function with a list

We can make a function that will loop through the list and then print out when the item was checked.

This example will have a list of common assets which will be passed in the function number_crunch as an argument. The for loop will start from length of list -1, as Python is zero indexed.

Show the code
def number_crunch( assets ):
  
  L = len(assets)
  print(f"Number of assets = {L}\n")
  
  #--------------------------- for loop
  for wealth in assets:
    print(f" {wealth} ... checked")
  #---------------------------
  
#--
common_assets = ['investments','cash','yacht','cabin','vacation home']

number_crunch( common_assets )
Number of assets = 5

 investments ... checked
 cash ... checked
 yacht ... checked
 cabin ... checked
 vacation home ... checked

1.10.4 Function with a dictionary

As mentioned in the dictionary section, dictionaries are very pliable data objects and are great as an option to store data. Data dictionaries are very similar to JSON data objects, so it is helpful to be used to working with them and passing them into functions.

This book will heavily use data dictionaries for function arguments, these function will pull values from specified keys to be used in calculations.

In this example we will have a dictionary for assets which will be passed in the function the_count.

Show the code
assets = {
    "cash": 300322.78,
    "inventory": 7886.23,
    "supplies": 56234.56,
    'prepaid expenses': 14560
} 


def the_count( acc_dict ):
    
    #------ convert dictionary to a list
    dict_list = list( acc_dict.values() )
    #-- for loop of values
    for num in dict_list:
        print(num)
    
    # sum the assets
    s = sum( dict_list )
    print("sum of assets = $ {:,}".format(s))

# use the assets dictionary from above 

the_count( assets )
300322.78
7886.23
56234.56
14560
sum of assets = $ 379,003.57

This function used a few tricks, the dictionary argument was converted to a list data object, which stores the dictionary values. Once the dictionary list was created and had all the values, a for loop was used to iterate over the list. The dictionary list was then summed using the sum() function and stored in a variable ‘s’ and printed out.

The conversion of a data dictionary to a list is needed for any future looping, you can’t loop through a dictionary.

1.11 Python Classes

Python classes are not considered a basic level topic, it is complicated and easy to get confused. I include it as a means of showing that you can bundle all of the functions in one file and then extract the specific functions you need. You need to understand how functions work and be comfortable with them before you attempt to work with classes. A class object has inheritance, it can store a data object(s), have multiple functions (which are called methods inside a class) and can be imported to another file.

Class objects start with a capital letter, this is convention and is to signify that this is a class and not a regular function. I will show what a simple class object looks like, but will let you learn more about them on your own.

Show the code
class Simple_class:
  def __init__(self, name, age): # class self referencing arguments
        self.name = name
        self.age = age    # self.name = name  declares the argument 
        
  # class property
  class_property = "simple_class: property value"
    
  #-- class method
  def number(self):
    x= 1898
    print(x)
    
    
# ----- important
# similar to calling functions but this is called INSTANTIATE or 
# creating an OBJECT INSTANCE of the class

obj = Simple_class("Python", 28) # pass in values for class arguments

# now that there is an object we can get properties from the class
obj.class_property
'simple_class: property value'

Call the class method number() to get a number

Show the code
obj.number()
1898

To aid in understanding, Python has a library called Math (comes with Python installation) and it has many math functions that you would typically want to use. When you want to square root a number you need to use Math.sqrt(), the square root function is inside the class called Math. In order to have access to this math function or any other you need to import the library into your python file. The “obj.number()” is same type of code used to get the math function from the class Math.

Class inheritance is the next thing to learn when learning about class objects, which is not the focus of this book. As shown, class objects are very helpful for storing multiple or doing multiple things at once.