Learning To Code – Acquiring Knowledge And Developing A Skill

Get Results: coding
Get Results: coding

As part of my own journey of self improvement, and the subsequent creation of this website, I’ve worked at putting many of the sites teachings into practice. It’s made a huge difference to my business, my relationships and my general outlook on life.

As part of this process, I’ve opened myself up to doing new things. One of these new things has been learning to code.

Historically I’ve convinced myself that I’m not the type of person to be a coder, and have failed to be able to get into it. I now realise this to be a coping strategy and an attempt to not have to take responsibility. Kind of saying to myself “If god hasn’t designed me to be a coder, I guess he knows best”. This allows me to psychologically move on to something else.

However, I’m now a little wiser and certainly more self aware, I can admit I’ve been closing myself off to the challenge.

I’m now open to the challenge and the surprising thing is, I’ve really enjoyed studying it. There is so much to learn it can be overwhelming, but also really exciting, with regards to the headroom for learning and the future possibilities for coding.

The key skill to programming is the ability to solve problems. I like solving problems, as well as helping people, so coding is a good fit for me personally as it aligns with my core purpose.

So where to begin? After doing some initial research, and asking a couple of programmer friends of mine (who have subsequently become mentors), I came to the conclusion Python would be a good starting point. I like the idea of data mining , deep learning, AI etc and Python ticks many of these boxes. It’s also a high level programming language, which means it operates at a higher conceptual level, and this really appeals to me.

I realised that web based applications would also be possible, but figured learning more about JavaScript and PHP would be worth investigating. I was informed by one of my mentors that it’s relatively easy to pick up a second language once you have one under your belt, and this has subsequently proved to be the case.

I scoured the internet, particular Youtube to find easy to follow tutorials. Not having anything of a coding background, I found some of the terminology rather difficult to come to terms with, but  with plenty of patience and determination, I’ve been able to power through these challenges.

I figured it best to learn the basic building blocks of the language, which I’ve detailed below, this isn’t designed to be a comprehensive list, but to give you an idea of what is involved in the learning process. It also helps me crystalise my learning, because I’m a firm believer than if you can’t explain it simply, you don’t understand it well enough.

Hopefully you have gained some insight from my experience, and don’t shy away from learning new skills, I’m 50 years old and prepared to learn a completely new skill set at my age. It’s never too late.

The important thing to remember is not to get overwhelmed, or try to run before you can walk. Be patient, understand the fundamentals well, before progressing. Play with and enjoy the learning experience for it’s own sake, and not for what you will gain at the end. It’s about the journey, not just the destination.

If you’re not particularly interested in coding, you don’t need to read this post any further.

Learning the fundamentals of Python

I’m not going into the details of installing Python, there are many resources online detailing the exact process, other than saying you input  your code into Idle, which comes along with the Python installation.

“#” is a comment, it’s not part of the code, but allows you to add important notes to help readability and explain what you’re trying to do on each bit of code.

Variables

A variable is simply a pointer to something in memory.

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The syntax is such that the operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

So “myVariable” in the example below is the variable name, it should have no spaces and not start with numbers. variable names can only include a-z, A-Z, _, and 0-9. Other special characters are not permitted.

myVariable = "Hello World"

# this is a comment, and not part of the code. If you want to print the result to the screen do the following..
print(myVariable)
another_name = "Hello World" 
print(another_name)

Both the above examples print out “Hello World” to the screen. The variable name can be anything you want it to be, but make sure it’s descriptive enough so you and anyone else can understand the code at a later date.

Values can include strings (including sentences) which appear inside “”, numbers (including integers, floats, complex number) , lists which appear inside [], tuples () or directories {}, and we’ll cover these data types later. Here are a few examples

randomNumber = 400 
print(randomNum)
randomList = ["money", 43, "red", "UB40"]
print(randomList)
randomTuple = ("money", 43, "red", "UB40")
print(randomTuple)

Functions

A function is a block of reusable code that is used to perform a single, related action. Functions are convenient for reusing, without having to write the code out again and again later in a program.

The syntax for functions can be seen below; start with “def” and are followed by the function name (you choose what) and parentheses  ( ).

The code block within every function starts with a colon : and is indented. The indentation is very important, it will not work otherwise. Indenting code is done by pressing space bar 4 times on new line.

The bottom line below “calls” the function.

def bitcoin_to_sterling(btc):
    amount = btc * 3714.76
    print(amount)
bitcoin_to_sterling(10) #this line calls the function

