Raymond Daugherty

Functions in Python

Functions have notorious been a difficult concept to grasp for me as a self-taught “developer” (I use that term loosely because I feel I am FAR from any type of skilled developer). So, In order for me to better understand how functions… ummm… function(?), I ‘ll try my best to explain how I think functions process information. Here’s the “How to change a tire” program I’m going to use to explain the process:

#Display the instructions for each step individually.
#Ask the user to press Enter to see the next step.

def main():
    
    startup_message()
    input("Press ENTER to begin.")
        
    step1()
    input("Press ENTER to continue.")
        
    step2()
    input("Press ENTER to continue.")

    step3()
    input("Press ENTER to continue.")

    step4()
    input("Press ENTER to continue.")
    
    step5()
    input("Press ENTER to continue.")
    
    step6()
    input("Press ENTER to continue.")
    
    step7()
    input("Press ENTER to continue.")
    
    step8()
    input("Press ENTER to continue.")
    
    step9()
    print("You can now change a flat!")

def startup_message():
    print('This program will explain how to change a flat tire.')
    print('We\'ll assume you\'ve already taken the spare and jack out of the trunk, or wherever it\' being held.')
    print()
# The step1 function displays the instructions
# for step 1.
def step1():
    print('Step 1: Secure the other tires with someting to prevent them from rolling forward or backwards. This could be a large rock, a tires stop, or anything else that will keep the car from rolling forwards and backwards.')
    print()

# The step2 function displays the instructions
# for step 2.
def step2():
    print('Step 2: Using the jack handle, or a lug wrench, loosen the lug nuts on the flat tire.')
    print('** It\'s not necessary to loosen them completely, you simply want to "unstick" them so that removing them doesn\'t put much pressure on the car once it\'s on the jack.')
    print()

# The step3 function displays the instructions
# for step 3.
def step3():
    print('Step 3: Once the lug nuts are slightly loosened, slid the jack under the frame of the car, and using the jack handle slowly jack the corner of the car with the flat tire up so that the flat tire is only about an inch off the ground.')
    print('** Make sure to position it under the frame, and not the metal shell of the car, since putting it then the shell will cause the shell to bend once you begin to lift the car with the jack.')
    print()

# The step4 function displays the instructions
# for step 4.
def step4():
    print('Step 4: Once the flat tire is no longer touching the ground, Use the lug wrench or jack handle to finish removing the lug nuts from the flat tire so you can remove the flat.')
    print('** When you remove the flat, it\'s always best to lay the flat tire on it\'s side and slide it half under the side of the car that\'s off the ground. This will ensure that if the jack fails for any reason, the car doesn\'t slam onto the ground causing severe damage to the wheel base and the under carriage.')
    print()

# The step5 function displays the instructions
# for step 5.
def step5():
    print('Step 5: With the flat tire off the car, simply slide the spare onto the exposed lugs of the wheel.')
    print('** You may need to jack the car up a little to fit the spare onto the hub, since the air in the spare makes the height of the spare a little taller than the flat. If this is the case, very gently jack the car up, little by little until you can slide the tire on.')
    print()

# The step6 function displays the instructions
# for step 6.
def step6():
    print('Step 6: Once the spare is on the hub, hand tighten the lug nuts back onto the rim. Try to get them on as far as you can, and use the lug wrench or jack handle if necessary, but don\'t tighten them down with the car still on the jack.')
    print('** It\'s best to put the lug nuts on in a star shaped pattern. This allows the tire to mount evenly on the hub and will help you with putting on the latter lug nuts.')
    print()

# The step6 function displays the instructions
# for step 7.
def step7():
    print('Step 7: Once the lug nuts are somewhat on the tire, remove the spare tire from under the car, and very gently lower the car down to the ground.')
    print()

# The step8 function displays the instructions
# for step 8.
def step8():
    print('Step 8: When the car is firmly on the ground, use the lug wrench or jack handle to tighten the lugs once again. This time, try to tighten them as much as you can without using too much unnecessary effort, like standing on the lug wrench to tighten them.')
    print('** It\'s best to tighten the lug nuts on in a star shaped pattern. This allows the tire to mount evenly in this final step.')
    print()

