SlideShare a Scribd company logo
1 of 38
Python course 2012
      Karin Lagesen

 karin.lagesen@bio.uio.no
Format of course
3 hours session
  1 part of homework review
  1 part lecture
  1 part assisted programming
Book: Python for Bioinformatics,
       Sebastian Bassi
Note: no Python3 here.
What is programming?
Programming: ordered set of instructions
Programming can be compared to a:
  Cooking recipe
  Ikea furniture instructions
  Lab protocol
Language: instruction set
Programming: combining instructions to
 solve problem
How to make a program
Need a programming language
Programming language is the set of
 available instructions
Several types of languages – several types
 of instruction sets
Two main types:
  Interpreted languages
  Compiled languages
Interpreted languages
No compilation needed
Program interpreted “on-the-fly”
Programs often called scripts
Example of interpreted languages:
  General purpose: perl, python
  Special purpose: R
Possible disadvantage: can be slower than
 compiled programs.
Interactive – batch mode
Python can be used in the shell,
 interactively
Useful for testing etc
Exit from python: Ctrl-D
Most common: save code in text file, run in
 shell
Called batch mode
Python data types
Numbers: integers and floats
Strings
Lists
Tuples


Dictionaries
Sets
Data type features
Sequence datatypes:
  Sequential order
  Strings, lists and tuples


Immutable datatypes:
  Cannot be changed
  Numbers, strings, tuples
Python operators
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
   >>>
Exercise in class

Log in to freebee.titan.uio.no
Go to
  /projects/temporary/cees-python-course/
Create a directory under your name
Do module load python
Type in python, then press enter
You are now in the python interactive shell
Repeat what was done on the last slide
Strings
Use ', “ or ''' to delineate
Remember: 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: n
Tab: t
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
Variables

A variable is something with a value that may
 change
Naming variables:
  Letters, numbers and _
  CasE sEnsitive
  Numbers may not be first
  Some words are reserved
  Convention: small letters, underscore to separate
   words
Reserved words
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
 itself
Can do the same thing to another string
Dynamic, strong typing
No need to specify type
Type 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
   >>>
Printing variables
Interactive mode,
  type name of variable, press enter
  print variable_name
Batch mode:
  Only print variable_name
Lists

Ordered collection of elements
list1 = [elem, elem, elem]
Can hold elements of any type, including
 another list
Can 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']
 >>>
Adding to list

Create empty list:
   list1 = []
Add to list:
   list1.append(elem)
   Adds element to the end
Add at position:
   list1.insert(position, elem)
   Adds element at position
Extend list:
   list1.extend(elem)
   Extends list with elements
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]]
   >>>
List removal
list1.remove(elem) – remove specified
   element
list1.pop(index) – return elem in index,
   default is last
del list1[index] – not recommended
Tuple
Basically an immutable list
Cannot add or remove to tuple
List: order can be changed, tuple: locked
Initiation: (elem, elem)
One element: (elem,) #note comma
Can contain all data types
Sequence methods

Indexing
  Index starts at zero
  Negative indices go from right edge
Slicing
  Can access portions of sequence using indices
In operator – test for membership
Concatenation – add two together with +
Len, min, max
Create list from sequence using list()
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]
in operator

Test if element is in sequence
Works 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
                              >>>
Concatenation
Concatenation: + sign
Can 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
  >>>
Len, min, max
Len: length of sequence object
Min: minimum
Max: maximum
  >>>   txt1 = "ABCDEF"
  >>>   len(txt1)
  6
  >>>   max(txt1)
  'F'
  >>>   min(txt1)
  'A'
  >>>
Exercise

Create 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
Exercise
Create 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 test
Use the same numbers to create a tuple,
 and repeat the above operations
Batch mode program
Write program
  Open text file
  Write the following:
  print “Hello world”
  Save file as Hello_world.py
Run program
  % module load python
  % python Hello_world.py
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
Module load python

Several versions of python available
Without:
[karinlag@freebee]~% which python
  /usr/bin/python

With:
[karinlag@freebee]~% which python
  /site/VERSIONS/python-2.6.2/bin/python

Biopython compatible with 2.6
Exercise
Gather what you have done earlier into a
 text file
Remember print!
Name the file datatypes.py
Run python datatypes.py


Congratulations: your first script!
Getting help
In python:
  help(what you want to know more about)
  Example: help(list)
wiki.python.org/moin/BeginnersGuide/NonPr
 ogrammers
Look at the book!
Send me an email
Homework
ORF.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)
Homework

GCcontent.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
Homework results
Will be examined by your fellow student
Bring
  Paper copy of code
  Printout of results of running code

More Related Content

What's hot

Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Pythonprimeteacher32
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational BiologyAtreyiB
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
4 b file-io-if-then-else
4 b file-io-if-then-else4 b file-io-if-then-else
4 b file-io-if-then-elseMalik Alig
 

What's hot (20)

Functions in python
Functions in pythonFunctions in python
Functions in python
 
python codes
python codespython codes
python codes
 
Python
PythonPython
Python
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Python programming
Python  programmingPython  programming
Python programming
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Biopython
BiopythonBiopython
Biopython
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
 
Python ppt
Python pptPython ppt
Python ppt
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
 
Python basic
Python basicPython basic
Python basic
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python basics
Python basicsPython basics
Python basics
 
