0% found this document useful (0 votes)
132 views

Python Introduction 2019

Python is a high-level, easy to learn programming language with many advanced features and libraries available for tasks like physics, astronomy, and data analysis. It has good scientific computing libraries and is useful for physics work, though other languages may be faster for efficiency-critical code. Python can be learned through online tutorials and documentation, and its core containers like lists and dictionaries provide flexible ways to store and access data.

Uploaded by

Daniel Hockey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views

Python Introduction 2019

Python is a high-level, easy to learn programming language with many advanced features and libraries available for tasks like physics, astronomy, and data analysis. It has good scientific computing libraries and is useful for physics work, though other languages may be faster for efficiency-critical code. Python can be learned through online tutorials and documentation, and its core containers like lists and dictionaries provide flexible ways to store and access data.

Uploaded by

Daniel Hockey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Why Python?

Python is a mature high-level language that is easy to learn but with many
advanced features.
“Batteries Included”: many packages and libraries available.
Python is increasingly used in physics, astronomy and data analytics
http://www.timteatro.net/2010/07/21/why-every-physicist-should-know-python/
http://bellm.org/blog/2011/05/27/why-astronomers-should-program-in-python/
Python comes with many scientific libraries (see later slide)
However Python is not perfect for everything and in cases where efficiency
and speed are needed, code is still written in C/C++ and called from
Python.
However, Python is the most generally-useful programming language for
Physics today due to the scientific modules that are available!
Python Scientific Libraries

● Gammalib: http://gammalib.sourceforge.net/ e.g. to deal with FITS


