100
100
We declare a number of variables with different value types.
By ‘type’ we mean object type.
Data types and data structures are both types of object.
Data types are created by the way they are written or as keywords …
Here is a series of literal values (called literals):
Integers
100
100
Floats (decimals)
3.14
3.14
1, 1.
(1, 1.0)
Strings
Type of quote does not matter, but they must be straight quotes, not “smart quotes” that some word processors use.
Note that there is no explicit character type as in Java and other languages.
"foo"
'foo'
"1"
'1'
'foo'
'foo'
Boolean
True, False
(True, False)
Nothing
It evaluates to nothing!
None
print(None)
None
Complex
For the physicists and signal processors.
5+0j
(5+0j)
You can always find out what kind of type you are working with by calling the type()
function.
type(3.14)
type("foo")
type('foo')
type(True)
type(None)
<class 'float'>
<class 'str'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
Data are assigned to variables using the assignment operator =
.
The variable is always on the left, the value assigned to it on the right.
This is not the same as mathemtical equality.
Variables are assigned types dynamically.
This is in contrast to static typing, where you have define variables by asserting what kind of data values they can hold.
Python figures out what type of data is being set to the variable and implicitly stores that info.
= 8
integerEx = 22000000000000000000000
longIntEx = 2.2
floatEx = "Hello"
stringEx = True
booleanEx = None noneEx
Note that type()
returns the type of the value that a variable holds, not the type “variable”.
type(integerEx)
<class 'int'>
del()
= 101.25 x
x
101.25
del(x) # delete the variable x
x
NameError: name 'x' is not defined
You can’t delete values!
del("foo")
SyntaxError: cannot delete literal (1397139688.py, line 1)
id()
This function returns the identity of an object.
The identity is a number that is guaranteed to be unique and constant for this object during its lifetime (during the program session).
You can think of it as the address of the object in memory.
print(id(integerEx))
4329876032
It is possible to convert between types (when it makes sense to do so).
Sometimes conversions are “lossy” – you lose information in the process
int()
int?
Init signature: int(self, /, *args, **kwargs)
Docstring:
int([x]) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
Type: type
Subclasses: bool, IntEnum, IntFlag, _NamedIntConstant
Float to Int
= 3.8
val print(val, type(val))
3.8 <class 'float'>
= int(val)
val_int print(val_int, type(val_int))
3 <class 'int'>
String to Float
= '3.8'
val print(val, type(val))
3.8 <class 'str'>
= float(val)
val_int print(val_int, type(val_int))
3.8 <class 'float'>
Converting string decimal to integer will fail:
= '3.8'
val print(val, type(val))
3.8 <class 'str'>
= int(val)
val_int print(val_int, type(val_int))
ValueError: invalid literal for int() with base 10: '3.8'
ord()
Converting a character to it’s code point
ord?
Signature: ord(c, /)
Docstring: Return the Unicode code point for a one-character string.
Type: builtin_function_or_method
ord('a'), ord('A')
(97, 65)
If variables are nouns, and values meanings, then operators are verbs.
In effect, they are elementary functions that are expressed in sequential syntax.
a + b
could have been expressed as add(a, b)
.
Basically, each data type is associated with a set of operators that allow you to manipulate the data in way that makes sense for its type. Numeric data types are subject to mathematical operations, booleans to logical ones, and so forth.
There are also operations appropriate to structures. For example, list-like things have membership.
The relationship between types and operators is a microcosm of the relationship betweed data structures and algorithms. Data structures imply algorithms and algorithms assume data structures.
The w3schools site has a good summary.
Here are some you may not have seen.
//
5 // 2
2
-5 // 2
-3
5.5 // 2
2.0
%
Returns the remainder
5 % 2
1
odd integers % 2 = 1
even integers % 2 = 0
Look at this …
5.5 / 2, 5.5 // 2, 5.5 % 2
(2.75, 2.0, 1.5)
**
5**3
125
+
The plus sign is an ovderloaded operator in Python.
= 'This: ' myString
= myString + ' Goodbye, world!' my2ndString
my2ndString
'This: Goodbye, world!'
*
# print('-' * 80)
*2 myString
'This: This: '
* 5 myString
'This: This: This: This: This: '
= 'I will not skateboard in the halls' bart_S1E3
print((bart_S1E3 + '\n') * 5)
I will not skateboard in the halls
I will not skateboard in the halls
I will not skateboard in the halls
I will not skateboard in the halls
I will not skateboard in the halls
print('-' * 80)
--------------------------------------------------------------------------------
See them all :-)
=
We’ve used this already, but it too is an operator.
= 20
epoch print('epoch:', epoch)
epoch: 20
Comparisons are questions.
They return a boolean value.
==
0 == (10 % 5)
True
'Boo' == 'Hoo'
False
Can we compare strings
'A' < 'B'
True
ord('A'), ord('B')
(65, 66)
!=
5/9 != 0.5555
True
Python uses words where other languages will use other symbols.
and
, or
, not
Note the we group comparisons with parentheses.
= 10
x
% 10 == 0) or (x < -1) (x
True
% 10 == 0) and (x < -1) (x
False
not x == 5
True
is
The is
keyword is used to test if two variables refer to the same object.
The test returns True
if the two objects are the same object.
The test returns False if they are not the same object, even if the two objects are 100% equal.
Use the ==
operator to test if two variables are equal.
– from W3Schools on Identity Operators
is
= 'fail' x
is 'fail' x
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
/var/folders/14/rnyfspnx2q131jp_752t9fc80000gn/T/ipykernel_53814/1139635342.py:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
x is 'fail'
True
is not
is not 'fail' x
<>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
<>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
/var/folders/14/rnyfspnx2q131jp_752t9fc80000gn/T/ipykernel_53814/1754352910.py:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
x is not 'fail'
False
= 'foo'
x = 'foo'
y is y x
True
= ['a']
x = ['a']
y is y x
False
not
not True, not False, not 0, not 1, not 1000, not None
(False, True, True, False, False, True)
Python offers a short-cut for most operators. When updating a variable with an operation to that variable, such as:
= my_var + 1 # Incrementing my_var
You can do this:
+= 1 my_var
Python supports many operators this way. Here are some:
-= a
a = a
a \= a
a \\%= a
a *= a
a **= a a
Variables, literal values, and operators are the building blocks of ebxpressions.
For example, the following combines three operators and four variables:
1 + 2 * 3 / 2
4.0
Python employs operator precedence when evaluating expressions:
P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction
You can use parentheses to group them to force the order of operations you want:
1 + 2) * (3 / 2) (
4.5
Variables and literal values can be combined:
= 5
y = 2.5
m = 10 b
= m * 10 + b
y y
35.0
= m * 5 + b
y y
22.5
Expresssion can be very complex.
Expressions evaluate to a value, just as single variables do.
Therefore, they can be put anywhere a value is accepted.
int((y + 10) ** 8)
1244706300354