Python Fundamentals¶
This material is mostly adapted from the official python tutorial, Copyright 2001-2021, Python Software Foundation. It is used here under the terms of the Python License.
Invoking Python¶
There are three main ways to use Python.
By running a Python file, e.g.
python myscript.py
Through an interactive console (Python interpreter or iPython shell)
In an interactive notebook (e.g. Jupyter)
As previously mentioned, we will mostly be interacting with Python via Jupyter notebooks in this course.
Python Versions
There are two versions of the Python language out there: Python 2
and Python 3
. In 2021, the vast majority of the scientific community now uses Python 3
. As new Python learners, you should definitely learn Python 3
. But it is important to be aware that Python 2
exists, since you might encounter it in the wild.
Some of the main changes introduced in Python 3
are:
print
is a functionInteger division returns a float
Basic Variables: Numbers and String¶
Identifiers
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
Built in functions
Additionally, the following are built in functions which are always available in your namespace once you open a Python interpreter
abs() dict() help() min() setattr() all() dir() hex() next() slice() any()
divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray()
filter() issubclass() pow() super() bytes() float() iter() print() tuple()
callable() format() len() property() type() chr() frozenset() list() range()
vars() classmethod() getattr() locals() repr() zip() compile() globals() map()
reversed() __import__() complex() hasattr() max() round() delattr() hash()
memoryview() set()
All variables are objects. Every object has a type (class). To find out what type your variables are
Different objects attributes and methods, which can be accessed via the syntax variable.method
IPython will autocomplete if you press <tab>
to show you the methods available.
Math¶
Basic arithmetic and boolean logic is part of the core Python library.
More Flow Control¶
Important point: in Python, we always count from 0!
What is the thing in brackets? A list! Lists are one of the core Python data structures.
Lists¶
There are many different ways to interact with lists. Exploring them is part of the fun of Python.
- list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
- list.extend(L)
Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.
- list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
- list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
- list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
- list.clear()
Remove all items from the list. Equivalent to del a[:].
- list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
- list.count(x)
Return the number of times x appears in the list.
- list.sort()
Sort the items of the list in place.
- list.reverse()
Reverse the elements of the list in place.
- list.copy()
Return a shallow copy of the list. Equivalent to a[:].
Don’t assume you know how list operations work!
Memorize this syntax!
It is central to so much of Python
and often proves confusing for users coming from other languages.
In terms of set notation, Python
indexing is left inclusive, right exclusive. If you remember this, you will never go wrong.
Lists are not meant for math! They don’t have a datatype.
Python is full of tricks for iterating and working with lists
Other Data Structures¶
We are almost there. We have the building blocks we need to do basic programming. But Python has some other data structures we need to learn about.
Tuples¶
Tuples are similar to lists, but they are immutable—they can’t be extended or modified. What is the point of this? Generally speaking: to pack together inhomogeneous data. Tuples can then be unpacked and distributed by other parts of your code.
Note
Tuples may seem confusing at first, but with time you will come to appreciate them.
Dictionaries¶
This is an extremely useful data structure. It maps keys to values.
Dictionaries are unordered!
Square brackets [...]
are Python for “get item” in many different contexts.