# this function replaces btc with 10 which is multiplied by 3714.76 = 37147.6
def greet_user(username):
# Display a simple greeting
    print("Hello, " + username.title() + "!")
greet_user('mike') #this line calls the function

# this function prints out "Hello Mike"

Conditionals : if – elif -else

Conditional statements are common among programming languages and they are used to perform actions or calculations based on whether a condition is evaluated as true or false. If then else statements or conditional expressions are essential features of programming languages and they make programs more useful to users.

x = 14 
y = 14
z = 5

if x < y:
    print("X is less than Y")
elif y < x:
    print("Y is less than X")
elif z > x:
    print("Z is greater than X")
else:
    print("Y and X are the same and Z is less")

# prints out "Y and X are the same and Z is less"

Loops

A loop is a programming construct that enables repetitive processing of a sequence of statements. Python provides two types of loops to its users: the “for loop” and the “while loop”. The “for” and “while” loops are interation statements that allow a block of code (the body of the loop) to be repeated a number of times.

# WHILE loop example
condition = 1 # variable
while condition < 10:
    print(condition)
    condition += 1 # just keeps adding 1 until condition is met up to 10 but not including 10
# FOR loop example 
colours = ["red","blue","green","yellow","orange"] # this is a list

# this is for actual FOR loop
for colour in colours:
    print(colour)

Lists

We’ve used a list in the previous example for loops

A list is a data type that can be used to store any type and number of variables and information. You can manipulate lists, adding, removing, sorting, deleting contents.

# FOR loop example 2 - manipulating the original list

colours = ["red","blue","green","yellow","orange"] # this is a list

# add to end of list
colours.append("pink")

# replace an item on list
colours[0] = "pink"

# insert into list
colours.insert(1, "pink")

# delete from list
del colours[0]
colours.remove("pink")

# sort list
colours.sort()

# reverse list
colours.reverse()

# this is the actual FOR loop
for colour in colours: 
    print(colour)

Tuples

Tuples are fixed size in nature whereas lists are dynamic. In other words, a Tuple is immutable whereas a list is mutable. You can’t add elements to a tuple. Tuples have no append or extend method.

A Tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it.

A Tuple can have any number of items and they may be of different types (integer, float, list, string etc.).

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print(tup1)
print(tup2)

Directory

A directory is like a list but instead of looking up an index to access values, you’ll be using a unique key, which can be a number, string, or tuple. Directory values can be anything but the keys must be an immutable data type. A colon separates a key from its value and all are enclosed in curly braces. Here is the directory structure:

 d={key_1:a, key_2:2, key_3:ab}

menu = {"spam":12.50,"carbonara":20, "salad":15}
print(menu)
print(len(menu)) # 3

Classes and object-orientated programming

Python is an object-oriented programming language, as it manipulates and works with data structures called objects. Objects can be anything that could be named in Python, such as  integers, functions, floats, strings, classes, methods etc. All these objects have equal status in Python. They can be used anywhere an object is required.

You can assign them to variables, lists or directories. They can also be passed as arguments. Every Python object is a class. A class is simply a way of organising, managing and creating objects with the same attributes and methods.

class Employees(object):
   def __init__(self,name,rate,hours):
   self.name = name
   self.rate = rate
   self.hours = hours

staff = Employees("Wayne",20,8)
supervisor = Employees("Dwight",35,8)
manager = Employees("Melinda",100,8)

print(staff.name, staff.rate, staff.hours)
print(supervisor.name, supervisor.rate, supervisor.hours)
print(manager.name, manager.rate, manager.hours)

Opening, Reading and Closing text files

One thing you’re likely to need to do with Python, is manipulate external files, below is some code for  opening, reading and closing text files.

There are many libraries you can call upon to add functionality to your Pyhton code, such as NLTK, which help you deal with other file types, such as HTML (webpages), word documents, PDF files, electronic books etc.

# open and read from text file
f = open("test.txt")
#print(f.read())
# create and save text file
with open("list_created.txt", "w") as output:
 output.write(f.read())
# reading file
f = open("start_days.txt")
print(f.read())
# writing file
title = "Days of the Week\n"
days_file = open("start_days.txt", "r")
weekDays = days_file.read()
new_days = open("new_file.txt", "w")

new_days.write(title)
print(title)

new_days.write(weekDays)
print(weekDays)
# closing file
days_file.close()
new_days.close()
#changing external variables (string/interger combination) from a text file into a
#directory by defining key and value
mydict = dict((k, int(v))
for k, v in (e.split(' = ')
for e in days.split(',')))

