Introduction to Python Programming
This section gives a brief introduction to Python programming in general, without reference to use with Itasca software. There are many online and published resources to find more information:
The official Python web page: http://python.org.
The official Python tutorial is a good place to start: http://docs.python.org/2/tutorial/introduction.html
Learning Python by Mark Lutx published by O’Reilly.
For scientific programming specific information see: https://scipy-lectures.github.io/
IPython Console
The best way to get started with Python programming is to experiment with the IPython pane in the program. A tab like the one shown below is accessed using the
item on the menu. The following examples can be run in this terminal.![../../../../../../../_images/ipython_term.gif](../../../../../../../_images/ipython_term.gif)
Use the up and down arrow keys to access previous inputs.
Use the tab key for completion of Python names.
See http://ipython.org for more information about this terminal.
Basic Types
Every value in Python has a specific type. The most common types are
int
, float
and str
. These represent an integer, a real
number, and a character string, respectively. Below we assign some values to
some variables.
size = 0.5
box_count = 10
first_name = "Fred"
last_name = 'Baker'
long_string = """
This is a multi-line string.
Triple quotes are used to define strings like this.
"""
Lists, Tuples and Dictionaries
Three fundamental container types are commonly used in Python. These
are the list
, tuple
and dict
types.
Lists are created with the [ ] characters.
id_list = [1, 2, 3, 4]
Typing id_list
in the IPython console will show the value of this list.
id_list
output:
[1, 2, 3, 4]
Add an item to the end of a list with the append
method.
id_list.append(903)
id_list
output:
[1, 2, 3, 4, 903]
Iterate over a list (or any sequence) with for
and in
.
for id_number in id_list:
print ("id #: ", id_number)
output:
id #: 1 id #: 2 id #: 3 id #: 4 id #: 903
Note that white space is used to indicate what code is included in the loop.
Get the length of a list with len
.
len(id_list)
output:
5
Access individual elements of a list by index (using [ ]).
id_list[0]
output:
1
Access a sequence of elements (a slice) of a list using [#:#].
id_list[1:3]
output:
[2, 3]
The list index can be negative, which returns elements from the back of the list.
id_list[-1]
output:
903
The value of an element of a list may be changed.
id_list[0] = 10.0
print (id_list)
output:
[10.0, 2, 3, 4, 903]
Lists may store objects of different types.
id_list.append("this is a string")
id_list
output:
[10.0, 2, 3, 4, 903, 'this is a string']
Tuples
Tuples resemble but they cannot be changed after they are created being — in other words tuples are immutable.
parts = (1,2,3,4,5)
parts
output:
(1, 2, 3, 4, 5)
Dictionaries
Python dictionaries are used for one-to-one mappings between
objects (key/value pairs). The following line shows a dictionary
literal that is assigned to the variable telephone_directory
.
telephone_directory = {"Jim" : 125, "Steve": 128, "Bob" : 144}
telephone_directory
output:
{'Jim': 125, 'Steve': 128, 'Bob': 144}
Look up a value in a dictionary by supplying its key.
telephone_directory["Jim"]
output:
125
Assign new key/value pairs to an existing dictionary using [ ].
telephone_directory["Fred"] = 147
telephone_directory[(1,3)] = 0.22344
telephone_directory
output:
{'Jim': 125, 'Steve': 128, 'Bob': 144, 'Fred': 147, (1, 3): 0.22344}
Remove key, value pairs from a dictionary with del
.
del(telephone_directory["Bob"])
Iterate over a the key, value pairs of a dictionary as was shown with lists.
for key, value in telephone_directory.items():
print ("found key: {} with value: {}".format(key, value))
output:
found key: Jim with value: 125 found key: Steve with value: 128 found key: Fred with value: 147 found key: (1, 3) with value: 0.22344
Use the keys
method to get a list of the dictionary keys.
telephone_directory.keys()
output:
dict_keys(['Jim', 'Steve', 'Fred', (1, 3)])
For more about dictionaries see: The dictionary section of the Python tutorial
Defining Functions
Functions are defined in Python with the def
keyword.
def my_function(a, b):
return a + b
my_function(1.0, 5)
output:
6.0
Error Handling in Python.
The function call below contains a deliberate mistake to help show how Python handles errors.
my_function(1.0, "This is a Python string")
output:
Traceback (most recent call last): File "<string>", line 8, in <module> File "", line 1, in <module> File "c:/src/ppfc/common/python/src/basic_python.py", line 60, in <module> my_function(1.0, "This is a Python string") File "c:/src/ppfc/common/python/src/basic_python.py", line 49, in my_function return a + b TypeError: unsupported operand type(s) for +: 'float' and 'str'
The error occurs because float
and str
objects cannot be added in
Python, so an error message occurs when the function is called. Causing an
error in Python results in a traceback being printed. The traceback tells
you the type of error encountered and the line and file the error occured in.
Note
For advanced troubleshooting use the Python debugger. Typing debug
in
the IPython console activates the debugger.
Object-Oriented Programming
In Python all values (values are things variables can refer too) are
objects. Objects are instances of a class. Objects have methods. For
example, the long_string
variable defined above (and repeated below)
is an object of type str
. The str
methods may be called on the variable
by attaching the method (split()
, in this case) to the variable name.
long_string = """
This is a multi-line string.
Triple quotes are used to define strings like this.
"""
long_string.split()
output:
['This', 'is', 'a', 'multi-line', 'string.', 'Triple', 'quotes', 'are', 'used', 'to', 'define', 'strings', 'like', 'this.']
The split
method of the str
object takes the original string, splits it
at each space character, and returns the result as a list.
The numerical model objects of PFC, FLAC3D, and 3DEC are represented as
objects in Python. For example there is a Ball
object to represent PFC
balls, or a Zone
object to represent FLAC3D zones. As seen here with the
built-in Python object type String
, Itasca software model objects have
properties and methods. Refer to the sections on using Python with each code
for further information.
Interactive Documentation
The IPython console displays interactive completion and inline documentation to make programming easier. The following figure uses these features to show some of the available methods of string objects.
Pressing the
tab
key at the end of a partially written name will offer interactive completions. Pressingtab
again will cycle through the available names. Pressingenter
selects a completion.Interactive documentation is shown when the
(
character is typed after a function name.Alternatively, adding a
?
character to the end of any Python function, module or object displays inline documentation.
![../../../../../../../_images/ipython_term2.gif](../../../../../../../_images/ipython_term2.gif)
Example File
The source code for this example is basic_python.py.
Was this helpful? ... | Itasca Software © 2024, Itasca | Updated: Aug 13, 2024 |