SlideShare a Scribd company logo
1 of 17
Disclaimer
Though I’ve extensively programmed in Python, I
have ~0 formal programming training.
So some terminology I use may be total gibberish to
those better taught than I.
My mantra is:
“If it works it works, who cares about the fancy
terminology”.
Python version
• Here I will talk about functions within Python
2.6.x / 2.7.x (the JBCA system default)
• The separate development stream of Python
3.x ... Most of what I say won’t work, or will
work very differently.
Why Python?
• The current astronomers favourite...
• CASA (interferometric data reduction package
is written in it).
• Its free! (unlike IDL...*)
• *I’m yet to find something IDL can do that
Python can’t...
Why Python?
• First we need to set up which version of python your linux box
will default to.
• In your home area type:
>emacs –nw .cshrc
• This will open an in terminal text editor.
• Press the down key until you see the line:
#USER MODIFICATIONS
• After this type
alias python2.7 ‘/usr/local/lib/python2.7/bin/python2.7’
• The type ctrl-x ctrl-s. Close your terminal and open another
and we’re good to go.
BEFORE GETTING STARTED
Getting started
• From the command line ‘python’ will get you
into the python environment. Within which
you can start some basic work. e.g.
>>> a=3.141*0.005
>>> b=7.0**2.0
>>> c=a+b
>>> print c
49.015705
Scripting
• Adding those lines into a file named e.g.
‘test.py’ will then be executable by the
command
>python test.py
Will result in ...
49.015705
Dynamic whitespace
• In python whitespace is important, unlike e.g.
Perl. Your left hand indentation matters.
So this will work:
for x in range(len(array)):
print x
y=x**2.7
print y
print y # will print the last
#value of y
This won’t:
for x in range(len(array)):
print x
y=x**2.7
print y
print y # we’ll have crashed
#before we reach here
• Remember for later your ‘if’s, ‘elif’s and
‘else’s need to line up!
Importing modules
• A lot of functionality can be imported into your scripts with import
commands e.g.
import numpy
• As python is object orientated you call a ‘numpy’ task as follows:
numpy.sqrt(2.0) #will give us square-root of 2
• But because we’re lazy we don’t want to type numpy over and over so we
can instead use:
import numpy as np
• So the above becomes
np.sqrt(2.0) #will still give us square-root of 2
Importing modules 2.
• Some times we only want a couple of functions from a
module for this we can use a ‘from’:
from numpy import sqrt , other_function
• Now:
sqrt(2.0) #will give us what we’re after
Why isn’t there a function for this?
• If the function you’re after doesn’t exist... Write your own!
• In your code you can create your own functions, here is an
example:
def my_function(arg1, arg2):
z=np.sqrt(arg1)*np.exp(arg2)
return z
• Which can then be called later in your code simply as:
something=my_function(arg1, arg2)#something will then == z
• With the same number of arguments.
Example functions
• Example functions I’ve created:
1. Calculating colour-colour plots from incomplete data lists.
2. Find the peak flux in a spectrum.
3. Finding Zeeman split line pairs and calculating the local magnetic
field strength in ex-OH masers.
4. Calculating the rms noise in an ALMA map... Etc etc
• Functions are good because they mean you don’t have to re-
type code umpteen times throughout a script.
Useful python modules for Astronomy
• numpy – array and matrix mathematics, nice
load from txt options...
• scipy – Scientific functions, e.g. correlation,
signal processing, ffts...
• matplotlib – plotting... Makes beautiful plots.
• pyfits – FITS file manipulation.
• astropy - many useful astronomy modules and
packages all in one...
• APLpy for making nice FITS images.
Examples
resFOV.py
Basic syntax stuff and quick plot
Page 1 of 2
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1.0,10.0,1.0) #creates an array from 1 to 9
for value in x:
if value ==4.0:
print “wow a 4!”
elif value == 5.0:
print “and now a 5!”
else:
print value
y=np.sqrt(np.exp(x)) #just for something to plot against x!
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111) #sets up a plot environment to
# plot on
ax1.plot(x,y,’bo-’) #plots x v. y , ‘bo-’ sets it to
#plot blue circles with a solid
#line joining them
ax1.set_xlabel(‘x’)
ax1.set_ylabel(‘y’) #take a guess!
plt.show() #shows our plot
Basic syntax stuff and quick plot
Page 2 of 2
Challenge
• Using the basics demonstrated in this tutorial
write a script which calculates the
Schwarzschild radius for black holes of mass =
to each of the solar system planets.
• Extra credit, plot mass vs. radii and label each
planet.