How to learn Python?
Many online resources and tutorials.
Python Course: http://www.python-course.eu/
Python Programming Tutorial: http://www.programiz.com/python- programming
Python Documentation ( including a Tutorial):
https://docs.python.org/2.7/
https://docs.python.org/3.4/index.html.
Containers
The most common Python containers (e.g. see
https://docs.python.org/2.7/tutorial/datastructures.html) :

lists: ordered sequence, fast access, repeatable values, mutable


tuples: ordered sequence, fast access, repeatable values, immutable, faster than
lists, use if data is not to be changed
strings: ordered sequence of characters, fast access, repeatable values,
immutable
dictionaries: no a priori order, unique key, fast key access, mutable. sets:
unordered collection with no duplicate elements, mutable.
Strings
strings are sequences of characters.
strings are not changeable (“immutable”) strings are made with:
single quotes (')

'This is a string with single quotes'

double quotes (")



"Obama's dog is called Bo"

triple quotes, both single (''') and (""") 



'''String in triple quotes can extend

over multiple lines, like this on, and can contain

'single' and "double" quotes.'''
Lists & Strings
Lists & Strings

https://docs.python.org/2.7/library/stdtypes.html#string-methods
Read from the keyboard
To read a string from the keyboard use input(‘Prompt: ‘), e.g.

• s=input('Please enter something: ')


• To convert use the functions: float(), int(), complex(), e.g.
• s=float(input('Please enter a number: ‘))
Or one can split the string and convert different parts of the list individually.
If you try to convert something that is incompatible (e.g. characters to a float) an
error will occur.
Lists
>>> cubes = [1, 8, 27, 65, 125]
[1, 8, 27, 65, 125]
>>> cubes[3]=64
[1, 8, 27, 64, 125]
>>> cubes=cubes+[216, 343, 512]
[1, 8, 27, 64, 125, 216, 343, 512]
>>> cubes.append(729)
[1, 8, 27, 64, 125, 216, 343, 512, 729]
>>> cubes[2:4]=[] # removing elements
[1, 8, 125, 216, 343, 512, 729]
>>> cubes[2:2]=[27,64] # inserting elements
[1, 8, 27, 64, 125, 216, 343, 512, 729]
To check if an item is in a list or string use in or not in:

>>> "a" in abc >>> str = "Python is easy!"


>>> "y" in str
True True
>>> "x" in str
>>> "a" not in abc False
False
>>> "e" not in abc
False
>>> "f" not in abc
True
Operations on Containers
Dictionaries
Dictionaries contain (key, value) pairs.
Items are access via their key and not their position (as withs strings and
lists) They can be easily changes and shrink and grow as needed....
Dictionaries

>>> city = {"New York City":8175133, "Los Angeles": 3792621,


"Washington":632323, "Chicago": 2695598, "Toronto":2615060,
"Montreal":11854442, "Ottawa":883391, "Boston":62600}
>>> city["New York City"]
8175133
>>> city["Toronto"]
2615060
>>> city["Halifax"] = 390096
>>> city
{'Toronto': 2615060, 'Ottawa': 883391, 'Los Angeles': 3792621,
'Chicago': 2695598, 'New York City': 8175133, 'Halifax':
390096, 'Boston': 62600, 'Washington': 632323, 'Montreal':
11854442}
>>> city = {}
>>> city
{}
Conditional Statements
>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x=0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
More
for Loops
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print w, len(w)
...
cat 3
window 6
defenestrate 12
for Loops
# Script:

edibles = ["ham", "spam","eggs","nuts"]


Produces output:
for food in edibles:
Great, delicious ham
if food == "spam": No more spam please!
Finally, I finished stuffing myself
print("No more spam please!")

break

print("Great, delicious " + food)

else:

print("I am so glad: No spam!")

print("Finally, I finished stuffing


myself")

Great, delicious ham


Remove spam from the list and the output is: Great, delicious eggs
Great, delicious nuts
Finally, I finished stuffing myself
Modules
Scipy, Numpy, Matplotlib,
Gammalib
Main Reference
http://www.scipy.org

Fantastic online tutorials:


http://scipy-lectures.github.io
Numpy is compiled C code and should be much faster than the Python equivalent.
Good Guide: http://www.engr.ucsb.edu/~shell/che210d/numpy.pdf

GammaLib is a versatile toolbox for the high-level analysis of astronomical gamma-ray


data. Implement the FITS interface
http://gammalib.sourceforge.net/
Numpy
Some useful functions for creating arrays (not exhaustive!):
ones() % an array filled with 1s
zeros() % an array filled with 0s
arange() % evenly spaced values in a given interval [start,stop)
(last pt. not included)
Usage: numpy.arange([start, ]stop, [step, ]dtype=None)
start, and step are optional and default to 0 and 1
respectively
linspace() % evenly spaced values in range [start,stop] (end pt. included)
Usage: numpy.linspace(start, stop, num=50,...)
Number of points are specified but can be changed with

logspace() % evenly spaced on a log scale. Note start and


stop values should be the log of the start and
stop you want as it generates in the interval
[start**10, stop**10]
Numpy arrays
Numpy arrays
Numpy Math
Numpy has its own math routines that you should use with numpy arrays:
http://docs.scipy.org/doc/numpy/reference/routines.math.html
All operations are vectorised, i.e. they operate on all elements of the array.
Example:
>>> x=np.linspace(0,10,10)
>>> y=np.sin(x)
Matplotlib
Matplotlib
Matplotlib
Files: different ways to read
#!/usr/bin/python
the name of the file to read
import sys
was used as an argument to
f=open(sys.argv[1]) --→
the program
print f
********************************************
import numpy
x,dx=numpy.loadtxt('test.dat',unpack=True)
ok = numpy.where(x>dx)
********************************************
import gammalib
import cscripts
import numpy

# Read spectrum file


fits = gammalib.Gfits(filename)
table = fits.table(1)

# Extract columns dependent on flux type


if table.contains('EnergyFlux'):
c_flux = table['EnergyFlux']
Until next week:
● Plot points with error bars from file spectrum.dat (in the WORK directory);
connect points with line. If error bar is larger than the value, then it should
be upper limit. Think whether you need lin or log scale.
● Create a file with some text, count how many different words you have in
the text and find out which word is the most common one ( use dictionary
for this task ).
● plot histogram illustrating distribution of words with different length in the
text.
● Look trough new papers in https://arxiv.org/
● Ctools are installed on cheetah
● To initiate: export GAMMALIB=/usr/local/gamma
source $GAMMALIB/bin/gammalib-init.sh
export CTOOLS=/usr/local/gamma
source $CTOOLS/bin/ctools-init.sh
● Follow the tutorial on how to run ctools
http://cta.irap.omp.eu/ctools/users/tutorials/index.html

You might also like