2 + 3 # addition
5
int, float, str, bool
Read Ch 4 intro and Ch 4.1, which describes in detail how Python evaluates expressions involving numeric data types.
Before continuing, make sure you understand the following:
int
values. Real numbers are called float
values. These are flexible but have some computational limitations.type
of an expression is the type of its final value.float
value is combined with an int
value using some arithmetic operator, then the result is always a float
value.You have seen this table before.
Operator | Symbol | Example Expression | Expression Value |
---|---|---|---|
Addition | + |
2 + 3 |
5 |
Subtraction | - |
15 - 4 |
11 |
Multiplication | * |
-2 * 9 |
-18 |
Division | / |
15 / 2 |
7.5 |
Integer division | Cuts off remainder | // |
15 // 2 |
Remainder/Modulo | % |
19 % 3 |
1 (19 ÷ 3 = 6 Remainder 1) |
Exponentiation | ** |
3 ** 2 |
9 |
Read Ch 4.2 which describes the string data type.
Before continuing, make sure you understand the following:
Concatenation operation: The +
operator works differently on string data types. Instead of adding numerically, it “adds textually,” which is more formally called concatenation:
2 + 3 # addition
5
'hello' + "donuts"
'hellodonuts'
Length function: There is one function not shown above that would be useful to you know, and that is len(s)
, which takes a string argument and returns its length.
= "hello world"
s len(s)
11
The Boolean data type (bool
) has exactly two values: True
and False
. Note that boolean values are not strings!
= True
b b
True
= False
b type(b)
bool
In our current view of Python as an advanced calculator, it may be unclear why such a special data type is needed. We will find soon that it is very useful to have a special data type to represent whether something is true or false.
We can also typecast, or convert values between data types. These typecasting functions take in one typed argument and return another typed argument, then return that value as a different type. The function name is generally the type. Note that data type conversion is only valid “when it makes sense.” We’ll talk about this more later.
= 3 # what type is x?
x str(x) # returns a value of type string
'3'
= "5" # what type is x?
s float(s) # what type is returned?
5.0