DOC PREVIEW
Introduction to Python

This preview shows page 1-2-3-26-27-28 out of 28 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 28 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Introduction to Pythonand Python/EMANSteve [email protected] History8512 documented languages (vs. 2376)●Four of the first modern languages (50s):–FORTRAN (FORmula TRANslator)–LISP (LISt Processor)–ALGOL–COBOL (COmmon Business Oriented Language)●C (1972)●C++ (1983)●Perl (1990)●Python (1991)●Ruby (1992)●HTML (1994)●Java (1995)Python ?PYTHON OOL- developed by Guido van Rossum, and named after Monty Python.(No one Expects the Inquisition) a simple high-level interpreted language. Combines ideas from ABC, C, Modula-3, and ICON. It bridges the gap between C and shell programming, making it suitable for rapid prototyping or as an extension of C. Rossum wanted to correct some of the ABC problems and keep the best features. At the time, he was working on the AMOEBA distributed OS group, and was looking for a scripting language with a syntax like ABC but with the access to the AMOEBA system calls, so he decided to create a language that was extensible; it is OO and supports packages, modules, classes, user-defined exceptions, a good C interface, dynamic loading of C modules and has no arbritrary restrictions.www.python.orgSo, why not X ?●C/C++ : Fast code, good reusability, but: risky, pointers, memory management, hard for beginners●Fortran 77/90/95 - yeeech●Java : Strongly structured, enforces good programming, but: a pain to use, many portability/version problems, language gets in the way of getting work done●Perl - Great for text processing, concise syntax, but impossible to learn, remember syntax, or write clean code●Tcl - Used as embedded control language, and provided Tk, but very limited language features, somewhat difficult syntaxPython Features●Simple, easy to learn●Gigantic set of built-in libraries●Portable (virtually all computers/OS supported)●Interpreted and byte-compiled (like Java)●Object oriented●Very popular for application scripting (especially in scientific apps)●Python for high-level work, with compute-intensive work in C++/Fortran librariesHello World●Pythonprint “Hello, world!”●Perlprint "Hello, world!\n";●C:#include <stdio.h>main() { printf(“Hello, world!\n”); exit(0);}The first program you learn in any programming language.EMAN2>>> from EMAN2 import *>>> img=test_image()>>> imgs=EMData.read_images(“imgs.hed”) <-- reads all images>>> imgs[0].get_attr_dict()...>>> for i in imgs: print i.get_attr(“maximum”)...>>> img=EMData()>>> img.read_image(“file.mrc”)>>> print img.get_xsize(),img.get_ysize,img.get_zsize()...>>> for i in imgs[1:]: imgs[0]+=i>>> imgs[0]/=len(imgs)>>> display(imgs[0])>>> imgs[0].write_image(“out.mrc”)● dump_processors()● dump_processors_list() - introspectiona=EMData()...b=a.process(“nam e”,{ “m”:2.0, ”b ”:1. 0})- or -a.process_inplace(“name ”, {key:value,key:value})- or -# if initialization is expensivep=Processor.get(“nam e”, {k:v,k:v})for i in imgs:p.process_inplace(i)Using a Processor● dump_aligners()●newimg=img.align(“ name” ,img2,{k:v},” cmpname” ,{k,v})● dump_cmps()●img.cmp(“n ame”, img2,{k:v})● dump_projectors()●prj=vol.project(“n ame”, {k:v,k:v})Other Modular classesOther Modular classes● dump_reconstructors()r=Reconstructors.get(“ name” ,{k:v,k:v})r.setup()r.insert_slice(img,Transform3D)...vol=r.finish()● dump_averagers()r=Averagers.get(“ name”, {k:v,k:v})r.add_image(img)...avg=r.finish()Interactive Python●Python as a calculator●strings, tuples, lists, dictionaries●import (os,math,sys,string,random,etc.)●help()●if, while, for●def●files, readline, readlinesBasic Syntax Reference●Indent●Numbers:0 1.5 1.2e43+2j●Strings:“test string” 'this too'“””multiple linestring”””●Lists:lst=[1,2,'abc',1+3j]lst[0]●Dictionaries:dict={'key1':'value1','key2':'value2',3:'value3'}dict['key2']dict[3]●import:import osfrom math import *●print:print 'x=',x,' y=',yprint 'x=%f y=%f'%(x,y)●if,else:if x>5: print “x>5”elif x<0: print “x<0”else: print “0<x<5”●for loops:for i in list: print i●while loops:while x<10: print x x*=1.5Python as a Calculator> python >>> 5*10 <-- Note that bold italics indicate what you should type at the prompt50>>> 5*10/316>>> 5.0*10/316.666666666666668>>> 5**225>>> 5**3125>>> sqrt(4)Traceback (most recent call last): File "<pyshell#5>", line 1, in -toplevel- sqrt(4)NameError: name 'sqrt' is not definedPython as a Calculator>>> import math <-- before we use special math functions, we need to 'import' the>>> math.sqrt(4) math library2.0>>> math.sqrt(-1) <-- normal math library does not support imaginary numbersTraceback (most recent call last): File "<pyshell#2>", line 1, in -toplevel- math.sqrt(-1)ValueError: math domain error>>> import cmath <-- cmath stands for 'complex math' and supports complex numbers>>> cmath.sqrt(-1)1j>>> from math import * <-- the '*' is a wildcard meaning read everything, after doing>>> pi this, all math operations are available without 'math.'3.1415926535897931>>> sin(pi/2)1.0Your Own Functions>>> def y(m,x,b): <-- Now we define it as an actual function we can re-usereturn m*x+b>>> y(1,2,3) <-- Call the function with m=1, x=2 and b=35>>> f(1.0,2,3)5.0>>> def g(x,y):return float(x)**int(y) <-- '**' means raise to the power of in python>>> g(5.0,3)125.0>>> g(5,3.0)(what do you think?)>>> cos(pi)-1.0>>> def cos(x): return x+1.0>>> cos(pi)4.1415926535897931Simple Strings>>> "Hello there" <--- A simple string'Hello there'>>> 'Hello there' <--- Single quotes equivalent to double'Hello there'>>> """Hello There""" <--- Triple-double-quotes let you span multiple lines'Hello There'>>> "'Hello' there""'Hello' there">>> print "'Hello' there"'Hello' there>>> print """This is amultiline string, denoted bytriple quotes"""This is amultiline string, denoted bytriple quotesString Slicing and Dicing>>> "Hello there world"'Hello there world'>>> “Hello there world”[1] <-- Returns element number 1 from the string'e' but the first element is 0, so 1 is the second>>> "Hello there world"[6:11] <-- A 'slice of the string, the 7th thru 11th elements'there' the last element (number 11) is never included>>> "Hello there world"[:5] <-- Starts at the beginning if the first number'Hello' is missing>>> "Hello there world"[-5:] <-- Negative values count from the END of the'world' string, if the 2nd number is missing, go to end 111111101234567890123456 <-- counting from the beginningHello there


Introduction to Python

Download Introduction to Python
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Introduction to Python and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Introduction to Python 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?