Free preview Computational thinking with variables

Program execution

What happens when you run a program?

๐Ÿ“„ Data types

All programs manipulate data in some way. A program might manipulate text to find relevant web pages, sound waves to cancel background noise, or photos to detect faces.

How does a computer represent all of those complex forms of data? You might be surprised to discover that everything boils down to just numbers and letters!

Primitive data types

In programming, we call a single piece of data a value.
A data type is a category for a value. It describes what the value represents and how it can be used.

Just a few basic types form the building blocks of all data. We call these primitive data types because we can create all other types of data by composing them. In Python, the primitive data types are integers, floats, booleans, and strings.

Integers

An integer is any number without a decimal point. It includes negative numbers, positive numbers, and zero.

The values 1 , 2024 , 12345678 , 0 , -47 , and -1000000 are all integers.

We don't add commas between digits. The computer doesn't recognize the comma-separated -1,000,000 as an integer.

Floats

A float is any number with a decimal point. The name float comes from the term floating point number because the decimal point 'floats' between digits.

The values 1.5 , 3.14159 , 56.01 , -91.7, and -33.33333 are all floats.

The values 22.000 , 0.0, and -1.0 are also floats. The computer recognizes any number written with a decimal point as a float, even if its decimal part is zero.

Booleans

A boolean is a truth value. It can only be one of two possible values: True or False.

We can think of a boolean value as indicating the answer to a question with only two options. Yes or no? On or off? Logged in or logged out?

In Python, the capitalization of True and False matters. The computer does not recognize the lowercase true or false as booleans.

Strings

A string is text, shortened from: a string of characters. A character is any letter, number, symbol, or space that we can type on a keyboard. A string must be surrounded by quotation marks.

The values "z" , "python@example.com" , "Try it out!" , "25% off", and ":)" are all strings.

The values "-12" , "98.5" , "2 + 2" , and "True" are also strings. The computer recognizes anything surrounded by quotation marks as a string, even if the text inside the quotation marks looks like a number or a boolean.

The value "" is a string, often called the empty string because it contains no characters. This is different from the value " ", which contains a single space character.

๐Ÿ“ Try it out!

[[โ˜ƒ graded-group 1]]

[[โ˜ƒ explanation 1]]

Complex data

How can just integers, floats, booleans, and strings possibly make up something as complex as a webpage, song, or photo?

Think about a webpage you use often. What data is on that page? Maybe it has a username (string!), a view count (integer!), or a price (float!). Maybe it shows your last message as read or unread (boolean!). This whole article you're reading right now is represented as one giant string.

Audio and images

Computers represent all audio and image data as huge sequences of integers. For audio, we sample the sound wave at regular time intervals and convert the amplitude at each sample point to an integer. That sequence of integers describes the sound wave, just like points on a graph.

[[โ˜ƒ image 4]]

Computers break images down into thousands of tiny pixels like a mosaic. They represent each pixel as an integer between 0 and 255 that describes its brightness. In black and white images, for example, the computer represents each pixel as either the integer value 255 (white) or the integer value 0 (black). In color images, we need three integers in the range 0-255 to describe each pixel's color: one for the amount of red light, one for green, and one for blue.

Binary data

Okay, but why make this all so complicated? It turns out that computers can only truly understand 1s and 0s, or binary. At the end of the day, every piece of data that the computer processes needs to be translated to 1s and 0s. [[โ˜ƒ explanation 2]]

Computers can easily convert integers, floats, booleans, and strings to binary, so it's convenient to use them as the basis for data in most programming languages. We can imagine how a boolean True or False maps to a binary 1 or 0, but integers, floats, and strings map to 1s and 0s, as well. We can represent the integer 47 as 101111, and we can represent the string "k" as 01101011. [[โ˜ƒ explanation 1]]

Computers automatically handle the data conversion behind the scenes, saving programmers like us from needing to directly manipulate 1s and 0s. Instead, we get to enjoy the convenience of primitive data types!

Summary

[[โ˜ƒ video 1]]

๐Ÿ“„ Syntax, runtime, and logic errors