# The step9 function displays the instructions
# for step 9.
def step9():
    print('Step 9: Once all of the lug nuts are firmly tightened down, remove the objects you used to stop the car from rolling, stow the flat somewhere in your car, and drive carefully someplace where you can get your original tire repaired.')
    print()

# Call the main function to begin the program.
main()

First, every line that begins with a “#” is simply a comment in Python. I usually place these types of comments after the line of code that the comment refers to, but that’s just a style of commenting that works for me. For this one though, I wanted to first state what I was trying to do. You can think of this as pseudocode. It just helps me organize my thoughts.

The way I wrote the code is considered to be in the “top-down” method. This means that the way the program runs is from the top to the bottom, executing code with each step. I’m not going to go into detail with every function created for this program, since a lot of it is repetition, so I’ll do the first two, and the last one.

It opens with defining the “main()” function.

def main():

The reason why we define it here is so that when it’s “called” at the end of the code, the program goes to the top and starts processing all of the information that’s been read. And since we aren’t passing any arguments to it, it simply gets followed with the “()”.

Following the defining of the “main()” function, we have indented function calls, “startup_message(), “step1()”, etc… in order.

    startup_message()
    input("Press ENTER to begin.")

This tells the program the order that each of these functions needs to be processed, and to process them one at a time, requiring the user to press “Enter” in order to move onto the next step with the input() function. (The input() function is a standard function in Python, and just reads input from the keyboard in this example.)

When the startup_message() function is called, Python skips to where that function is defined, and processes the information that is output by THAT function, and displays it to the user.

def startup_message():
    print('This program will explain how to change a flat tire.')
    print('We\'ll assume you\'ve already taken the spare and jack out of the trunk, or wherever it\' being held.')
    print()

This process is repeated through Step 9.

At the very bottom of the page, we call the “main()” function.

# Call the main function to begin the program.
main()

This is what tells Python to go to the top and process the program since we’ve already coded all of the necessary information the program needs to run successfully. Notice that this isn’t indented. Since it’s not indented, we’re telling Python that it needs to run this block of code independently of the function definitions.

As Python goes to the top and reads each line of code, and the user progresses through the program, each step is printed out to the user describing how to change a tire. This is a very basic example of how functions process information, and as I progress through learning Python, I’m sure I will find better ways to write such a repetitive program in a better format.

The Fibonacci Sequence in Python

The Fibonacci Sequence. For those that don’t know what it is, it’s a sequence of numbers where you start with the number 1, duplicate it, then add the 2 previous numbers together to make the third. for example: 1+1=2, so the first 3 digits of the sequence are 1, 1, 2. There are a lot of references to this sequence in mathematics. From the “Golden Ratio” to fractals, you could easily fall down this wormhole. My favorite example is from TOOL, in the song “Lateralus”. I still find it absolutely amazing how math came into the making of this song, so here’s the link if you want to see it in action: https://www.youtube.com/watch?v=lsQDSw5AAUU

Mathematically, the sequence is F(n)=F(n-1)+F(n-2).

So, back to what I was doing with Python. I decided to use this sequence as a learning tool for Python. It incorporates the range() function to count steps requested by the user via the input() function at line 1.

end = int(input("How far do we go? "))
fibNumber=0
firstStep=0
secondStep=0
thirdStep=0
total = 0

for x in range(end):
    if (fibNumber == 0):
        print("1", end=", ")
        firstStep = 1
    elif(x != (end - 1)):
        print(fibNumber, end=", ")
    else:
        print(fibNumber)
    thirdStep = secondStep 
    secondStep = firstStep 
    firstStep = secondStep + thirdStep
    fibNumber = firstStep
    total+=int(fibNumber)
    
total=(total+1)-fibNumber
print("The total is:", total, end=".")

Since this is my first iteration of the Fibonacci Sequence in Python, I’m sure as I study it more, I will find better, faster ways to produce the expected outcome, but much like the sequence itself… one step at a time.

