100100
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
100100
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!
Noneprint(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.
integerEx = 8
longIntEx = 22000000000000000000000
floatEx = 2.2
stringEx = "Hello"
booleanEx = True
noneEx = NoneNote that type() returns the type of the value that a variable holds, not the type “variable”.
type(integerEx)<class 'int'>
del()x = 101.25x101.25
del(x) # delete the variable xxNameError: 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
val = 3.8
print(val, type(val))3.8 <class 'float'>
val_int = int(val)
print(val_int, type(val_int))3 <class 'int'>
String to Float
val = '3.8'
print(val, type(val))3.8 <class 'str'>
val_int = float(val)
print(val_int, type(val_int))3.8 <class 'float'>
Converting string decimal to integer will fail:
val = '3.8'
print(val, type(val))3.8 <class 'str'>
val_int = int(val)
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 // 22
-5 // 2-3
5.5 // 22.0
%Returns the remainder
5 % 21
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**3125
+The plus sign is an overloaded operator in Python.
myString = 'This: 'my2ndString = myString + ' Goodbye, world!'my2ndString'This: Goodbye, world!'
*# print('-' * 80)myString*2 'This: This: '
myString * 5'This: This: This: This: This: '
bart_S1E3 = 'I will not skateboard in the halls'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.
epoch = 20
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.5555True
Python uses words where other languages will use other symbols.
and, or, notNote the we group comparisons with parentheses.
x = 10
(x % 10 == 0) or (x < -1)True
(x % 10 == 0) and (x < -1)False
not x == 5True
isThe 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
x = 'fail'x is 'fail'<>: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
x is not 'fail'<>: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
x = 'foo'
y = 'foo'
x is yTrue
x = ['a']
y = ['a']
x is yFalse
notnot 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 = my_var + 1 # IncrementingYou can do this:
my_var += 1Python supports many operators this way. Here are some:
a -= a
a \= a
a \\= a
a %= a
a *= a
a **= aVariables, literal values, and operators are the building blocks of ebxpressions.
For example, the following combines three operators and four variables:
1 + 2 * 3 / 24.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:
y = 5
m = 2.5
b = 10y = m * 10 + b
y35.0
y = m * 5 + b
y22.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