The Basics of Coding
An over-dramatic representation of coding: prompt by the author, image generated by Dall-E

The Basics of Coding

To understand software, as this series of articles endeavors to explain, we must understand at least the basics of what exactly coders do: what basic constructs are used to create, what problems coders need to solve in order to be effective, and what tradeoffs are made along the way.

Programming Languages

Code is written in one of many different programming languages. Like normal spoken languages, one may express the same thought or idea in many different programming languages, so deciding what language to use for a given program based on matters of practicality or taste.

A few of the most popular, widely used programming languages include:

  • C: The C language, along with a close cousin called C++, is used in a wide variety of software, especially where the highest performance is needed, including operating systems, web browsers, and video games. Another variant called Objective C is popular for writing iOS apps.
  • Java: Has become most popular for writing software to be deployed on servers, where retaining compatibility across a number of different operating systems is important, without sacrificing performance for most tasks. Java is also used for creating most Android apps.
  • Python: One of many “scripting” languages that optimizes for speed of development. Python is popular for beginners, due to the code being readable and easy to understand, but it is also growing in popularity due to heavy use in the scientific community, where it can be used for machine learning problems.
  • Javascript: Arguably the most widely used programming language today, due to it being the only language that most web browsers will execute within the browser itself. Note that it bears no relation to Java - the name Javascript was chosen for maximum marketing benefit when the Java language was at peak popularity in the 1990s.

Any popular language offers a wide set of libraries that help developers more easily perform common tasks like formatting data, connecting to networks, displaying graphics on a screen, and much more.

Syntax

Code is written as text on a computer, and is then either “compiled” or “interpreted”, depending on how the particular language works. We can overlook the details of what that means and refer simply to a set of code “running”. Code is a set of commands, or “statements” to a computer: do this, then do this, then do this, and so on. The rules that a language sets forth for how the contents of each statement should be interpreted are it’s syntax.

Let’s take another look at the simple program from the last chapter, to show some of the syntax rules for the Python language:

inputFromUser = input("Enter some text: ")
output = inputFromUser.upper()
print(output)        

In this simple example, the program runs from top to bottom, and a computer running it executes each of the 3 individual statements one after the other. The first statement in this program as executed proceeds like this:

“Run the input function, displaying Enter some text: on the command line, then assign the value entered to the inputFromUser variable.”

Instead of my natural language description of what steps to perform, Python uses its own syntax to indicate that certain operations should take place. Parentheses “( )” after the name of a function indicate that the enclosed data should be sent to that function. An equal sign “=“ means that the variable on the left should be assigned the value on the right. On the second line, the dot character “.” executes the upper function on the value of the inputFromUser variable. While some languages attempt to actually use some kind of natural syntax, most programming language syntax uses symbols for common operations, making a tradeoff in favor of terseness and precision at the expense of pure readability.

Control Flow

The flow of the program above is simple - a set of statements executed in exact order. When you run the program, you will get one and only one result: the value you specify on the command line will be printed out in upper case.

But most programs are more complex than this. Depending on the data entered into the program, different things will happen. If this button is clicked, this happens. If this data equals some other data, some other thing happens. In order to create these kinds of branches in our code we need to use what is called control flow.

By using an if statement, we can create a branch of code that will only execute if a certain condition is true. Let’s modify our Uppercase program with an if statement:

inputFromUser = input("Enter some text: ")
if inputFromUser == "forbidden":
   print("Sorry, I can not uppercase that word")
   exit()
output = inputFromUser.upper()
print(output)        

Now, the output of the program can be different depending on what I enter on the command line. If I enter the text “forbidden”, the program refuses to show me the upper case version and it exits. I could add as many different if statements as I want into this program, introducing all sorts of silly rules and different paths depending on different conditions.

The syntax that Python uses for if statements is this. The statement must begin with the keyword “if”, and then immediately following is a condition. The condition must be something that can evaluate to either True or False. In our case here, the condition is True if and only if the user enters the exact text “forbidden”, otherwise the condition is False. If the condition evaluates to True, then the indented statements immediately following the “:” are executed, otherwise they are skipped. I could have written any number of other statements, including other if statements, but as soon as I call exit(), the program quits. If I didn’t call exit(), then the program would continue on to print the uppercase version of the text I entered.

