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

Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
How to build a rest api.pptx
How to build a rest api.pptxHow to build a rest api.pptx
How to build a rest api.pptxFraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksFraboni Ec
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceLuis Goldster
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceHarry Potter
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryHarry Potter
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonTony Nguyen
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous classLuis Goldster
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonHarry Potter
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonTony Nguyen
 

Viewers also liked (20)

Cache recap
Cache recapCache recap
Cache recap
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Python language data types
Python language data typesPython language data types
Python language data types
 
How to build a rest api.pptx
How to build a rest api.pptxHow to build a rest api.pptx
How to build a rest api.pptx
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Abstract class
Abstract classAbstract class
Abstract class
 
Inheritance
InheritanceInheritance
Inheritance
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
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
 
Poo java
Poo javaPoo java
Poo java
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Object model
Object modelObject model
Object model
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 

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 Luis Goldster

Ruby on rails evaluation
Ruby on rails evaluationRuby on rails evaluation
Ruby on rails evaluationLuis Goldster
 
Ado.net & data persistence frameworks
Ado.net & data persistence frameworksAdo.net & data persistence frameworks
Ado.net & data persistence frameworksLuis Goldster
 
Multithreading models.ppt
Multithreading models.pptMultithreading models.ppt
Multithreading models.pptLuis Goldster
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningLuis Goldster
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningLuis Goldster
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryLuis Goldster
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheLuis Goldster
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksLuis Goldster
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsLuis Goldster
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisLuis Goldster
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsLuis Goldster
 
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 siteLuis Goldster
 

More from Luis Goldster (20)

Ruby on rails evaluation
Ruby on rails evaluationRuby on rails evaluation
Ruby on rails evaluation
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Lisp and scheme i
Lisp and scheme iLisp and scheme i
Lisp and scheme i
 
Ado.net & data persistence frameworks
Ado.net & data persistence frameworksAdo.net & data persistence frameworks
Ado.net & data persistence frameworks
 
Multithreading models.ppt
Multithreading models.pptMultithreading models.ppt
Multithreading models.ppt
 
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
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
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
 
Object model
Object modelObject model
Object model
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Abstract class
Abstract classAbstract class
Abstract class
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
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
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
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
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
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
 
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
 
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 pragmaticscarlostorres15106
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

Recently uploaded (20)

Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
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
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
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
 
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)
 
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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

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.