Python course 2012      Karin Lagesen karin.lagesen@bio.uio.no
Format of course3 hours session  1 part of homework review  1 part lecture  1 part assisted programmingBook: Python for Bi...
What is programming?Programming: ordered set of instructionsProgramming can be compared to a:  Cooking recipe  Ikea furnit...
How to make a programNeed a programming languageProgramming language is the set of available instructionsSeveral types of ...
Interpreted languagesNo compilation neededProgram interpreted “on-the-fly”Programs often called scriptsExample of interpre...
Interactive – batch modePython can be used in the shell, interactivelyUseful for testing etcExit from python: Ctrl-DMost c...
Python data typesNumbers: integers and floatsStringsListsTuplesDictionariesSets
Data type featuresSequence datatypes:  Sequential order  Strings, lists and tuplesImmutable datatypes:  Cannot be changed ...
Python operators
Python as a calculator[karinlag@freebee]/projects/temporary/cees-python-course/Karin% python   Python 2.6.2 (r262:71600, S...
Exercise in classLog in to freebee.titan.uio.noGo to  /projects/temporary/cees-python-course/Create a directory under your...
StringsUse , “ or  to delineateRemember: same type on each end can be used to create block text  >>> This is a piece     ....
String operations>>> "TTAAGAGGA".replace("T", "U")   UUAAGAGGA   >>> "TTAAGAGGA".count("G")   3   >>> "TTAAGAGGA".find("AG...
VariablesA variable is something with a value that may changeNaming variables:  Letters, numbers and _  CasE sEnsitive  Nu...
Reserved words
Using variables>>> t1 = "TTAAGAGGA"   >>> t2 = "GGGG"   >>> t1 + t2   TTAAGAGGAGGGG   >>> t1.replace("T", "U")   UUAAGAGGA...
Dynamic, strong typingNo need to specify typeType is interpreted as we go  along – python objects we do  something wrong>>...
Printing variablesInteractive mode,  type name of variable, press enter  print variable_nameBatch mode:  Only print variab...
ListsOrdered collection of elementslist1 = [elem, elem, elem]Can hold elements of any type, including another listCan be s...
Adding to listCreate empty list:   list1 = []Add to list:   list1.append(elem)   Adds element to the endAdd at position:  ...
List adding example>>> list1 = "A,B,C,D,E".split(",")   >>> list1   [A, B, C, D, E]   >>> list1.append(F)                 ...
List removallist1.remove(elem) – remove specified   elementlist1.pop(index) – return elem in index,   default is lastdel l...
TupleBasically an immutable listCannot add or remove to tupleList: order can be changed, tuple: lockedInitiation: (elem, e...
Sequence methodsIndexing  Index starts at zero  Negative indices go from right edgeSlicing  Can access portions of sequenc...
Indices>>> text = "ABCDEFG"   >>> text[2]   C   >>> text[-2]   F                             0   1   2   3   4   5   6   >...
in operatorTest if element is in sequenceWorks with lists, sequences, tuples>>> X = [1,4,8,2,9]           >>> X = "ABCDEF"...
ConcatenationConcatenation: + signCan only concatenate same types  >>> a = (1,2)  >>> b = (3,4)  >>> a+b  (1, 2, 3, 4)  >>...
Len, min, maxLen: length of sequence objectMin: minimumMax: maximum  >>>   txt1 = "ABCDEF"  >>>   len(txt1)  6  >>>   max(...
ExerciseCreate the string GATTAGAT  Find two ways to print the character in the    4th position  Count the number of Ts in...
ExerciseCreate list [1,4,8,2,10]  Find the maximum number  Use sort to find the two lowest numbers  Find out if the number...
Batch mode programWrite program  Open text file  Write the following:  print “Hello world”  Save file as Hello_world.pyRun...
Different ways of running% python filename.py  As you did on previous slide% filename.py  Make executable:  chmod gu+x fil...
Module load pythonSeveral versions of python availableWithout:[karinlag@freebee]~% which python  /usr/bin/pythonWith:[kari...
ExerciseGather what you have done earlier into a text fileRemember print!Name the file datatypes.pyRun python datatypes.py...
Getting helpIn python:  help(what you want to know more about)  Example: help(list)wiki.python.org/moin/BeginnersGuide/Non...
HomeworkORF.py Define string  ATTAATGAGATTACAGAGCTAAGAC Replace all Ts with Us Find position of start codon AUG Find posit...
HomeworkGCcontent.py  Define DNA string   AGCAGATCAGCGA  Calculate the frequency of Gs and Cs in the string  Calculate the...
Homework resultsWill be examined by your fellow studentBring  Paper copy of code  Printout of results of running code
Upcoming SlideShare
Loading in...5
×

Python course Day 1

1,145

Published on

These slides are for the first day of a python course. Note, some slides are specific for the computers that the course was run on.

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,145
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
37
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Python course Day 1

  1. 1. Python course 2012 Karin Lagesen karin.lagesen@bio.uio.no
  2. 2. Format of course3 hours session 1 part of homework review 1 part lecture 1 part assisted programmingBook: Python for Bioinformatics, Sebastian BassiNote: no Python3 here.
  3. 3. What is programming?Programming: ordered set of instructionsProgramming can be compared to a: Cooking recipe Ikea furniture instructions Lab protocolLanguage: instruction setProgramming: combining instructions to solve problem
  4. 4. How to make a programNeed a programming languageProgramming language is the set of available instructionsSeveral types of languages – several types of instruction setsTwo main types: Interpreted languages Compiled languages
  5. 5. Interpreted languagesNo compilation neededProgram interpreted “on-the-fly”Programs often called scriptsExample of interpreted languages: General purpose: perl, python Special purpose: RPossible disadvantage: can be slower than compiled programs.
  6. 6. Interactive – batch modePython can be used in the shell, interactivelyUseful for testing etcExit from python: Ctrl-DMost common: save code in text file, run in shellCalled batch mode
  7. 7. Python data typesNumbers: integers and floatsStringsListsTuplesDictionariesSets
  8. 8. Data type featuresSequence datatypes: Sequential order Strings, lists and tuplesImmutable datatypes: Cannot be changed Numbers, strings, tuples
  9. 9. Python operators
  10. 10. Python as a calculator[karinlag@freebee]/projects/temporary/cees-python-course/Karin% python Python 2.6.2 (r262:71600, Sep 1 2009, 10:39:29) [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2+2 4 >>> 4-2 2 >>> 5*23 115 >>> 12/6 2 >>> 11/6 1 >>> 11.0/6 1.8333333333333333 >>> 2**8 256 >>> 5%3 2 >>> 7%3 1 >>>
  11. 11. Exercise in classLog in to freebee.titan.uio.noGo to /projects/temporary/cees-python-course/Create a directory under your nameDo module load pythonType in python, then press enterYou are now in the python interactive shellRepeat what was done on the last slide
  12. 12. StringsUse , “ or to delineateRemember: same type on each end can be used to create block text >>> This is a piece ... of block text This is a piecenof block text >>>Newline: nTab: t
  13. 13. String operations>>> "TTAAGAGGA".replace("T", "U") UUAAGAGGA >>> "TTAAGAGGA".count("G") 3 >>> "TTAAGAGGA".find("AG") 3 >>> "TTAAGAGGA".find("AGX") -1 >>> "TTAAGAGGA".index("AG") 3 >>> "TTAAGAGGA".index("AGX") Traceback (most recent call last): File "<stdin>", line 1, in <module> Note the error message! ValueError: substring not found This is pythons way of telling >>> "TTAAGAGGA".split("A") [TT, , G, GG, ] you something went wrong. >>> "TTA,AGA,GGA".split(",") [TTA, AGA, GGA] >>> "TTA AGA GGA".split() [TTA, AGA, GGA] >>> Repeat on freebee
  14. 14. VariablesA variable is something with a value that may changeNaming variables: Letters, numbers and _ CasE sEnsitive Numbers may not be first Some words are reserved Convention: small letters, underscore to separate words
  15. 15. Reserved words
  16. 16. Using variables>>> t1 = "TTAAGAGGA" >>> t2 = "GGGG" >>> t1 + t2 TTAAGAGGAGGGG >>> t1.replace("T", "U") UUAAGAGGA >>> t1 TTAAGAGGA >>> t3 = t1.replace("T", "U") >>> t3 UUAAGAGGA >>>We are using the variable instead of the string itselfCan do the same thing to another string
  17. 17. Dynamic, strong typingNo need to specify typeType is interpreted as we go  along – python objects we do  something wrong>>> t4 = 123 >>> t1 + t4 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate str and int objects >>>
  18. 18. Printing variablesInteractive mode, type name of variable, press enter print variable_nameBatch mode: Only print variable_name
  19. 19. ListsOrdered collection of elementslist1 = [elem, elem, elem]Can hold elements of any type, including another listCan be sorted (in place) using .sort() >>> list1 = ["a", "c", “b”] >>> list2 = ["X", "Y", list1] >>> list2 [X, Y, [a, c, b]] >>> list1.sort() >>> list1 [a, b, c] >>>
  20. 20. Adding to listCreate empty list: list1 = []Add to list: list1.append(elem) Adds element to the endAdd at position: list1.insert(position, elem) Adds element at positionExtend list: list1.extend(elem) Extends list with elements
  21. 21. List adding example>>> list1 = "A,B,C,D,E".split(",") >>> list1 [A, B, C, D, E] >>> list1.append(F) Basic adding to list >>> list1 [A, B, C, D, E, F] >>> list1.extend(G) >>> list1 [A, B, C, D, E, F, G] >>> list1.insert(3,G) >>> list1 [A, B, C, G, D, E, F, G] >>> list1.extend([1,2]) Note difference between >>> list1 append and extend! [A, B, C, G, D, E, F, G, 1, 2] >>> list1.append([1,2]) >>> list1 [A, B, C, G, D, E, F, G, 1, 2, [1, 2]] >>>
  22. 22. List removallist1.remove(elem) – remove specified elementlist1.pop(index) – return elem in index, default is lastdel list1[index] – not recommended
  23. 23. TupleBasically an immutable listCannot add or remove to tupleList: order can be changed, tuple: lockedInitiation: (elem, elem)One element: (elem,) #note commaCan contain all data types
  24. 24. Sequence methodsIndexing Index starts at zero Negative indices go from right edgeSlicing Can access portions of sequence using indicesIn operator – test for membershipConcatenation – add two together with +Len, min, maxCreate list from sequence using list()
  25. 25. Indices>>> text = "ABCDEFG" >>> text[2] C >>> text[-2] F 0 1 2 3 4 5 6 >>> text[2:4] A B C D E F G CD >>> text[2:-2] -7 -6 -5 -4 -3 -2 -1 CDE >>> text[:4] ABCD >>> text[4:] EFG >>> Note: for slicing, it is  [from and including : to but  excluding]
  26. 26. in operatorTest if element is in sequenceWorks with lists, sequences, tuples>>> X = [1,4,8,2,9] >>> X = "ABCDEF" >>> X >>> X [1, 4, 8, 2, 9] ABCDEF >>> 5 in X >>> "Y" in X False False >>> 8 in X >>> True >>> "BC" in X >>>  True >>>
  27. 27. ConcatenationConcatenation: + signCan only concatenate same types >>> a = (1,2) >>> b = (3,4) >>> a+b (1, 2, 3, 4) >>> c = [5,6] >>> a + c Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate tuple (not "list") to tuple >>>
  28. 28. Len, min, maxLen: length of sequence objectMin: minimumMax: maximum >>> txt1 = "ABCDEF" >>> len(txt1) 6 >>> max(txt1) F >>> min(txt1) A >>>
  29. 29. ExerciseCreate the string GATTAGAT Find two ways to print the character in the 4th position Count the number of Ts in it Find the indices needed to print AGA Add the sequence TTG to the string, count Ts Replace the Ts with Us
  30. 30. ExerciseCreate list [1,4,8,2,10] Find the maximum number Use sort to find the two lowest numbers Find out if the number 9 is in the list Add the number 9 to the list, repeat testUse the same numbers to create a tuple, and repeat the above operations
  31. 31. Batch mode programWrite program Open text file Write the following: print “Hello world” Save file as Hello_world.pyRun program % module load python % python Hello_world.py
  32. 32. Different ways of running% python filename.py As you did on previous slide% filename.py Make executable: chmod gu+x filename.py Add shebang to script #!/usr/bin/env python env: run with first python in your path
  33. 33. Module load pythonSeveral versions of python availableWithout:[karinlag@freebee]~% which python /usr/bin/pythonWith:[karinlag@freebee]~% which python /site/VERSIONS/python-2.6.2/bin/pythonBiopython compatible with 2.6
  34. 34. ExerciseGather what you have done earlier into a text fileRemember print!Name the file datatypes.pyRun python datatypes.pyCongratulations: your first script!
  35. 35. Getting helpIn python: help(what you want to know more about) Example: help(list)wiki.python.org/moin/BeginnersGuide/NonPr ogrammersLook at the book!Send me an email
  36. 36. HomeworkORF.py Define string ATTAATGAGATTACAGAGCTAAGAC Replace all Ts with Us Find position of start codon AUG Find position of stop codon UAA Print sequence from (including) start codon to stop codon (excluding)
  37. 37. HomeworkGCcontent.py Define DNA string AGCAGATCAGCGA Calculate the frequency of Gs and Cs in the string Calculate the frequency of the dinucleotide ´GC´in the input string Print the results to screen
  38. 38. Homework resultsWill be examined by your fellow studentBring Paper copy of code Printout of results of running code
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×