Code
= 3
x type(x)
int
Type | Example | Description |
---|---|---|
int |
x = 1 |
integers (i.e., whole numbers) |
float |
x = 1.0 |
floating-point numbers (i.e., real numbers) |
complex |
x = 1 + 2j |
Complex numbers (i.e., numbers with real and imaginary part) |
bool |
x = True |
Boolean: True/False values |
str |
x = 'abc' |
String: characters or text |
NoneType |
x = None |
Special object indicating nulls |
We’ll take a quick look at each of these in turn.
The most basic numerical type is the integer. Any number without a decimal point is an integer:
Another convenient feature of Python integers is that by default, division up-casts to floating-point type:
The floating-point type can store fractional numbers. They can be defined either in standard decimal notation, or in exponential notation:
In the exponential notation, the e
or E
can be read “…times ten to the…”, so that 1.4e6
is interpreted as ~1.4 \times 10^6.
An integer can be explicitly converted to a float with the float
constructor:
Complex numbers are numbers with real and imaginary (floating-point) parts. We’ve seen integers and real numbers before; we can use these to construct a complex number:
Alternatively, we can use the “j
” suffix in expressions to indicate the imaginary part:
Complex numbers have a variety of interesting attributes and methods, which we’ll briefly demonstrate here:
Strings in Python are created with single or double quotes:
Python has many extremely useful string functions and methods; here are a few of them:
Q: What does split()
method do? What is the result?
Q: Now try to split this notebook’s name into words. What argument you have to pass to split()
?
Q: When you have a sequence of string, you can use join()
method:
Strings are immutable
Python includes a special type, the NoneType
, which has only a single possible value: None
. For example:
You’ll see None
used in many places, but perhaps most commonly it is used as the default return value of a function. For example, the print()
function in Python 3 does not return anything, but we can still catch its value:
The Boolean type is a simple type with two possible values: True
and False
, and is returned by comparison operators discussed previously:
Keep in mind that the Boolean values are case-sensitive: unlike some other languages, True
and False
must be capitalized!
A Whirlwind Tour of Python by Jake VanderPlas (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-491-96465-1 ## License Open MIT License, adapted from the Python Course 2020 developed by Cefas (Centre for Environment, Fisheries and Aquaculture Science) and Python Course for SENSE (Centre for Satellite Data in Environmental Science) PhD students 2020.