You may have noticed that in the condition, I use a double equals sign. That isn’t a mistake, and is one example of how easy it can be to introduce unintended bugs into code. Python (like many other programming languages), uses double equal signs to test for equality, while a single equals sign assigns a value to a variable. All programming languages, even those with reputations for being easy to program in, have “gotchas” like this that you simply have to learn along the way.

Loops

We’ve looked at example programs that do a series of steps exactly once, but in order to do some work a number of times, we need to use what is called a loop. To remember the term, think in terms of driving. An if statement is like deciding whether to turn left or right, while a loop is driving around the block a number of times.

Loops are especially useful when dealing with lists, like when there is some work we want to do with every element in a list. For example, we can use a loop to make every element in a list uppercase, like this:

listOfWords = [“this”, “is”, “my”, “inside”, “voice”]
for word in listOfWords:
   print (word.upper())        

The first line creates the list, and populates it with 5 example strings. The second line defines my loop, and it creates a variable called “word” that I can refer to within the loop. I can have any number of statements within the loop, and in this example each element in the list is printed as uppercase. Note that I could have called the variable whatever I want, but I used the best descriptive name for the variable I could think of, since I know that each element in the list is a word.

In order to create a program that keeps running in perpetuity (rather than doing some set of work and then quitting), we need to use a different kind of loop called a “while” loop. The loop will keep the program running until we explicitly exit the program:

while True:
  command = input("Enter a command: ")
    if command == "exit":
      print("Exiting!")
    exit( )
  print ("Sorry, I don't understand that command. Try again!")        

The first line of the while loop may be a bit confusing at first. A while loop must specify a condition that evaluates to True or False. But you can supply the value “True” itself, which means the loop will keep running. Until we exit out of the program, that is, by calling the exit( ) function builtin to Python when the user enters the right command. We could extend this program by adding any number of additional commands that the program responds to, by adding additional if statements that check if what was entered by the user matched any known value.

Let’s look at one more example of a loop that does something more useful, like calculating sales tax from a bill of goods:

priceOfGoods = [55.00, 10.88, 11.25, 9.99, 20.25]
taxRate = 0.075
total = 0
for item in priceOfGoods:
  pricePlusTax = item + (item * taxRate)
  total = total + pricePlusTax
  print(total)        

The first three lines should be familiar. We create three variables to hold the list of prices, an example tax rate of 7.5%, and the total, which starts at 0. The loop is a for loop like we’ve seen already, but with this loop we refer to the variables that are created outside of the loop. The tax rate is used to calculate the total price plus tax of each individual item. The way to read line 5 is from inside the parentheses out. So we calculate the amount of tax for each item by multiplying the rate against that price, then add that amount to the base price of the item.

The 6th line of the program refers to the total variable twice. Let’s step through this carefully. The first time through the loop, total = 0. The pricePlusTax value for the first item will be 59.125. So the value for total is set to 0 + 59.125. The second time through the loop, the existing total is 59.125, and pricePlusTax value for the second item is 11.696, so the new value for total is set to 59.125 + 11.696. This pattern repeats as the program progresses through the rest of the list, until the total value is complete.

Let’s pause here for just a moment. If the code is starting to get overwhelming, don’t worry. Getting used to any coding syntax takes time. The example above solves a problem that anyone with basic math fluency could do, but the way that humans solve this kind of problem is different. Even if we write down what seems like every step of a calculation like this on paper, we probably skip some something, or take some mental shortcut, because we can do these kinds of basic calculations in our heads. But with software, a computer doesn’t know how to take those shortcuts. When we write code we have to spell out exactly what we want the computer to do in exacting detail. But once we write a bit of code, like our loop that calculates sales tax, we can use it on any size data we want - a list of 5 items or 5 million, with assurance that we can get the right result.

Functions

There is just one more important basic programming concept to cover: functions.

Every programming language will provide some set of built-in capabilities. Python provides many of these capabilities through a set of built-in functions. We’ve already encountered a few built-in Python functions in our example programs:

  • print

