Source
Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree
Implicit Conversion
Python decides the result type of an operation by itself, choosing the type that avoids losing data:
int * intreturnsintint * floatreturnsfloatint / intreturnsfloat
type(3 * 4) # <class 'int'>
type(3 * 4.0) # <class 'float'>Explicit Conversion (Type Casting)
Call the target type like a function, dtype(value):
str(25) # '25'
int('25') # 25
float('3.5') # 3.5
int(3.9) # 3, truncates
int('3.0') # ValueError, the str is not an integer literalCasting is how numeric data read from a text file (which arrives as str) is turned back into numbers.
Identity: is, is not
Two different checks:
a == banda != bcheck whether the values are equalisandis notcheck whether two names point to the same object in memory
a = [1, 2, 3]
b = a # no new object, b is a second name for the same list
c = [1, 2, 3] # a new list with the same content
a == c # True, same values
a is b # True, same object
a is c # False, different objectsSince b = a does not copy, changing b also changes a.
Membership: in, not in
Checks whether an item is present in a str or a data structure (list, tuple, dict, set):
'ell' in 'Hello' # True
0.2 in [0, 3.2, 0.2] # True
age = {'Ben': 4, 'Amy': 8}
'Amy' in age # True
8 in age # False, only keys are checkedFor a dict only the keys are checked, not the values. The structures themselves are in Tuples Dictionaries and Sets.