More Related Content

What's hot

OpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersOpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersDhanashree Prasad
 
Concurrent Programming OpenMP @ Distributed System Discussion
Concurrent Programming OpenMP @ Distributed System DiscussionConcurrent Programming OpenMP @ Distributed System Discussion
Concurrent Programming OpenMP @ Distributed System DiscussionCherryBerry2
 
Short introduction to Storm
Short introduction to StormShort introduction to Storm
Short introduction to StormJimmyZoger
 
Parallelization using open mp
Parallelization using open mpParallelization using open mp
Parallelization using open mpranjit banshpal
 
How my visualization tools use little memory: A tale of incrementalization an...
How my visualization tools use little memory: A tale of incrementalization an...How my visualization tools use little memory: A tale of incrementalization an...
How my visualization tools use little memory: A tale of incrementalization an...Eugene Kirpichov
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 
BWB Meetup: Storm - distributed realtime computation system
BWB Meetup: Storm - distributed realtime computation systemBWB Meetup: Storm - distributed realtime computation system
BWB Meetup: Storm - distributed realtime computation systemAndrii Gakhov
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Machine Learning Lecture Series Lecture 2
Machine Learning Lecture Series Lecture 2Machine Learning Lecture Series Lecture 2
Machine Learning Lecture Series Lecture 2MuhammadRizwanMunawa1
 
Unity best practices (2013)
Unity best practices (2013)Unity best practices (2013)
Unity best practices (2013)Benjamin Robert
 

What's hot (15)

Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
OpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersOpenMP Tutorial for Beginners
OpenMP Tutorial for Beginners
 
Concurrent Programming OpenMP @ Distributed System Discussion
Concurrent Programming OpenMP @ Distributed System DiscussionConcurrent Programming OpenMP @ Distributed System Discussion
Concurrent Programming OpenMP @ Distributed System Discussion
 
Short introduction to Storm
Short introduction to StormShort introduction to Storm
Short introduction to Storm
 
Parallelization using open mp
Parallelization using open mpParallelization using open mp
Parallelization using open mp
 
How my visualization tools use little memory: A tale of incrementalization an...
How my visualization tools use little memory: A tale of incrementalization an...How my visualization tools use little memory: A tale of incrementalization an...
How my visualization tools use little memory: A tale of incrementalization an...
 
OpenMP
OpenMPOpenMP
OpenMP
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
BWB Meetup: Storm - distributed realtime computation system
BWB Meetup: Storm - distributed realtime computation systemBWB Meetup: Storm - distributed realtime computation system
BWB Meetup: Storm - distributed realtime computation system
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Open mp intro_01
Open mp intro_01Open mp intro_01
Open mp intro_01
 
Open mp directives
Open mp directivesOpen mp directives
Open mp directives
 
Machine Learning Lecture Series Lecture 2
Machine Learning Lecture Series Lecture 2Machine Learning Lecture Series Lecture 2
Machine Learning Lecture Series Lecture 2
 
Return Oriented Programming
Return Oriented ProgrammingReturn Oriented Programming
Return Oriented Programming
 
Unity best practices (2013)
Unity best practices (2013)Unity best practices (2013)
Unity best practices (2013)
 

Viewers also liked

