Even without the scientific packages, Python provides readable, easy-to-use variables and data structures. There are already very good tutorials on these topics from a computer science perspective, such as Learn Python the Hard Way. This will be a quick overview of the basics before moving on to engineering applications.
Defining variables (no type declaration):
a = 5 # this is a comment
b = 10.0
c = 'this is a string'
print "Output = " + str(a) + ", " + str(b)
Lists and loops:
L = [10.0, 3.0, 'some words', 2]
for item in L:
print(item)
If statements: As with for
loops, these require :
characters at the end of the line. Other lines in Python do not require line ending characters. Use and
and or
keywords to connect multiple logical statements.
if a==5:
print("a is 5")
elif a==3:
print("a is 3")
else:
print("a is neither 5 nor 3")
Whitespace: As you see in the previous examples, whitespace matters in Python. There are no brackets {}
to denote code blocks. Use either spaces or tabs to indent for
loops and if
statements.
Ranges and slicing:
The range()
function returns a sequence of integers in a list. Its arguments are (start, stop, step)
, and the stop
value is not included in the range. Only stop
is required; default values for start
and step
are 0 and 1, respectively.
L = range(1,10,2)
print(L)
count = 0
for i in range(10):
count += i
print(count)
Slicing (retrieving values from a list) follows a similar syntax: start:stop:step
. Any of these can be omitted with the same default values as above. This is important, because later we'll use NumPy arrays and matrices with the same syntax for indexing.
L = range(10)
print L[0] # get a single value (Python indices start at 0)
print L[5:] # values 5-end
print L[:5] # values start-5
print L[3:9:2] # values 3-9 in steps of 2
print L[::-1] # whole list with step=-1 (reverse order)
Lists may look like vectors, but in general they are too slow to use for scientific computing applications, especially if you append
new values to the end of the list. In the next tutorial, NumPy will solve that issue for us.
Dictionaries: A set of key-value pairs, which you can think of as a lookup table. Unlike lists, the values in a dictionary are not ordered, and they are indexed with strings instead of integers. Lookups are very fast because you don't have to search for items.
person = {'name': 'Terry', 'age': 42, 'weight': 160}
print('This person is named ' + person['name'] + ' and they are ' + str(person['age']) + ' years old')
Combining lists and dicts: Both data structures are flexible enough to accept values of any type. This means you can have a list of dictionaries, a dictionary of lists, and any number of nested combinations you can think of! Dictionaries are a good way to handle data in your program, even more complicated objects like matrices, because the items are easy to access.
person_2 = {'name': 'Chris', 'age': 31, 'weight': 155}
people = [person, person_2]
company = {'workers': people, 'num_workers': len(people)}
for p in company['workers']:
print p['name']
Functions: A function accepts one or more arguments and returns a value. We've already seen the range()
function, for example, but we can define our own too. The arguments and return values can be any type, including lists and dicts.
def square(x):
return x**2
def square_list(L):
return [square(x) for x in L] # this is called a "list comprehension" -- makes things easy
print(square(5))
print(square_list(range(10)))
Keyword arguments: Functions can accept either positional or keyword arguments. Positional arguments are identified by their order, while keyword arguments are explicitly named and may be given a default value in the function definition.
def square(x, a=0):
return (x+a)**2
print(square(5))
print(square(5,2))
Again, this is only an overview of the Python language. Whenever you see syntax you don't recognize, you should check whether it comes from Python itself or from a particular scientific package. Spend some time with Learn Python the Hard Way for a much more detailed tutorial of the language.
On to engineering! Part 2: NumPy and Matplotlib