Below is a fun little program, I’ve made, putting some of the code learned above, into practice. It interacts with a user, and asks them to input a number guess into IDLE. It’s only basic stuff, but it’s a start, and practice makes perfect.

The inspiration for making this little game came from reading an article about a coder who was asked to do a program that asked a user to guess a predefined number between 1 and 100, and printed out onto the screen after each guess, whether the guess was under  or over the target number.

magicNumber = 20
number = ""

while number != magicNumber:
    answer = input("Pick a number between 1 and 100 ")
    number = int(answer) 

if number > magicNumber:
    print("Too high")
elif number < magicNumber:
    print("Too low")
else:
    print("Well done, you've got it right!")

Doing this little program tweaked my interest in the concept of interacting with a user, so I’ve spent some time learning Javascript as a results, because I am able to interact with website visitors more readily using Javascript. I’ll be posting something in the future to detail my experience with this web based language.

Here is a rather more complex program, which I’ve since rewritten in Javascript.

print("first get a piece of paper, right down two choices for a particular decision you have to make. Under each right down 3 attributes that are important in the decision. Think about the most important to least important. Now lets begin")
define1 = input("Define your first option as suscinctly as possible ")
feature1 = input("define an attribute that is important in this choice ")
weight1 = input("weight it's importance 1-5 , five being more important ")
weightone = int(weight1)
listing1 = input("how important is this attribute compared to other attributes. If it's the most important score it 5, if it's the second most important 4 and so on (least 1-5 most) ")
listingone = int(listing1)
result1 = weightone * listingone
print(define1)
print(feature1)
print(result1)

feature2 = input("define an attribute that is important in the choice ")
weight2 = input("weight it's importance 1-5 , five being more important ")
weighttwo = int(weight2)
listing2 = input("how important is this attribute compared to other attributes. If it's the most important score it 5, if it's the second most important 4 and so on (least 1-5 most) ")
listingtwo = int(listing2)
result2 = weighttwo * listingtwo
print(define1)
print(feature2)
print(result2)

feature3 = input("define an attribute that is important in the choice ")
weight3 = input("weight it's importance 1-5 , five being more important ")
weightthree = int(weight3)
listing3 = input("how important is this attribute compared to other attributes. If it's the most important score it 5, if it's the second most important 4 and so on (least 1-5 most) ")
listingthree = int(listing3)
result3 = weightthree * listingthree
print(define1)
print(feature3)
print(result3)

if result1 > result2 and result1 > result3:
    print("The most imporant attibute is " + feature1)

elif result2 > result1 and result2 > result3:
    print("The most imporant attibute is " + feature1)

elif result3 > result1 and result3 > result2:
    print("The most imporant attibute is " + feature3)

else:
    print("No winner")


define2 = input("Define your second option as suscinctly as possible ")
print("The attribute has already been defined as " + feature1)
weight4 = input("weight it's importance 1-5 , five being more important ")
weightfour = int(weight4)
listing4 = input("how important is this attribute compared to other attributes. If it's the most important score it 5, if it's the second most important 4 and so on (least 1-5 most) ")
listingfour = int(listing4)
result4 = weightfour * listingfour
print(define2)
print(feature1)
print(result4)

print("The attribute has already been defined as " + feature2)
weight5 = input("weight it's importance 1-5 , five being more important ")
weightfive = int(weight5)
listing5 = input("how important is this attribute compared to other attributes. If it's the most important score it 5, if it's the second most important 4 and so on (least 1-5 most) ")
listingfive = int(listing5)
result5 = weightfive * listingfive
print(define2)
print(feature2)
print(result5)

print("The attribute has already been defined as " + feature3)
weight6 = input("weight it's importance 1-5 , five being more important ")
weightsix = int(weight6)
listing6 = input("how important is this attribute compared to other attributes. If it's the most important score it 5, if it's the second most important 4 and so on (least 1-5 most)")
listingsix = int(listing6)
result6 = weightsix * listingsix
print(define2)
print(feature3)
print(result6)

if result4 > result5 and result4 > result6:
    print("The most imporant attibute is " + feature1)

elif result5 > result4 and result5 > result6:
    print("The most imporant attibute is " + feature2)

elif result6 > result4 and result6 > result5:
    print("The most imporant attibute is " + feature3)

else:
    print("No winner")

calculation1 = result1 + result2 + result3
calculation2 = result3 + result4 + result6

if calculation1 > calculation2:
    print("Of the two choices, the one that got the best score, based on your answers was " + define1)

elif calculation1 < calculation2:
    print("Of the two choices, the one that got the best score, based on your answers was " + define2)
else:
    print("There was no overall winner")