2do A Devesa Berasi Tubbia Garcia Tecnologia
2do A Devesa Berasi Tubbia Garcia Tecnologia2do A Devesa Berasi Tubbia Garcia Tecnologia
2do A Devesa Berasi Tubbia Garcia TecnologiaLucia Julia Berasi Garcia
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonHarry Potter
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheTony Nguyen
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteTony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonFraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksHarry Potter
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonFraboni Ec
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonHarry Potter
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsTony Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsHarry Potter
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friendHarry Potter
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous classFraboni Ec
 

Viewers also liked (20)

2do A Devesa Berasi Tubbia Garcia Tecnologia
2do A Devesa Berasi Tubbia Garcia Tecnologia2do A Devesa Berasi Tubbia Garcia Tecnologia
2do A Devesa Berasi Tubbia Garcia Tecnologia
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Api crash
Api crashApi crash
Api crash
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Poo java
Poo javaPoo java
Poo java
 
Learning python
Learning pythonLearning python
Learning python
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Inheritance
InheritanceInheritance
Inheritance
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Api crash
Api crashApi crash
Api crash
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
 

Similar to Python your new best friend

Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"Fwdays
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfMichpice
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxnyomans1
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxJeromeTacata3
 
Python introduction
Python introductionPython introduction
Python introductionRoger Xia
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on pythonShubham Yadav
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Introduction to Python Programming .pptx
Introduction to Python Programming .pptxIntroduction to Python Programming .pptx
Introduction to Python Programming .pptxtilakrajpanchal22600
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
if, while and for in Python
if, while and for in Pythonif, while and for in Python
if, while and for in PythonPranavSB
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 

Similar to Python your new best friend (20)

Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"Travis Oliphant "Python for Speed, Scale, and Science"
Travis Oliphant "Python for Speed, Scale, and Science"
 
Python for ML.pptx
Python for ML.pptxPython for ML.pptx
Python for ML.pptx
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
ACM init()- Day 4
ACM init()- Day 4ACM init()- Day 4
ACM init()- Day 4
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptx
 
Python introduction
Python introductionPython introduction
Python introduction
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on python
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
SnW: Introduction to PYNQ Platform and Python Language
SnW: Introduction to PYNQ Platform and Python LanguageSnW: Introduction to PYNQ Platform and Python Language
SnW: Introduction to PYNQ Platform and Python Language
 
Introduction to Python Programming .pptx
Introduction to Python Programming .pptxIntroduction to Python Programming .pptx
Introduction to Python Programming .pptx
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
if, while and for in Python
if, while and for in Pythonif, while and for in Python
if, while and for in Python
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Kaggle tokyo 2018
Kaggle tokyo 2018Kaggle tokyo 2018
Kaggle tokyo 2018
 

More from Fraboni Ec

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreadingFraboni Ec
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreadingFraboni Ec
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceFraboni Ec
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningFraboni Ec
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningFraboni Ec
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryFraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksFraboni Ec
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheFraboni Ec
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsFraboni Ec
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonFraboni Ec
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesFraboni Ec
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsFraboni Ec
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileFraboni Ec
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisFraboni Ec
 
Abstract class
Abstract classAbstract class
Abstract classFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 

More from Fraboni Ec (20)

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Lisp
LispLisp
Lisp
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreading
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Abstract class
Abstract classAbstract class
Abstract class
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 

Recently uploaded (20)

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 