Sends some text to the command line.

  • input

Accepts text from a user on the command line.

  • upper

Returns an uppercase version of a given string.

  • exit

Quits the running Python program.

Python includes a few dozen builtin functions that help with common things like finding absolute values of numbers (the abs function), determine the length of something (len), reverse something (reverse), and more.

Functions are a way to organize a chunk of code that it can be useful elsewhere. The Python built-in functions solve very common problems - so common that the language designers took on the responsibility of maintaining the code that exists within those functions. In order to use the reverse function, I don’t have to know how the code within the function works, all I need to know is what data to pass to that function, and what data (if any) the function returns to me. As long as the function does what it is supposed to do (it has no bugs, and I don’t misunderstand what it does), then I have saved a bunch of time by not having to write that code myself.

The data that a function accepts are called the functions arguments. The input function, for example, accepts a single argument. To use the function, I pass in a string. The syntax for that is to put the value for that argument in the parentheses: input(“Enter some data:”). Depending on how the function works, it may or may not require that a value be provided for the argument. The input function makes the argument value optional, so if I don’t pass in anything, when the function is called no text is sent to the command line to prompt the user what data to enter. Certain programs that use output might want this behavior, so having it optional makes sense.

Functions may take no arguments, one, or multiple, and they may or may not return any data too. The input function does return data. It returns whatever text the user enters on the command line. Other functions like print don’t return anything.

Besides using the set of built-in functions, we can also write our own functions too. As programs get bigger and bigger, organizing code becomes a challenge, and grouping code into functions is one way to help. Also, if there is some work that we want to do multiple times in a program, writing a function can help remove duplication. And finally, we can write functions that are packaged into our own code libraries that are then re-used in entirely different programs. Let’s look at how to organize the sales tax code from the last section into a function:

def addTax(priceOfGoods):
  taxRate = 0.075
  total = 0
  for item in priceOfGoods:
    pricePlusTax = item + (item * taxRate)
    total = total + pricePlusTax
  return total

goods1 = [55.00, 10.88, 11.25, 9.99, 20.25]
goods2 = [1100.00, 12500.00]

print(addTax(goods1))
print(addTax(goods2))        

The first seven lines of this Python program are a function that adds tax to the set of prices that are provided to the function as an argument. The keyword def (short for “define”) is used to declare, or create a function. The function is given a name, “addTax”, and one argument is specified. The body of the function, which means the code contained within the function that does all the work, uses the argument in the same way as our code in the previous example used the variable. But instead of printing the value, at the end of the function the function returns (using the return keyword) the end result to the caller. This means that whatever code executes or “calls” the function will get a value back, and it can decide what to do with it: print it, use it in some other calculation, write it to a database, or whatever else. You can imagine that a program that deals with sales tax may have many different such uses within one program, and that is a great example where it makes sense for that program to group that calculation into one function.

The rest of the example shows how we can use the function. Two different lists of example values are created and assigned to the goods1 and goods2 variables, and then those values are passed in to the addTax function. Notice that the calls to the function are contained within the call to the print function. What’s that about? This is one kind of short cut that you’ll see all over the place in code - because I don’t care about doing anything with the returned value except for printing it to the command line, I don’t actually need to create a variable. Instead, I can call the function, and the return value is passed right into the print function as its argument. Just remember when reading code like this to go from inside the parentheses out.

Putting it All Together

We’ll look at one more program in this chapter, a number guessing game that builds on everything we’ve learned.

import random

secretNumber = random.randint(1,100)
numGuesses = 0
hasWon = False
while numGuesses < 7:
   guess = int(input("Guess a number between 1 and 100: "))
   if guess == secretNumber:
       print("You guessed right!")
       hasWon = True
       break
   elif guess < secretNumber:
       print("Your guess is too low! Guess again:")
   elif guess > secretNumber:
       print("Your guess is too high! Guess again:")
   numGuesses = numGuesses + 1

if hasWon:
   print("Congratulations, you won the game!")
else:
   print("Sorry, the correct number was:")
   print(secretNumber)        

