Introduction to Python
Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows) 10.BlueFish (Linux)
Python Version Python Version 2.7.x Download Link : https://www.python.org/downloads/
Python Interactive Shell % python Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. You can type things directly into a running Python session name Andrew name 'Andrew' >>> print "Hello", name Hello Andrew
Lists A compound data type: [5, "Hello", "there", 9.8] [5, "Hello", "there", [1, AI ] ] Use len() to get the length of a list >>> fruits = [ Apple", Banana", Olive"] >>> len(fruits) 3
Use [ ] to index items in the list fruits = [ Apple, Banana ] fruits Apple fruits Banana fruits Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range fruits [-1] Banana' fruits [-2] Apple [0] is the first item. [1] is the second item. Out of range values raise an exception. Negative values go backwards from the last element.
Strings share many features with lists smiles = "C(=N N)N.C(=O O O smiles 'C' smiles smiles[-1] O smiles Use slice notation to get a substring N smiles[10:-4] 'C(=O
String Methods: find, split smiles = "C(=N N)N.C(=O O O smiles.find O smiles.find Use find to find the start of a substring. smiles.find Start looking at position 10. - Find returns -1 if it couldn t find a match. smiles.split Split the string into parts with. as delimiter. 'C(=N N N', 'C(=O O O
String operators: in, not in if "Br" in Brother : print "contains! else: print doesn t contain email_address = tberis if @ not in email_address: email_address += @di.uoa.gr
Lists are mutable - some useful methods fruits = ["Apple", "Banana", "Olive"] fruits.append("strawberry") fruits [ Apple, Banana, Olive, Strawberry ] del fruits ['Banana', 'Olive', 'Strawberry'] #remove an element fruits.reverse() ['Strawberry', 'Olive', 'Banana'] #reverse the elements in a list fruits.sort() ['Banana', 'Olive', 'Strawberry'] #in place sort based of ASCII codes
Tuples: sort of an immutable list yellow = (255, 255, 0) # r, g, b yellow 255 yellow yellow Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
Zipping lists together names [ Themis, Nikos, Despoina ] gender [ Male, Male, Female ] zip(names, gender) [( Themis, Male ), ( Nikos, Male ), ( Despoina, Female )]
Dictionaries Dictionaries are lookup tables. They map from a key to a value. symbol_to_name = { "H": "hydrogen", He helium "Li": "lithium", "C": "carbon O oxygen "N": "nitrogen" } Duplicate keys are not allowed Duplicate values are just fine
Dictionary Key access >>> symbol_to_name = {"H": "hydrogen, He helium "Li": "lithium,"c": "carbon O oxygen "N": "nitrogen } >>> symbol_to_name["c"] Get the value for a given key 'carbon' >>> Z" in symbol_to_name Test if the key exists( in only checks the keys, not the values.) False >>> symbol_to_name[ Z"] [] lookup failures raise an exception. Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: Z' >>> symbol_to_name.get("p", "unknown") Use.get() if you want to return a default value. 'unknown' >>> symbol_to_name.get("c", "unknown") 'carbon >>> symbol_to_name["cu"] = copper Insert a new item >>> symbol_to_name["c"] = calcium Update single item
Keys can be any immutable value Numbers, strings, tuples are valid (immutable). Lists, dictionaries, sets are not valid (mutable). A set is an unordered collection with no duplicate elements. nobel_prize_winners = { (1979, "physics"): ["Glashow", "Salam", "Weinberg"], chemistry Hodgkin biology McClintock
Some useful dictionary methods >>> symbol_to_name = {"H": "hydrogen, He helium "Li": "lithium,"c": carbon O oxygen "N": "nitrogen } >>> symbol_to_name.keys() ['C', 'H O N Li He >>> symbol_to_name.values() ['carbon', 'hydrogen', 'oxygen', 'nitrogen', 'lithium', 'helium'] >>> symbol_to_name.update( {"P": "phosphorous", "S": "sulfur"} ) >>> symbol_to_name.items() [('C', 'carbon H hydrogen O oxygen N nitrogen P phosphorous S sulfur Li lithium He helium >>> del symbol_to_name['c'] >>> symbol_to_name {'H': 'hydrogen', 'O': 'oxygen', 'N': 'nitrogen', 'Li': 'lithium', 'He': 'helium'}
Control Flow Things that are False The boolean value False The numbers 0 (integer), 0.0 (float) The empty string "". The empty list [], empty dictionary {} and empty set set(). Things that are True The boolean value True All non-zero numbers. Any string containing at least one character. A non-empty data structure.
Control flow: if statement x = int(raw_input("please enter #:")) if x print 'Negative number' elif x print 'Zero' elif x print One' else: print 'More than one no switch case statements in python
Control flow: for a = ['cat', 'window', 'defenestrate'] for x in a: print x, len(x) no arithmetic progression, but range(10) # à [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(2,10,2) # à [2, 4, 6, 8] for i in range(len(a)): print i, a[i] break and continue like C and Java
User-defined functions def fib(n): """Print a Fibonacci series up to n.""" a b while b < n: print b a b b a+b fib(30)
File Manipulation
List Comprehension Construct lists in an alternative way
Classes class Person: def init (self, first, last): self.firstname = first self.lastname = last def get_fullname(self): return self.firstname + + self.lastname class Employee(Person): instances = 0 Class / static variables def init (self, first, last, afm): Person. init (self, first, last) self.afm = afm Employee.instances += 1 def get_employee(self): return self.get_fullname() + + self.afm employee1 = Employee( themis, beris, 123 ) Creates an instance of Employee employee2 = Employee( nikos, karalis, 456 ) Creates another instance of Employee print employee1.get_employee() print employee2.instances print employee1.instances == employee2.instances It will always be True