#!/usr/bin/python |
Comments are supported in the same style as Perl:
|
Python supports the following data types:
|
Example:
bool = True |
|
Variable Scope:
Most variables in Python are local in scope to their own function or
class. For instance if you define a = 1 within
a function, then a will be available within that
entire function but will be undefined in the main program that calls the
function. Variables defined within the main program are accessible to
the main program but not within functions called by the main program.
Global Variables: Global variables, however, can be declared with the global keyword.
a = 1 |
Some basic Python statements include:
|
Examples:
print "Hello World" |
|
Python expressions can include: a = b = 5 #The assignment statement b += 1 #post-increment c = "test" import os,math #Import the os and math modules from math import * #Imports all functions from the math module |
Operators:
|
Maths:
|
Strings can be specified using single quotes or double quotes.
Strings do not expand escape sequences unless it is defined as a raw string
by placing an r before the first quote:
print 'I\'ll be back.'. print r'The newline \n will not expand' a = "Gators" print "The value of a is \t" + a -> The value of a is Gators If a string is not defined as raw, escapes such as may be used. Optional syntax: Strings that start and end with """ may span multiple lines: print """ This is an example of a string in the heredoc syntax. This text can span multiple lines """ |
String Operators: Concatenation is done with the + operator. Converting to numbers is done with the casting operations: x = 1 + float(10.5) #$x=11.5, float x = 4 - int("3") #$x=1, int You can convert to a string with the str casting function: s = str(3.5) name = "Lee" print name + "'s number is " + str(24) Comparing Strings: Strings can be compared with the standard operators listed above: ==, !=, <, >, <=, and >=. | |
String Functions:
s = "Go Gators! Come on Gators!" |
Array Operators:
|
Array Functions:
|
|
Examples:
if a > b: print "a is greater than b"; |
|
Examples:
for j in range(10): print "Value number " + str(j) +" is "+value[j] |
|
Python supports OOP and classes to an extent, but is not a full OOP language.
A class is a collection of variables and functions working with these
variables. Classes are defined somewhat similarly to Java, but differences
include
|
being used in place of this
and constructors being named instead
of classname. Also note that must
be used every time a class-wide variable is referenced and must be the first
argument in each function's argument list, including the constructor. In
addition, functions and constructors cannot be overloaded, but as discussed
above, do support default arguments instead. Like functions, a class must
be defined before it can be instantiated. In Python, all class members are
public.
Example Class: class Rectangle: #Optionally define variable width width = 0 #Constructor with default arguments def __init__(self, width = 0, height = 0): self.width = width self.height = height #functions def setWidth(self, width): self.width = width def setHeight(self, height): self.height = height def getArea(self): return self.width * self.height arect = Rectangle() #create a new Rectangle with dimensions 0x0. arect.setWidth(4) arect.setHeight(6) print arect.getArea() -> 24 rect2 = Rectangle(7,3) #new Rectangle with dimensions 7x3. Extended Class: class RectWithPerimeter(Rectangle): #add new functions def getPerimeter(self): return 2*self.height + 2*self.width def setDims(self, width, height): #call base class methods from Rectangle Rectangle.setWidth(self, width) Rectangle.setHeight(self, height) arect = RectWithPerimeter(6,5) #Uses the constructor from Rectangle because no new constructor is provided to override it. print arect.getArea() #Uses the getArea function from Rectangle and prints 30. print arect.getPerimeter() #Uses getPerimeter from RectWithPerimeter and prints 22. arect.setDims(4,9) #Use setDims to change the dimensions. |
|
Examples: file = open("data/teams.txt","rb") team = "nonempty" while (team != ""): team = file.readline() if (team != ""): print team[:-1] #get rid of extra newline character file.close() file = open("data/teams.txt","rb") team = file.readlines() file.close() list = ["Florida","Clemson","Duke"] file = open("data/teams.txt","wb") for j in list: file.write(j+"\n") file.close() import pickle, fcntl player = Player("J.J. Redick", "Duke", 4) file = open("data/players.txt", "a") fcntl.flock(file.fileno(), fcntl.LOCK_EX) pickle.dump(player, file) fcntl.flock(file.fileno(), fcntl.LOCK_UN) file.close() |
FITS files: Python supports FITS files via the module
Now that you have a FITS object, you can access its header and data. Since each object within a file can have its own header and data, you would access the primary header as and the data as . Headers:You can print the entire header by calling the x[0].header.ascardlist() method. You can access individual elements in the header directly by keyword ( ) or by index ( ). If you know that a keyword is already present in the header, you can update its value using the same notation: x[0].header['NAXIS1'] = 265 But if the keyword might not be present and you want to add it if it isn't, use the update() method instead: x[0].header.update('NAXIS1',265) Data: Since the data is an array, you can use any methods on it. The data can thus be accessed using slice notation as well. print shape(x[0].data) print x[0].data[0:5,0:5] Writing FITS Files: Once the data and header have been modified, you can write them back to a new FITS file using writeto(string). This writes to a new file and closes that file, but further operations can still be done on the data in memory. Note that if a file exists with the specified name, it will NOT be overwritten and an error will be raised. To close the input file, use x.close(). |
. Once this module has been imported,
you can read and write FITS files. FITS files are read and stored in
and HDUList object, which has two components: header and data. The
header is a list-like object and data is usually an array. To read in
a FITS file, use
Examples: x = pyfits.open("NGC3031.fits") x.info() -> Filename: NGC3031.fits No. Name Type Cards Dimensions Format 0 PRIMARY PrimaryHDU 6 (530, 530) UInt8print x[0].header.ascardlist() -> SIMPLE = T BITPIX = 8 NAXIS = 2 NAXIS1 = 530 NAXIS2 = 530 HISTORY Written by XV 3.10aprint x[0].header['NAXIS1'] -> 530 print x[0].header[3] -> 530 print x[0].data[3,0:5] -> [11 11 11 9 9] x[0].data[3,0:3] = array([0,0,0]) print x[0].data[3,0:5] -> [0 0 0 9 9] x[0].data += 5 #using numarray to operate on entire array print x[0].data[3,0:5] -> [ 5 5 5 14 14] x.writeto("new_file.fits") x.close() |
Here is the code for Guess My Number in Python, a program that generates a
random number between 1 and 100 and asks the user to guess it. It will tell
the user if the number is higher or lower after each guess and keep track of
the number of guesses.
#!/usr/bin/python
import random, math
random.seed()
x = math.floor(random.random()*100)+1
z = 0
b = 0
while x != z:
b=b+1
z = input("Guess My Number: ")
if z < x: print("Higher!")
if z > x: print("Lower!")
print("Correct! " + str(b) + " tries.")
|