Python your new best friend

  • 1. Disclaimer Though I’ve extensively programmed in Python, I have ~0 formal programming training. So some terminology I use may be total gibberish to those better taught than I. My mantra is: “If it works it works, who cares about the fancy terminology”.
  • 2. Python version • Here I will talk about functions within Python 2.6.x / 2.7.x (the JBCA system default) • The separate development stream of Python 3.x ... Most of what I say won’t work, or will work very differently.
  • 3. Why Python? • The current astronomers favourite... • CASA (interferometric data reduction package is written in it). • Its free! (unlike IDL...*) • *I’m yet to find something IDL can do that Python can’t...
  • 5. • First we need to set up which version of python your linux box will default to. • In your home area type: >emacs –nw .cshrc • This will open an in terminal text editor. • Press the down key until you see the line: #USER MODIFICATIONS • After this type alias python2.7 ‘/usr/local/lib/python2.7/bin/python2.7’ • The type ctrl-x ctrl-s. Close your terminal and open another and we’re good to go. BEFORE GETTING STARTED
  • 6. Getting started • From the command line ‘python’ will get you into the python environment. Within which you can start some basic work. e.g. >>> a=3.141*0.005 >>> b=7.0**2.0 >>> c=a+b >>> print c 49.015705
  • 7. Scripting • Adding those lines into a file named e.g. ‘test.py’ will then be executable by the command >python test.py Will result in ... 49.015705
  • 8. Dynamic whitespace • In python whitespace is important, unlike e.g. Perl. Your left hand indentation matters. So this will work: for x in range(len(array)): print x y=x**2.7 print y print y # will print the last #value of y This won’t: for x in range(len(array)): print x y=x**2.7 print y print y # we’ll have crashed #before we reach here • Remember for later your ‘if’s, ‘elif’s and ‘else’s need to line up!
  • 9. Importing modules • A lot of functionality can be imported into your scripts with import commands e.g. import numpy • As python is object orientated you call a ‘numpy’ task as follows: numpy.sqrt(2.0) #will give us square-root of 2 • But because we’re lazy we don’t want to type numpy over and over so we can instead use: import numpy as np • So the above becomes np.sqrt(2.0) #will still give us square-root of 2
  • 10. Importing modules 2. • Some times we only want a couple of functions from a module for this we can use a ‘from’: from numpy import sqrt , other_function • Now: sqrt(2.0) #will give us what we’re after
  • 11. Why isn’t there a function for this? • If the function you’re after doesn’t exist... Write your own! • In your code you can create your own functions, here is an example: def my_function(arg1, arg2): z=np.sqrt(arg1)*np.exp(arg2) return z • Which can then be called later in your code simply as: something=my_function(arg1, arg2)#something will then == z • With the same number of arguments.
  • 12. Example functions • Example functions I’ve created: 1. Calculating colour-colour plots from incomplete data lists. 2. Find the peak flux in a spectrum. 3. Finding Zeeman split line pairs and calculating the local magnetic field strength in ex-OH masers. 4. Calculating the rms noise in an ALMA map... Etc etc • Functions are good because they mean you don’t have to re- type code umpteen times throughout a script.
  • 13. Useful python modules for Astronomy • numpy – array and matrix mathematics, nice load from txt options... • scipy – Scientific functions, e.g. correlation, signal processing, ffts... • matplotlib – plotting... Makes beautiful plots. • pyfits – FITS file manipulation. • astropy - many useful astronomy modules and packages all in one... • APLpy for making nice FITS images.
  • 15. Basic syntax stuff and quick plot Page 1 of 2 import numpy as np import matplotlib.pyplot as plt x=np.arange(1.0,10.0,1.0) #creates an array from 1 to 9 for value in x: if value ==4.0: print “wow a 4!” elif value == 5.0: print “and now a 5!” else: print value y=np.sqrt(np.exp(x)) #just for something to plot against x!
  • 16. fig1 = plt.figure(1) ax1 = fig1.add_subplot(111) #sets up a plot environment to # plot on ax1.plot(x,y,’bo-’) #plots x v. y , ‘bo-’ sets it to #plot blue circles with a solid #line joining them ax1.set_xlabel(‘x’) ax1.set_ylabel(‘y’) #take a guess! plt.show() #shows our plot Basic syntax stuff and quick plot Page 2 of 2
  • 17. Challenge • Using the basics demonstrated in this tutorial write a script which calculates the Schwarzschild radius for black holes of mass = to each of the solar system planets. • Extra credit, plot mass vs. radii and label each planet.