1. Computers and Coding

Chapter 0001 2

Stop

Unfinished Chapter!!

I am actively working to complete this eBook, and I haven’t gotten to this chapter yet. In fact, it’s probably just a copy/paste from a similar chapter in my C# book.

In other words, don’t read this yet!

What’s the Point?

  • Understand the role of programming languages, compilers, and interpreters in computer programming

  • Use print() to produce text output

  • Use code comments to document your code

  • Understand the purpose of PEP-8 and style guidelines

Source code examples from this chapter and associated videos are available on GitHub.

Note: This material is nearly identical to the corresponding material in Lo-Fi OOP, the eBook for CIS150AB, and Lo-Fi C#, the eBook for CIS162AD. If you’ve gone through that material before, be sure to at least read the section The Python Programming Language before you move on to the next chapter.


A computer is basically a device that executes a set of commands—and does so very quickly. Because the guts of a computer (a CPU) are kinda like a bunch of light switches—and I mean a BUNCH of light switches—it can only deal with zeros and ones: a switch that is off is "zero," and a switch that’s on is "one."

Never before has the concept of a modern computer been so recklessly simplified. I feel shame.

All of the information a computer handles ultimately has to be represented by some combination of 1s and 0s, which we call a binary (or "base-two") number system.

Imagine that your BFF is in your programming class, but that cruel professor won’t let you sit together. When the professor turns his back, you can use your fingers to send a quick message to your BFF. Holding up your index finger might mean, "meet me in the library after class;" two fingers could mean, "send me a copy of your homework." As long as you agree on what each number means, you could pass along commands or information—it would be like your own little language.

If you’re a sports fan, I have a better analogy. A quarterback and a coach could have a language based completely on numbers. The coach tells the quarterback "22" and the quarterback knows which play to run, because they’ve agreed on what instruction (play) the number 22 means—and there are football teams that do exactly this.

Sending that number to the quarterback as a binary number would be a lot less efficient because the coach would have to say "10110" (which is the binary representation of twenty two) and the quarterback would have to know binary numbers, or have them written on his wrist-band thing as a cheatsheet.

Want to take the analogy one step further? A player standing on the sideline with their helmet on could represent a 1, and a player with their helmet off could represent a 0. Now the coach could just line up five players and tell the 2nd and 5th ones to take their helmets off. The quarterback could look over, see the pattern of helmets (10110) and run play 22.

Okay, that would be the nerdiest football team in history.

Deep Cut

The chapters of this eBook are subtitled using binary to show basic examples of the numbering system: 0001 is, well, 1 in decimal. And 0100 is 4 in decimal. If you’re curious, learn a little more about binary numbers and how computers work.

And how is any of that relevant? Let’s see…​

Remember that a computer can execute commands super fast. Each command, or instruction (like a football play), is represented by a number—a binary number, since that’s the number system the computer uses. The collection of instructions the computer understands is called machine language. Incidentally, there are lots of different machine languages out there. Just like people in different cultures use different languages, different CPU types ("architectures") use different languages.

You could give the computer a set of instructions (a.k.a., a program) if you looked up the binary number for each instruction you wanted to use. Of course, even a simple program requires a lot of instructions, so you’re going to be looking up a lot of stuff.

Few people actually want to do that, so the rest of us use programming languages instead.

1.1. Programming Languages

A programming language is something that’s easier for humans to use than machine language, but is capable of being accurately translated to machine language.

There are many, many programming languages. Seriously, there are a lot.

The instructions you write using a programming language are called source code. Translating source code file to a machine language file that can be executed is called compiling, and is done by an application called a compiler. When the computer runs the program, it’s using the machine language translation created by the compiler. Clicking on the icon to open Microsoft Word runs a file that’s been compiled from source code.

Time To Watch!

Coding and Compiling

Some programming languages don’t get translated ahead of time—they get translated "on the fly," as the program is running. That’s called interpreting instead of compiling, but it’s conceptually the same thing.

Python is an example of an interpreted languagel; popular compiled languages include C++ and (sort of) Java and C#.

1.2. The Python Programming Language

The language we’ll be learning is called Python; the name is a reference to the British comedy group Monty Python Flying Circus. As a side note, you can’t call yourself a real nerd if you’ve never seen Monty Python and the Holy Grail.

