← Back to the Introduction to Computer Science outline The Course Maker
← Introduction to Computer Science outline
Week 2 · Lecture

Lecture: Variables, Data Types & Expressions

Introduction to Computer Science Free sample edition

Lecture script · about 15–20 minutes spoken · Week 2

Opening

Picture your phone's step counter at lunch. It reads 4200 steps. You walk to class, and when you check again it reads 5000. The word "Steps" at the top of the screen never changed. Only the number under it did.

That small idea runs through a lot of work you might do. A nursing student converts a dose from one unit to another. A business student splits a budget into equal shares and has something left over. Each of them needs to name a value, know what kind of value it is, and trust the arithmetic. When any of those slips, a total can be quietly wrong.

In Week 1, you ran your first lines of Python. You saw that multiplication goes before addition, that two strings join instead of adding, and that you read an error from its last line. You also saw a surprise: dividing 10 by 2 printed 5.0, with a decimal point. I promised an explanation, and it arrives in this lecture.

Here's the plan. We give values names, sort them by type, and work out expressions in Python's order. Then we divide three ways, convert between types, and finish with two decimal surprises and a chatbot claim we check by running the code. Next, in Week 3, Input, Output & Strings, your programs start asking a person for values.

1. Name a value: variables and assignment

Think about a jar of coins with a sticky note on it that says "Laundry." The note is a label. The coins inside change every week, but the label stays put, so you always know which jar to reach for.

A program needs labels like that. A variable is a name that holds a value so a program can use that value later, such as pages_left holding 255.

You make a variable with assignment, the statement that puts the value on the right of the equals sign into the name on the left. You read the equals sign as "gets." So the line goal equals 300 means goal gets 300. That reading matters. In a math class, the equals sign says two sides are the same. In Python, it's an instruction: work out the right side, then store the result under the name on the left.

Let's grow the reading log from Week 1. The goal is 300 pages, and you've read 45 so far. Line one: goal gets 300. Line two: pages_read gets 45. Line three: pages_left gets goal minus pages_read. Python looks up both names, works out 300 minus 45, which is 255, and stores 255 under pages_left. Line four prints pages_left, and the output is 255. So 255 pages remain before the goal.

Now, what happens when a name gets a second value? That's reassignment: assigning a new value to a name that already holds one, which replaces the old value and leaves every other name exactly as it was.

Here's a tiny story about that. You type three lines. First, x gets 5. Second, y gets x. Third, x gets 10. Then you print y. Many people expect 10, because the second line looks like it ties the two names together. Run it, and the output is 5. When y got x, it took the value x held at that moment, which was 5. Later, x got a new value. Nothing told y to change.

Week 1's rule about capital letters still applies: Steps with a capital S and steps in lowercase are two different names, and mixing them up gives a NameError.

Pause and try this. The step counter program says steps gets 4200, and then steps gets steps plus 800. What does steps hold after the second line, and what happened to 4200?

Work out the right side first, then store it.

Here's the answer. Steps holds 5000. Python worked out 4200 plus 800 on the right side, then stored 5000 under the name, and the old 4200 is gone.

So a label stays put, and the value under it changes.

2. Sort values by type: int, float, str, and bool

Think about a cashier. A price, a coupon code, and the question "is this a member?" all show up at the register, and the cashier treats each one differently. You can add two prices. You can't add a coupon code to a price. And the member question has only two possible answers.

Python sorts every value the same way. A data type is the kind of value a piece of data is, such as a whole number or a piece of text, which decides what operations Python allows on it.

You meet four core types in this lecture. An int is Python's type for whole numbers with no decimal point, such as 255, which can grow as large as the computer's memory allows. A float is Python's type for numbers with a decimal point, such as 8.5 or 5.0. A str is Python's type for text: a string such as the characters 2, 5, 5 inside quotation marks is a str even when every character in it is a digit. And a bool is Python's type for the two truth values, True and False.

You never have to guess a type. The name type, with parentheses after it, is the built-in function that reports what type a value is. Ask it about 255, and it reports the class int. Ask about 8.5, and it reports the class float. Ask about 255 inside quotation marks, and it reports the class str. Ask about True, and it reports the class bool.

Notice the first and third of those. Both show the same three digits. The quotation marks turn the second one into text. A str holds characters, and it doesn't know they look like a number.