Python programing
Python programingPython programing
Python programing
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Python language data types
Python language data typesPython language data types
Python language data types
 
4 b file-io-if-then-else
4 b file-io-if-then-else4 b file-io-if-then-else
4 b file-io-if-then-else
 

Similar to Python course Day 1

python-cheatsheets.pdf
python-cheatsheets.pdfpython-cheatsheets.pdf
python-cheatsheets.pdfKalyan969491
 
python-cheatsheets that will be for coders
python-cheatsheets that will be for coderspython-cheatsheets that will be for coders
python-cheatsheets that will be for coderssarafbisesh
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentationNimrita Koul
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1Giovanni Della Lunga
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...Yashpatel821746
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 

Similar to Python course Day 1 (20)

python-cheatsheets.pdf
python-cheatsheets.pdfpython-cheatsheets.pdf
python-cheatsheets.pdf
 
python-cheatsheets that will be for coders
python-cheatsheets that will be for coderspython-cheatsheets that will be for coders
python-cheatsheets that will be for coders
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
PYTHON
PYTHONPYTHON
PYTHON
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
 
Five
FiveFive
Five
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 

Recently uploaded

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Python course Day 1

  • 1. Python course 2012 Karin Lagesen karin.lagesen@bio.uio.no
  • 2. Format of course 3 hours session 1 part of homework review 1 part lecture 1 part assisted programming Book: Python for Bioinformatics, Sebastian Bassi Note: no Python3 here.
  • 3. What is programming? Programming: ordered set of instructions Programming can be compared to a: Cooking recipe Ikea furniture instructions Lab protocol Language: instruction set Programming: combining instructions to solve problem
  • 4. How to make a program Need a programming language Programming language is the set of available instructions Several types of languages – several types of instruction sets Two main types: Interpreted languages Compiled languages
  • 5. Interpreted languages No compilation needed Program interpreted “on-the-fly” Programs often called scripts Example of interpreted languages: General purpose: perl, python Special purpose: R Possible disadvantage: can be slower than compiled programs.
  • 6. Interactive – batch mode Python can be used in the shell, interactively Useful for testing etc Exit from python: Ctrl-D Most common: save code in text file, run in shell Called batch mode
  • 7. Python data types Numbers: integers and floats Strings Lists Tuples Dictionaries Sets
  • 8. Data type features Sequence datatypes: Sequential order Strings, lists and tuples Immutable datatypes: Cannot be changed Numbers, strings, tuples
  • 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. Exercise in class Log in to freebee.titan.uio.no Go to /projects/temporary/cees-python-course/ Create a directory under your name Do module load python Type in python, then press enter You are now in the python interactive shell Repeat what was done on the last slide
  • 12. Strings Use ', “ or ''' to delineate Remember: 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: n Tab: t
  • 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. Variables A variable is something with a value that may change Naming variables: Letters, numbers and _ CasE sEnsitive Numbers may not be first Some words are reserved Convention: small letters, underscore to separate words
  • 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 itself Can do the same thing to another string
  • 17. Dynamic, strong typing No need to specify type Type 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. Printing variables Interactive mode, type name of variable, press enter print variable_name Batch mode: Only print variable_name
  • 19. Lists Ordered collection of elements list1 = [elem, elem, elem] Can hold elements of any type, including another list Can 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. Adding to list Create empty list: list1 = [] Add to list: list1.append(elem) Adds element to the end Add at position: list1.insert(position, elem) Adds element at position Extend list: list1.extend(elem) Extends list with elements
  • 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. List removal list1.remove(elem) – remove specified element list1.pop(index) – return elem in index, default is last del list1[index] – not recommended
  • 23. Tuple Basically an immutable list Cannot add or remove to tuple List: order can be changed, tuple: locked Initiation: (elem, elem) One element: (elem,) #note comma Can contain all data types
  • 24. Sequence methods Indexing Index starts at zero Negative indices go from right edge Slicing Can access portions of sequence using indices In operator – test for membership Concatenation – add two together with + Len, min, max Create list from sequence using list()
  • 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. in operator Test if element is in sequence Works 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. Concatenation Concatenation: + sign Can 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. Len, min, max Len: length of sequence object Min: minimum Max: maximum >>> txt1 = "ABCDEF" >>> len(txt1) 6 >>> max(txt1) 'F' >>> min(txt1) 'A' >>>
  • 29. Exercise Create 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. Exercise Create 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 test Use the same numbers to create a tuple, and repeat the above operations
  • 31. Batch mode program Write program Open text file Write the following: print “Hello world” Save file as Hello_world.py Run program % module load python % python Hello_world.py
  • 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. Module load python Several versions of python available Without: [karinlag@freebee]~% which python /usr/bin/python With: [karinlag@freebee]~% which python /site/VERSIONS/python-2.6.2/bin/python Biopython compatible with 2.6
  • 34. Exercise Gather what you have done earlier into a text file Remember print! Name the file datatypes.py Run python datatypes.py Congratulations: your first script!
  • 35. Getting help In python: help(what you want to know more about) Example: help(list) wiki.python.org/moin/BeginnersGuide/NonPr ogrammers Look at the book! Send me an email
  • 36. Homework ORF.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. Homework GCcontent.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. Homework results Will be examined by your fellow student Bring Paper copy of code Printout of results of running code