As mentioned above, Python is an interpreted language. Instead of compiling our source code and then running the compiled file, the Python interpreter reads the first line of our source code, translates it into machine language, and immediately executes it. Then it goes on the to next line, translates and executes it, and goes on. This continues until the interpreter reaches the end of the source code file (or crashes because of an error).

Python was first released in the early 1990s by Guido van Rossum. His goal was to create a language that was easy to read and write, so it uses a lot of plain English words and it minimizes the use of weird characters, like curly braces.

It is used for a wide variety of applications. System administrators use it to write scripts that automate repetitive tasks, for example. Web developers can use it to create web applications. It has become the de facto standard language for data science and AI/machine learning applications.

Around here, we believe that a good foundation in any programming language puts you in a good position to learn other languages down the road. So even if you don’t plan to use Python beyond this course, the skills you learn here will give you a head start on learning other languages down the road. Our goal here is to become programmers, not just Python programmers.

1.3. First Python Program

Enough of that, let’s write some code!

Python emphasizes simplicity, so it’s very easy to write a simple program. We basically just need to open a blank text file and type in our first line of code.

Time To Watch!

Note: these two videos cover the same content; just watch the one for the IDE you plan to use.

Starting with Python in PyCharm

Starting with Python in Visual Studio Code

Files from videos:

1.4. Basic Output

By tradition, the first program we write in any programming language is a program that outputs the text "Hello, World!" to the screen. In Python, we can do that with a single print() statement:

Example 1.1 - Hello World program in Python
print("Hello, World!")

The first programs we create in Python are console programs—they are text-based programs that can’t really display any graphics. For the time being, we’ll use a print() statement any time we want to output text to the console window.

print() simply outputs whatever text is in the parentheses, and we’ll need to put that text in quotation marks to indicate that it’s a string, but we’ll learn more about strings later.

To output additional text, we can just add more print() statements:

Example 1.2 - Basic print() statements in Python
1
2
3
print("In the words of Paul McCartney,")
print("Hey Jude, don't make it bad.")
print("Take a sad song, and make it better.")

After outputting the string in each print() statement, the cursor automatically advances to the next line. In other words, each print() statement outputs its text on a separate line.

In the words of Paul McCartney,
Hey Jude, don't make it bad.
Take a sad song, and make it better.

If we want to continue the next print() statement on the same line, we can add another piece of information inside the prentheses: end="" with no characters between the parentheses.

Example 1.3 - A print() statement that doesn’t advance to the next line
1
2
print("Hey Jude, don't make it bad.", end="") (1)
print("Take a sad song, and make it better.")
1 The addition of end="" keeps the cursor on the same line after outputting the text.

The program now produces the following output:

In the words of Paul McCartney,Hey Jude, don't make it bad.
Take a sad song, and make it better.

Notice that there is no space between the end of the first statement and the start of the second; if we want a space there, we have to include it within the quotation marks of one statement or the other.

Example 1.4 - Two different ways to add a space between two output statements
1
2
3
4
5
print("Hey Jude, don't make it bad. ", end="") (1)
print("Take a sad song, and make it better.")

print("Hey Jude, don't make it bad.", end="")
print(" Take a sad song, and make it better.") (2)
1 Space added at the end of the print() output.
2 Space added at the beginning of the next print() output.

1.5. Code Comments

The Python interpreter goes through our source code file line by line, translating each line into something that it can execute (unless it finds something it doesn’t understand, which causes it to stop and output an error message). If there’s something in our source code we don’t want the interpreter to process, we can identify it as a code comment and the interpreter will ignore it. Code comments are generally used to provide information for any humans who might be looking at the code, and are usually used to explain what the code is doing. And since they are ignored by the interpreter, code comments can be written however we want; so they should be written in plain human language. To indicate a comment, use the # symbol, which we call a pound sign or hash mark.

# This is a comment!

Once the interpreter sees that symbol, it just skips the rest of the line and moves on to the next line. If we add a comment onto the end a line of code, it’s called an inline comment:

Example 1.5 - An inline comment
print("Hello World") # This line outputs text to the console.

The print() statement still gets processed and will execute, but everything after the hash is ignored.

In Python, we shouldn’t use inline comments very often. Instead, we should generally put a comment on its own line above the code it refers to or explains. This is called a single-line comment:

Example 1.6 - A single-line comment to explain the code below it
# This line outputs text to the console.
print("Hello World")