Variables carry the type of the value they hold. In the reading log, pages_left holds 255, so its type is int.

Pause and try this. Two values look alike: 255 with no quotation marks, and 255 inside quotation marks. Which one is an int, and which is a str?

Think about what the quotation marks tell Python.

Here's the answer. The bare 255 is an int, a whole number. The one in quotation marks is a str, because the quotes make it text, even though every character is a digit.

So when a value surprises you, ask type before you guess.

3. Work out an expression: operator precedence and powers

Imagine a recipe that says "double the sugar, then add a spoonful." Now imagine one that says "add a spoonful, then double it." Same ingredients, different cake. Order changes the result.

An expression is a combination of values, names, and operators that Python works out to a single value, such as goal minus pages_read. When an expression has several operators, Python follows a fixed order, and you met that idea in Week 1 as operator precedence.

This week adds an operator at the very top. The exponent operator is written as two stars. It raises the number on its left to the power of the number on its right, and Python works it out before any other arithmetic operator.

So the full order has three levels. First, powers. Second, multiplying and the three kinds of dividing, worked out left to right. Third, adding and subtracting, left to right. And parentheses beat all of it.

Let's trace one. Take 2 times 3 to the power of 2. Reading left to right, you might say 2 times 3 is 6, and 6 squared is 36. Python doesn't do that. The power goes first, so 3 to the power of 2 is 9. Then 2 times 9 is 18. Run it, and the output is 18. Now put parentheses around 2 times 3. The parentheses go first, so 2 times 3 is 6, and 6 to the power of 2 is 36. The grouping doubles the result: 36 versus 18.

Here's a real-world one. A weather app converts 25 degrees Celsius to Fahrenheit by multiplying by 9, dividing by 5, and adding 32. Multiplying and dividing share a level, so Python goes left to right: 25 times 9 is 225, and 225 divided by 5 is 45.0. Then it adds 32 and gets 77.0. The order Python used matches the recipe.

2 to the power of 10 prints 1024. And 2 to the power of 100 prints an exact 31-digit whole number, with no rounding at all, because Python integers never overflow.

Pause and try this. A classmate predicts that 2 times 3 to the power of 2 prints 36. What did they do, and what does Python print?

Ask yourself which operator sits on the top level.

Here's the answer. They multiplied first. Python does the power first, 3 to the power of 2 is 9, then 2 times 9, so it prints 18.

Powers first, then times and divides, then plus and minus, and parentheses beat them all.

4. Divide three ways: true division, floor division, and remainder

Picture a bike-share station near the library with 47 bikes, and racks that hold 10 bikes each. Someone asks, "How many racks?" There are three honest answers. Exactly 4.7 racks. Or 4 full racks. Or 7 bikes left over after the full racks. Python has a separate operator for each.

True division is division with a single slash, which always gives a float, even when the two numbers divide evenly. Floor division is division with a double slash, which gives the quotient rounded down to the next whole number toward negative infinity. And the remainder operator, written with the percent sign, gives what is left over after floor division, carrying the sign of the number you divide by.

Now the reading log. You have 255 pages left, and you read 30 pages a day. Divide with a single slash, and Python prints 8.5. That's the exact count of days. Divide with a double slash, and it prints 8. That's how many full 30-page days fit. Use the percent sign, and it prints 15. That's the pages left after those full days.

Check them against each other. 8 times 30 is 240, and 240 plus 15 is 255. The floor and the remainder rebuild the total. So you need 8 full days and then 15 more pages, which is why the exact count is 8.5 days.

The bikes work the same way. 47 with a double slash and 10 gives 4. 47 with the percent sign and 10 gives 7. Four full racks, seven bikes over. And a short pinned pair: 7 floor-divided by 2 is 3, and 7 remainder 2 is 1.

And the Week 1 surprise? Dividing 10 by 2 printed 5.0, because a single slash always gives a float.

Negative numbers get one mention. Negative 7 floor-divided by 2 is negative 4, because the exact quotient is negative 3.5 and floor division moves down. And negative 7 remainder 3 is 2, because the remainder takes the sign of the number you divide by. Recognize these; don't memorize them.

Pause and try this. In the reading log, one operator answers "how many full 30-page days fit in 255 pages?" Which operator is it, and what does it print?

Think about full groups, not the exact count.

Here's the answer. Floor division, the double slash, and it prints 8. It doesn't round 8.5 up to 9; it always moves down to the whole number below.

