Types and Conversions#
Note
Source: Drawn from the SE4ML Python chapter (chapter_python.rst,
lines 1760–1801) and the C# edition (data/types-and-conversions.rst).
bool truthiness table and None discussion are original additions.
Every value in Python has a type that determines what operations can be performed on it and how it is stored.
Built-in Types#
The four types used most often in early programs are:
intWhole numbers:
0,42,-17,1_000_000.floatApproximate real numbers:
3.14,-0.5,2.0,1.5e3.strStrings of characters:
"Hello",'Python',"42".boolBoolean truth values:
TrueorFalse.
Use type() to see the type of any value:
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("Hello")
<class 'str'>
>>> type(True)
<class 'bool'>
Type Conversion#
Use the type name as a function to convert between types:
Function |
Description |
Example |
|---|---|---|
|
Convert to integer (truncates floats) |
|
|
Convert to float |
|
|
Convert to string |
|
|
Convert to bool |
|
>>> int("42")
42
>>> float("3.14")
3.14
>>> int(3.99)
3
>>> str(100)
'100'
Note that int() truncates floats toward zero — it does not round:
>>> int(3.9)
3
>>> int(-3.9)
-3
Use round() if you need rounding.
Boolean Values and Truthiness#
True and False are the two boolean values. Every Python value can be
interpreted as boolean in a condition:
Falsy values:
0,0.0,""(empty string),[](empty list),{}(empty dict),NoneTruthy values: everything else
>>> bool(0)
False
>>> bool(1)
True
>>> bool("")
False
>>> bool("hello")
True
None#
None is a special value that represents the absence of a value. It is
the Python equivalent of null in Java or C#.
>>> x = None
>>> x is None
True
>>> print(x)
None
Functions that do not explicitly return a value return None automatically.
None is also used as a placeholder when a variable exists but has not been
given a meaningful value yet.
Test for None with is None, not with == None:
if result is None:
print("No result yet.")