EDIT: Well, it didn’t take much time. Looking at how other programmers have coded the same sequence, I’ve found better ways to do it.

# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How far do we go? "))
n1, n2 = 0, 1 # first two terms
count = 0
total = 0
nth = 0

if nterms <= 0: # check if the number of terms is valid
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
        if n1 != 0:
            if (count+1) == nterms:
                print(n1, end=" ")
            else:
                print(n1, end=", ")
        total += n1
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1
print("\n Total of the sequence: ", format(total, ","))

Solidity

Day 2 …

Today we’ll be following the tutorial from CryptoZombies, which is basically a fun was to learn Solidity, the code used to create smart contracts that use the Etherium Blockchain.  It looks to be similar to Javascript (which I’m already familiar with, but will absolutely make JS a part of these 100 days), so I’m actually excited to learn this new language. Time to start…

 

Version Pragma

All solidity source code should start with a “version pragma”. This defines what version of Solidity your application runs on, and helps you avoid any future compiler updates that may break your app. For this, I’ll compile the smart contracts with any compiler version in the range of 0.5.0 (inclusive [identified by the “>=”]) to 0.6.0 (exclusive[identified by the “<“]). It’s best to think of it like “I’ll take anything that’s greater than or equal to version 0.5.0, but not version 0.6.0.

It looks like this:

pragma solidity >=0.5.0 <0.6.0;

This should always be the first line in your code. You can think of this like the HTML declaration for standard HTML pages.

 

Opening a Contract

Opening a contract is just Solidity’s way of creating a function. Just as Javascript creates functions with:

function nameOfFunction {
function does something;
}

a Solidity contract is set-up the same way. For example:

contract exampleOfContract{
do the contract thing;
}

 

Variables

Variables, like in any other programming language are simply holders of small bits of data. You can set variables to store any number of data types, like booleans and integers (numbers). With Solidity, you set variables like so:

uint theUnsignedInteger = 123;

Piecing the above code together, we would get a contract like this:

pragma solidity >=0.5.0 <0.6.0;  //1. Solidity version here
contract Example {
  // This will be stored permanently in the blockchain
  uint theUnsignedInteger = 123;
}

That’s it for Day 2. Only 98 more to go.

#100-Days=Of-Code

JSON

Day 1 …

I know I’m not supposed to move too fast, but I’m going to do my best to stick to doing what I can, when I can. It may be over an hour a day, or (sadly) may be under an hour. My goal with Day 1 is just to start, so here goes…

Today with be a day on managing NPM packages. NPM (or Node Package Manager) is a way for developers to include packages, supplied by other developers, into their projects. These packages can have a variety of applications, from simply formatting time to much larger implications. Since I’m going to be using FreeCodeCamp for this process, I’ll do my best to link what I can, when I can.

One thing to note: In order to use NPM, you need to have NodeJS and NPM installed. If you don’t want to install NodeJS and NPM, you can use Glitch for the testing for FreeCodeCamp. Hopefully I’ll be able to do a post about installing both NodeJS and NPM in the future, but for now, Google and Glitch are your friends. 🙂

Node Modules

When starting a new project, NPM creates a folder that it saves all of the modules (packages) in, called “node_modules”. It also creates a JSON file, which allows you to define what modules you’d like to use in your project. You could include all of the available modules for every project into this folder, but that would make the overall directory cluttered and very large. That’s what I plan on keeping each project separate, and only install the necessary modules for that project.

Package.json, the Core of Any Node.js Project or npm Package

So, I took the above “heading” right from FreeCodeCamp. As much as I tried to find a clever way of rewording it, they actually summed it up in the best possible way. Without the package.json file, no NodeJS or NPM package would work, and the file is actually fairly simple to understand.

In a nutshell, you can define different values through what’s called a key:value pair. Using this notation, you can define the author of the project –

 "author":"Raymond Daugherty",

a description –

 "description": "This is the beginning process for learning NPM packages with FreeCodeCamp.com.",