Communicating with computers can be frustrating sometimes. They don't always understand what we're trying to get them to do, they take everything literally, and they can't exactly explain what they're thinking. That means that our programs often won't work the first time around - they'll have errors!

What is an error?

An error just means that a program doesn't work as intended, also called a bug.

Errors are a totally natural part of the programming process. Expert programmers don't stare at a blank code editor, divine the perfect solution, and end up with a final working program on their first try. And that's okay! Programming is a cycle of try-fix-try again.

Let's start by understanding the categories of errors we might need to fix.

Syntax errors

A syntax error means that a program is not valid Python. It doesn't abide by the official rules of the Python language, just like "eat potato good" does not abide by the official rules of the English language.

When we run a program with a syntax error, the computer immediately reports an error in the console. It doesn't even try to execute the first line of the program. Because syntax errors deal with the structure of the code, the linter can often catch these errors upfront. Most linter errors we encounter correspond to syntax errors.

Common syntax errors include mismatched parentheses, mismatched string quotation marks, and invalid indentation.


Press the Run button to execute the program below. What error appears in the console? To inspect the linter error, hover over the red circle in the left margin.

[[โ˜ƒ python-program 1]]

[[โ˜ƒ explanation 1]]

Runtime errors

Runtime errors are sneakier. The computer only discovers these errors as it's running the program, hence the name RUN-time. The program is valid Python syntax, but when the computer actually tries to execute a particular instruction, it gets confused.

With runtime errors, the computer executes all the lines of code before the incorrect line. If these lines print values, we see their output appear in the console. The computer only reports an error when it reaches the incorrect line. Then, it terminates the program. It does not execute any remaining lines of code.

Runtime errors come in many forms like TypeError, NameError, or ValueError. We'll learn more about these different forms as we go!


Press the Run button to execute the program below. What do you see in the console? Notice that some lines of code executed before the error appears.

[[โ˜ƒ python-program 1]]

[[โ˜ƒ explanation 1]]

Logic errors

Logic errors are a mismatch between what the programmer intended and what the code they wrote actually does. To the computer, these programs seem totally fine. There's nothing wrong with the Python syntax and it understands all of the instructions. When it runs the program, it executes successfully; there is no error message.

This can make logic errors challenging to spot, because the computer can't offer any help here. The programmer has to identify why the result they're getting isn't quite right.


Press the Run button to execute the program below. Compare what the program is trying to do and its actual result. Can you spot the logic error?

[[โ˜ƒ python-program 1]]

[[โ˜ƒ explanation 1]]

How can we avoid errors?

We can't eliminate bugs altogether, but we can program defensively to reduce the amount of time we spend dealing with them.

Iterative development

The most important strategy is to run our code early and often. Think of this like checkpointing.

Imagine I spend 20 minutes writing my whole program, and only then, run it for the first time. If I get an error now, I have no idea which parts of my code work and which don't.

Instead, we can program iteratively by writing, running, and verifying small chunks of functionality at a time. Then, when we do get an error, we'll be confident that it was caused by the last change we made.

Comments

In Python, any lines of code that start with the # character are treated as comments. When the computer runs a program, it skips over comments entirely. Comments are for humans, not computers!

We can use comments to leave notes to our future self and other programmers. In particular, it's helpful to explain the intention behind obscure blocks of code. This helps us verify if the code is doing what it's supposed to, especially if we come back several days later when we've forgotten what we were doing.


Press the Run button to execute the program below. Notice that nothing appears in the console for the comments on lines 3 and 6!

[[โ˜ƒ python-program 1]]

In the program above, I add five arbitrary-looking integers. By adding a comment that explains that my intention is to sum multiples of 9, it's easier for me to later recognize that there's a logic error here. 34 is not a multiple of 9!

Pair programming

Pair programming is an active collaboration where one person types and the other person offers suggestions, switching roles every so often. The person typing talks through their thought process as they go, so the second person can validate what they're doing.

Another person increases our chance of spotting minor errors early. Plus, when we can discuss our assumptions with someone, we can identify any larger logic errors upfront.

Enjoying the free preview?

Lessons after number 3 are reserved for Pro members โ€” unlock the full course and every other one.

Sign up free Go Pro