This program is a bit longer, but it mostly includes coding constructs we’ve seen already. There are a few new things, though:

  1. The first line imports a Python package, the “random” package, which has useful functions for generating random data. We can then use one of those functions to generate a random integer between 1 and 100 on line 3.
  2. The while loop will run through (or “iterate”, as it is commonly referred to in code) up to 7 times. We ensure that the loop only runs 7 times by incrementing the numGuesses variable by 1 at the end of each loop iteration.
  3. We’ve seen if statements already, and this program introduces two related statements. Within the loop, we use an if/elif statement. Read elif as “else if”, and it will make more sense. If the user guesses right, they win! Else if the guess is too low, tell them that. Else if the guess is too high, tell them that instead. The final statement in the program specifies what to print out if the user has won (if the hasWon variable is True), else what to print out if they have not won.
  4. Within the if statement in the while loop, you’ll notice one line that just says “break”. What is that? The keyword break is used to break out of a loop. We use it here because if the user has guessed the number, we don’t want to continue through the loop any further.

In just 20 lines of code, we have created a meaningful program, not just an example to demonstrate a coding concept. Just with some variables, simple input and output, looping, and some simple control flow, we’ve created a game that, while simple, is real software. You could take those same patterns and create any number of text-based games with 100s of different dialog options and many different paths. Likewise, the same basic concept underlies games and other programs that have far more sophisticated graphics.

Is That It?

Coding needn’t be hard, and you don’t have to know all the different possible keywords or libraries in order to understand the simple concepts behind it all. Those concepts are, in effect, the grammar of programming, while all the libraries and functions that help you solve specific problems are the vocabulary. To understand how to program, you really only need to know the grammar, while to do it fast (and in order to make a career out of it) you need to be fluent with the vocabulary.

The other chapters in this book cover some of the remaining core concepts that you’d need to know in order to either developer or understand most Software: persisting data, building user interfaces, sending and receiving data over a network, and more. But there is a class of software that is doesn’t require much more than what we’ve covered here. Especially within company IT systems, much of the code written does little more than transform data from one format to another (in order to integrate systems together). The hardest part of this kind of work is often understanding the data itself, and then transforming it can be done using coding techniques we’ve covered in this chapter: reading data in, looping through variables and applying rules (if/then logic), and then outputting the new data.

If you are proceeding to write more software yourself, then don’t be intimated. Many books or tutorials overwhelm with details about edge cases and lists of functions or libraries. Rather, pick a problem you’re trying to solve first. You can try jumping right into coding, or if that isn’t your learning style, at least you’ll have a better sense for what grammar or vocabulary you need to learn about more.

Loving the way you boiled down the complex ideas into super digestible bits. Maybe consider diving deeper into a specific programming language next, it could really level up your skill set. Have you thought about which sector you'd want to apply your coding skills in? Tech startups, big companies, or maybe your own project? It's cool to see someone make coding this accessible. Keep it up! What's your dream project once you've mastered coding?

回复
Tom Ortega

Building Remixing Reality: A system to make useful tools and fun games in AR, featuring your favorite brands

11 个月

Bravo! Nicely done, but I expected nothing less from you!

Phillip Li

I help professionals in Tech (Microsoft, Amazon, Google etc...) and Consulting (EY, Deloitte etc...) | Financial Advisor | Director

11 个月

Learning the basics is the first step you should take to master it. Thank you for sharing this!

Andrew Fox

Chief of Staff, Product Development @ Flywheel

11 个月

Love the "grammar" and "vocabulary" analogy. I think Chomsky's work around Minimalist Program can somewhat apply here as folks are attempting to better understand the frameworks required of a coding language. For me, understanding the grammar or syntax of a coding language was/is certainly the first step with the vocabulary being a close second

要查看或添加评论,请登录

Alan Lewis的更多文章

  • Understanding How Data Works

    Understanding How Data Works

    This article is part of my series explaining how software works to a non-coder audience. Data is stored by software…

    2 条评论
  • How Software Works

    How Software Works

    I’m sitting in a coffee shop, waiting for a flight home, and I'm surrounded by software. I’m using a writing app on my…

    7 条评论

社区洞察