even a version number for your project –

 "version": "1.0.0",

One of the things to pay attention to here is the use of commas. You have to make sure that all comma separated elements are followed appropriately with a trailing comma.

The important part of the package.json file is the “dependencies” section.

In the dependencies section, you’ll define the dependencies in an array format. You can think of this as a “key:value” pair that houses other “key:value” pairs. For example:

 "dependencies": {
"moment": "2.14.0"
}

The above code tells your NodeJS application to include the Moment package when the app is complied, and use the version 2.14.0. Versioning is important here, since on the slight change a newer version breaks your app, you can always move to a previous build.

When it comes to versioning, it’s best to remember this rule:

"package":"MAJOR.MINOR.PATCH",

The “MAJOR” is considered a change that may affect previous versions of the package. Going from version 2 to version 3 is considered a major upgrade, and can break things. (I’m lookin’ at you jQuery….)

The “MINOR” are simple updates that shouldn’t break the previous installations.

The “PATCHES” are simply bug fixes that needed to be made without groundbreaking changes to the code.

Keeping packages updated

In order to keep packages up-to-date, NPM has some special characters you can use. By using the tilde (“~”) in front of your package number, this allows NPM to update the package to it’s most recent bug fixes.

 "dependencies": { "moment": "~2.14.0" }

This doesn’t cause the package to upgrade to the latest version, but if any bugs get squashed by the developer, this will help apply the fix in the background.

Using the carot (“^”) in front of the version number allows NPM to update the package to the latest MINOR release. This will update the package but shouldn’t cause any issues with previous installations.

 "dependencies": { "moment": "^2.14.0" }

Finally, you simply remove packages by removing their call from the package.json file. Keep in mind, doing this may also break your app if your calling that dependency somewhere, so always be on the look-out.

That’s it for Day 1. Only 99 more to go.

#100-Days=Of-Code

#100DaysOfCode – The Beginning

Welcome to my introduction to #100DaysOfCode.

I’ve decided to take this challenge for a plethora of reasons, one of them trying to find a way to use the word “plethora”. Anyway…

The core reason for attempting to conquer this challenge is to better myself. I’ve been a Web Designer / Front-End Developer / Back-End Developer since the late 90’s, when the internet was building into the monster it is today. Back then, my enthusiasm to learn everything possible was endless. Database management? No problem. PHP for 1 client? Sure. ColdFusion for dynamic, database driven sites with tons of capability requests? Bring it on!

But then after so many years, even the most enthusiastic of us seem to start losing the fight with information overload. With so much rattling around in my skull, it’s difficult to learn new languages just due to sheer numbers. PHP, Coldfusion, Javascript, CSS, HTML5, Bootstrap, Ruby on Rails, Angular, NodeJS… so many languages and frameworks that it’s super easy to get the feeling of drowning. But how can you stay up-to-date with current technologies without feeling lost on a raft in the middle of an ocean of information? Add onto that, after 44 years, I’m doing what I can do get the degree I’ve never been able to get.

But I need to stop bouncing around from language to language, falling into the tutorial Hell all of the programmers have experienced before, and just sit down, commit myself and dedicate my time to developing something that I can be proud of.  Competing in today’s world , where it seems that everyone and their mom knows languages that I could only dream of learning, I need to do something to make my experience relevant in the job market. I’m sure I could run circles around new graduates if I can just commit to learning new languages, and get back that thing that used to actually cause joy in my life.

I know I may miss a day here and there, though I’m going to do my absolute best to change the habit of coming home after my web design job and staying as far away from a computer as possible. I’m prepared to do what I can to move forward.

P.S. : Yes, I know I code for a living, but IMO, it’s HTML and my main “job” is graphic design. The coding challenge will help me maintain my roots in coding and even though I could use my job as an excuse to have coded for an hour that day, I promise I won’t. 😉

Clean Code

Regular Clean coding
Even though you have a deadline, always keep code clean.If you have clean code, you'll save time in the future altering and updating code.