Comments that span multiple lines are referred to as block comments or multi-line comments, and are useful when we need to provide a lot of explanation.

According to the official Python guidelines, which we’ll get to next, a comment block should be created by starting each line with a #. In other words, just use multiple single-line comments.

Example 1.7 - Block comment
# This line outputs text to the console.
# Although it doesn't need explanation, we need an excuse to demonstrate
# multiple lines of comments.
print("Hello World")

However, it’s also common to see two other ways of creating block comments.

  • Triple quotation marks (""") to indicate the start of the comment block, and the same triple quotes on a separate line to mark the end of the comment block.

    1
    2
    3
    4
    5
    """This line outputs text to the console.
    Although it doesn't need explanation, we need an excuse to demonstrate
    multiple lines of comments.
    """
    print("Hello World")
    
  • Triple apostrophe symbols (```) to indicate the start of the comment block, and the same triple apostrophes on a separate line to mark the end of the comment block.

    1
    2
    3
    4
    5
    '''This line outputs text to the console.
    Although it doesn't need explanation, we need an excuse to demonstrate
    multiple lines of comments.
    '''
    print("Hello World")
    

These last two methods are processed by the Python interpreter rather than being ignored. They create something called a literal string that is then discarded, though we haven’t learned about that yet. And we’ll have a special use for the triple-quote approach later on. But for our purposes as beginners, we can think of them as comment blocks.

Code comments don’t cost anything, so use lots of them!

We often add a multiline comment block at the top of a file to provide information about the overall program or class, and I require that of all files my students turn in. That comment block is often a special kind of comment called a docstring, though I don’t expect students to use a specific docstring format.

1.5.1. "Commenting Out" Code

Coding is all about trial and error, and we’ll spend a lot of time writing code in different ways until we get it working the way we want. Given that process, it’s not unusual to delete something only to regret it and wish we could have that old code back.

Code commenting gives us a life hack to help prevent that regret. Instead of deleting code that’s not working the way we want, we can just mark it as a comment. As far as the compiler is concerned, we’ve deleted the code. But if we want to see or use the code again down the road, it’s still there.

Almost all IDEs have a keyboard shortcut for commenting out code—and in many, it’s the same shortcut. Highlight a section of code and press Alt+/ on Windows or +/ on macOS, and many IDEs will add // at the start of each line. Highlighting a comment and pressing the shortcut again will usually "uncomment" it and remove the slashes. If that doesn’t work, check the IDE’s documentation to see if there’s a different shortcut.
Example 1.8 - Commenting out code
1
2
3
print("In the words of Paul McCartney,")
# print("Hey Jude, don't make it bad.")
print("Take a sad song, and make it better.")

Because line 2 is commented out, it will be ignored and the output will be:

In the words of Paul McCartney,
Take a sad song, and make it better.

If we decide we want that missing line later, we simply need to delete the `# ` and the interpreter will execute it.


1.6. Python Style Guidelines (PEP-8)

There is an official set of guilelines for writing Python code called PEP-8 (Python Enhancement Proposal #8). The goal of such style guidelines is to promote consistency in the way Python programmers write their code, which makes it easier for us all to read and understand one another’s code.

Some of the key guidelines include:

  • Use 4 spaces to indent. Your IDE should handle this automatically, but indenting is important in Python so it’s worth calling out.

  • Limit lines to 79 characters in length. Your IDE may or may not do this by default, but you can configure it the settings.

  • Specific guidelines for how we name things in our programs.

As you can see if you look through the PEP-8 document, there are a lot of guidelines. Many of them apply to situations we’re not likely to encounter any time soon.

Speaking of indenting: for now, do not indent your source code! In a few chapters, we’ll start to see why indenting (and other use of whitespace) is important.

While the conventions sometimes seem nitpicky and artibtrary, they are important. I do my best to follow PEP-8 guidelines throughout my examples, and I expect students to do the same in their own work. I don’t go looking for weird violations, but I do penalize students for obvious or repeated violations.


Check Yourself Before You Wreck Yourself (on the assignments)

Chapter Review Questions

  1. What is the primary role of a programming language in the context of computer programming?

  2. What happens when you run a Python program? Describe that process in simple terms.

  3. What is PEP-8?

  4. How would you explain what a "program" is to an 8-year-old?

  5. Explain the difference between compiled and interpreted programming languages. Which is Python?

Sample answers provided in the Liner Notes.