Show the code
= "variable string"
variable_one
= 1
variable_1 = 1 variable1
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.
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:
= "variable string"
variable_one
= 1
variable_1 = 1 variable1
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.
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.
= "pasta noodles"
stringy
= "Jane Doe"
chartered_accountant
= "899" string_number
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.
= "5"
a = "10"
b
= a + b y
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”.
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.
= 6754
x = 122.78
y
= x + y
z 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.
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.
= "Jane Doe"
accountant_name = 105_900.7688128
office_expenses
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
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 :
n - 1
to get the correct index value.= ['shareholders equity',233, True,"liabilities", 99]
accounting_list
print( accounting_list )
['shareholders equity', 233, True, 'liabilities', 99]
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.
1] accounting_list[
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.
-1] accounting_list[
99
Say we want to change ‘liabilities’ to ‘purchases’, we use the index of element we want to change and assign the new variable.
3] = "purchases"
accounting_list[ accounting_list
['shareholders equity', 233, True, 'purchases', 99]
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.
0:3] accounting_list[
['shareholders equity', 233, True]
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
.
len( accounting_list )
5
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.
"income_sheets")
accounting_list.append( accounting_list
['shareholders equity', 233, True, 'purchases', 99, 'income_sheets']
If you have one list array and want to join or merge them together, you can use .extend()
function.
= ["Accounts payable","debts receivable","credit payable"]
sheet1 = ["balance sheet","assets & liabilities"]
sheet2
sheet1.extend(sheet2)
print( sheet1 )
['Accounts payable', 'debts receivable', 'credit payable', 'balance sheet', 'assets & liabilities']
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.
2)
accounting_list.pop( accounting_list
['shareholders equity', 233, 'purchases', 99, 'income_sheets']
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).
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.
= ['boat','house','fancy car','comic book collection','stocks']
client_assets
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.
You can sort or reverse a list, simply by calling .sort()
function and .reverse()
on the list variable name.
= ['z item','investments','cash','inventory','supplies']
common_assets
= [100,1001.1,1020,101,300,301,90,9]
dividends_paid
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]
Tuples store data but are immutable and tuples index each element. Say we want to store 3 holiday gift ideas for the office.
= ('Subway sandwich gift card',"Starbucks coffee gift card", "Apple iTunes gift card")
gifts
print( gifts[2:3])
('Apple iTunes gift card',)
and to loop through the tuple
for xmas in gifts:
print(xmas)
Subway sandwich gift card
Starbucks coffee gift card
Apple iTunes gift card
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.
= {2015, 2016, 2017, 2018}
taxes_years
2009)
taxes_years.add(print(taxes_years)
{2016, 2017, 2018, 2009, 2015}
to remove a tax year
2009)
taxes_years.remove( taxes_years
{2015, 2016, 2017, 2018}
we can loop through the set
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
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’).
Pascal_Case
or CamelCase
your keys (also with everything) as it will help with tab-auto complete and grabbing the key you wantIn this example we have some financial information of assets.
= {
all_assets "cash": 3098772.89,
'inventory': 7886.23,
"supplies": 56234.56,
"prepaid_expenses": 14521
}
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.
'cash'] all_assets[
3098772.89
Find out how many elements are in a data dictionary
len(all_assets)
4
If you wanted to print out all the items in a dictionary, use .items() function
all_assets.items()
dict_items([('cash', 3098772.89), ('inventory', 7886.23), ('supplies', 56234.56), ('prepaid_expenses', 14521)])
If you want to know the keys for the dictionary in order to use them for a function, use the .keys() function.
all_assets.keys()
dict_keys(['cash', 'inventory', 'supplies', 'prepaid_expenses'])
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.
'property'] = 788655
all_assets[ all_assets.items()
dict_items([('cash', 3098772.89), ('inventory', 7886.23), ('supplies', 56234.56), ('prepaid_expenses', 14521), ('property', 788655)])
If you just wanted to see the values stored in a dictionary, use the .values() function.
all_assets.values()
dict_values([3098772.89, 7886.23, 56234.56, 14521, 788655])
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.
if "supplies" in all_assets:
print(" 'supplies' was found in the dictionary" )
'supplies' was found in the dictionary
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.
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]
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.
print(f" Original: {all_assets}\n")
= all_assets.copy()
assets_2
print(f" Copy: {assets_2}\n")
'yacht'] = 1086777
assets_2[
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}
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.
a == b
a != b
a < b
a <= b
a > b
a >= b
Note: If-Else statements are where indentation matters.
= 110
revenue = 120
expenses
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.
= 110
revenue = 110
expenses
if revenue > expenses:
print("you got money")
elif revenue == expenses:
print("breakeven point")
else:
print("those expenses!")
breakeven point
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.
#-------------------- 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.
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.
def my_function( job ):
print(f"your job is {job}")
# call the function and pass in a argument
"Accounting") my_function(
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.
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
def net_income(revenue: int, expenses: int):
# formula for net income
= revenue - expenses
net
print(f"Net (loss) income = $ {net}")
#-- outside function block
= 187568, expenses= 167812) net_income(revenue
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.
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.
def number_crunch( assets ):
= len(assets)
L print(f"Number of assets = {L}\n")
#--------------------------- for loop
for wealth in assets:
print(f" {wealth} ... checked")
#---------------------------
#--
= ['investments','cash','yacht','cabin','vacation home']
common_assets
number_crunch( common_assets )
Number of assets = 5
investments ... checked
cash ... checked
yacht ... checked
cabin ... checked
vacation home ... checked
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.
= {
assets "cash": 300322.78,
"inventory": 7886.23,
"supplies": 56234.56,
'prepaid expenses': 14560
}
def the_count( acc_dict ):
#------ convert dictionary to a list
= list( acc_dict.values() )
dict_list #-- for loop of values
for num in dict_list:
print(num)
# sum the assets
= sum( dict_list )
s 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.
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.
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
= "simple_class: property value"
class_property
#-- class method
def number(self):
= 1898
xprint(x)
# ----- important
# similar to calling functions but this is called INSTANTIATE or
# creating an OBJECT INSTANCE of the class
= Simple_class("Python", 28) # pass in values for class arguments
obj
# 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
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.