Single slash for exact, double slash for full groups, percent for leftovers.

5. Convert between types on purpose

Picture a card reader at a shop. It scans a price tag and sees the characters 1 and 2. You see a price of 12 dollars. The reader has to be told to treat those characters as a number before it can do any math. Python works the same way, and it never makes that choice for you.

Type conversion is turning a value of one type into another with a built-in function such as int, float, or str. When you skip the conversion, Python stops. A TypeError is the error type Python reports when an operation is applied to a value of the wrong type, such as adding a string to a number.

Here's the classic case. Put 5 in quotation marks, then a plus sign, then the number 3 with no quotation marks. Run it, and nothing prints. The last line of the error message names TypeError. Python saw text on one side of the plus sign and a number on the other. Should it add or join? It refuses to guess. This is a runtime error: the program started, and this line stopped it.

Now fix it two ways. Wrap the text 5 in int, then add 3. Python turns the text into the whole number 5, then 5 plus 3 is 8, and it prints 8. Or wrap the number 3 in str instead. Now both sides are text, the plus sign joins them, and it prints 53. You choose the type, and the type decides what the plus sign does.

One conversion has a trap. Truncation is cutting off the decimal part of a number without rounding it, the way int of 3.9 gives 3. Many people expect 4. Python cuts; it doesn't round, so int of 3.9 prints 3.

And one more pinned surprise: the text 3 times the number 4 prints 3333. With a string and a whole number, the star repeats the string four times.

Pause and try this. You have the text 5 and the number 3, and you want Python to print 8. Which conversion do you add, and to which value?

Decide which side needs to become a number.

Here's the answer. Wrap the text 5 in int, so both sides are whole numbers. Then 5 plus 3 is 8, and Python prints 8.

Python never guesses a type; you convert on purpose.

6. Check the two float surprises with a run

Think about a bus-arrival sign that shows 2.5 buses. It would look broken. Two decimal behaviors in Python look broken at first too.

The first is rounding. Round-half-to-even is the rule the round function follows for a number exactly halfway between two whole numbers: it picks the even neighbour, so round of 2.5 is 2 and round of 3.5 is 4. For 2.5, the neighbours are 2 and 3, and 2 is the even one. For 3.5, the neighbours are 3 and 4, and 4 is the even one. Run them together, and Python prints 2, then 4.

The second surprise is that some decimals can't be stored exactly. A float is kept in binary, and 0.1 has no exact binary form, much like one third has no exact decimal form. So when you ask Python whether 0.1 plus 0.2 equals 0.3, it prints False. The sum lands a tiny distance away from 0.3. You don't need the exact digits; you need to know tiny errors happen.

Now the chatbot. Suppose you ask a chatbot what round of 2.5 prints, and it answers 3, explaining that halves always round up. But a chatbot predicts likely text; it doesn't run your program. So you run the line in your browser runner. The output is 2. The chatbot described a rule Python doesn't use, and its explanation contradicts what the code prints. You caught it by running the code. If you want the rule in writing, the built-in functions page of the Standard Library reference, on docs.python.org, describes round.

Pause and try this. A chatbot tells you that round of 3.5 prints 4. Is it right, and how would you know for sure?

Remember which neighbour round picks.

Here's the answer. It's right: 3.5 sits between 3 and 4, and 4 is even. But you'd know for sure only by running the line and reading the output.

The chatbot proposes, and the run decides.

Closing

Let me pull it together in the order we built it. A variable is a name for a value, and the equals sign means "gets," so pages_left got 255, and a reassignment changes only the name on its left. Every value has a type, int, float, str, or bool, and type tells you which. Python works out powers first, then times and divides, then plus and minus, so 2 times 3 to the power of 2 is 18. A single slash gives the exact 8.5 days, a double slash gives 8 full days, and the percent sign gives the 15 pages left over. Python never mixes text and numbers on its own, so you convert with int, float, or str, and int cuts off decimals. And round sends a half to the even side, which a quick run will confirm every time.

Next in this module come the slide deck, the Readings and Resources page, the lecture tutorial, the practice set, the quiz, and the Coding Lab. Then, in Week 3, Input, Output & Strings, the input function hands you text every time a person types, so the conversions from this lecture become the first thing you write.


Built with The Course Maker · samples.thecoursemaker.com