Class summary: Booleans and Types
Copyright (c) 2017 Kathi Fisler
This material goes with basic data and expressions, sections 2.5 and 2.6 from the textbook
We’ve seen three kinds of data so far: numbers, strings, and images. We’ve actually seen a fourth, but not talked about it yet.
1 Booleans
Look at these expressions:
> 4 <= 5 |
true |
|
> "kathi" == "Kathi" |
false |
These two expressions yield yes/no answers, which seem different from numbers and strings. Booleans are our fourth kind of data. There are two Boolean values (true and false). Operations on Booleans are covered in the textbook.
2 Types in Programming
In programming, there’s actually a technical term for "kinds of data": types. A type is a collection of values. Each type can be processed by certain operations.
Programming Tip: Types help you make sure that your program only applies reasonable operations to values. When you encounter a new operation or feature, make sure you know what types of data it takes as inputs and produces as outputs.
For example, does it make sense to write num-min("hi", "bye")? No, because num-min is for numbers, not strings. We’ll see a lot more of types as we go through the course.
3 Conditionals
Imagine that you wanted to order some t-shirts, but the price of the shirts depended on how many you planned to order. Let’s assume shirts cost $15 each if you order fewer than 10, but $11 each if you order at least 10. What expression computes the price?
num-shirts = 20 |
if num-shirts < 10: |
num-shirts * 15 |
else: |
num-shirts * 11 |
end |
When you write an if expression, the checks must evaluate to booleans, but the answers (in the if and else cases) can evaluate to any value.
3.1 Evaluating Conditionals
How do conditionals evaluate? Let’s look at our tshirts example again.
num-shirts = 20 |
if num-shirts < 10: |
num-shirts * 15 |
else: |
num-shirts * 11 |
end |
We’ve said that programs evaluate from the inside out. What are the innermost expressions here? They are the two multiplication expressions. But it doesn’t make sense to run both of them – we only want to run whichever one we need (otherwise, if this code did a bit more, we might order two sets of shirts!).
See the textbook for an example of how to evaluate if-statements.