10:1 reading/writing code.

  1. Be responsible for the quality of your code. Even though your client, boss or someone else purchases your talents, it is your responsibility to write clean code.Your code defines your talent and abilities.
  2. Use meaningful names. Don't use vague variable names.
  3. Write code that expresses intent. When you write functions or programmatic steps, write it in a way that if someone else were to look at your code without knowing the language, they could still tell what your code is trying to do.
  4. Code should speak for itself, but if you write comments, keep them short and to the point. When you write a comment, it's another piece of the puzzle that you need to keep updated when you update your code. The biggest drawback of comments is that if another developer comes in and alters your code, they may not update your comments, and anyone else that reads the code afterwards may be misled since the comments are no longer valid. Keep them simple, brief and if you update something, keep the comments current.
  5. Keep code cleaner than you found it. When you get the chance, try to look at the surrounding code and clean it up. This doesn't just mean code formatting, this also means that if you see a variable that could be expressed with a better name, and is easily updated, update it and add your comment.
  6. Bob Martin - Single responsibility principle. When a function, method or class does 1 thing, does it well, and only does it. Don't try to write anything that tries to accomplish more than 1 goal. That will leave the next programmer confused and lost when they have to work on it in the future.
  7. Write tests. Not in the sense of pen and paper, but test on how the user may use the code. Unit tests are a great way of testing too. Write the test on paper, write the code, then test it. Rewrite code until it completes the test successfully.
  8. Work in short cycles. Trying to complete a huge project in one sitting will often lead to burnout, confusion or encourage the writing of sloppy code just to get it done. Stop. Take a break. Go for a walk. When you come back, come back refreshed, focused and eager to make something better. I've learned this through studying. Using the Pomodoro technique of studying for 15 minutes and taking a 5 minute break has been phenomenal in my studying and comprehension.
  9. Independent Architecture - There are good practices that you can see across other applications that can inspire you to create a more stable, reusable foundation of different elements. For example, don't constantly rewrite the same function on individual pages. Find a way to create the function as a separate file, and simply include that file in any framework you create.
  10. Practice. The more you code, the better you become. The more you code, the more ideas to write better code come to you. Yes, it's frustrating. Yes, it'll seem like there's not end to the projects. But often if your write clean code and find a better way in the future, you can go back to the previous clean code you wrote and apply the new style with little to no effort.

The-Beginning

The Beginning

Hey all (or Hi to the 1 person who actually stumbled across this with searching for something else and accidentally clicked on this link).

This is my first attempt at creating a blog. I’ve thought about doing one for years (since I’ve been a web designer for over a decade so it should have been easy), but now’s the time for me to dive in head first.

Why am I doing this? Well, to be honest, because I need to hold myself accountable for sticking with my studies, and to keep a record of my progress (and snippets) to see how my skills grow and develop. This idea came from a YouTuber, Network Chuck (https://youtu.be/b4PK1NFcRTM?t=244) who dropped the idea of keeping track of ones progress, not just to show the world that you can do a specific task, but to show understanding through teaching it to someone else. I found this to be an amazing idea, but also to keep a memorial to the hard work and dedication that I put in to better myself.

In the book “The Pragmatic Programmer”, Andrew Hunt tells of a programmer who would carry around a plastic duck, and debug their code by explaining the code, line by line, to the plastic duck. If he wasn’t able to explain it effectively, then it was too complicated and he would go back and rewrite the code. This very often fixed any issues that were happening in his code.

As Einstein once said, “If you can’t explain it to a six year old, you don’t understand it yourself.”

I’m a huge fan of the Astrophysicist Richard Feynman, and even when he died in 1988, there was a note on the top of his chalkboard that read “What I cannot create, I do not understand.” I want to create, understand and help others who struggle as much as I do.

My goal is also to help others get started in something that I am very passionate about. I love the feeling of creating something from nothing, and seeing it work in the way that I intended, and not settling for something that works “good enough”.

So, enough rambling. It’s time I start kicking up dust, put my nose to the digital grindstone, and begin this endeavor. I think I’ll start in the most basic way: Writing clean code…