SlideShare a Scribd company logo
Dictionaries, sets and
      flow control
       Karin Lagesen

  karin.lagesen@bio.uio.no
Dictionaries
Stores unordered, arbitrarily indexed data
Consists of key-value pairs
Dict = {key:value, key:value, key:value...}
Note: keys must be immutable!
  ergo: numbers, tuples or strings
Values may be anything, incl. another
 dictionary
Mainly used for storing associations or
 mappings
Create, add, lookup, remove
Creation:
  mydict = {} (empty), or
  mydict = { mykey:myval, mykey2:myval2 }
Adding:
  mydict[key] = value
Lookup:
  mydict[key]
Remove:
  del mydict[key]
Dictionary methods
All keys:
   mylist.keys() - returns list of keys
All values:
   mydict.values() - returns list of values
All key-value pairs as list of tuples:
   mydict.items()
Get one specific value:
   mydict.get(key [, default])
   if default is given, that is returned if key is not present in the
       dictionary, else None is returned
Test for presence of key:
   key in mydict – returns True or False
Dictionary exercise
Log in to freebee as before
Do module load python, then start python
Create this dictionary:
  {“A”: 1, 1:”A”, “B”:[1,2,3]}
Find out the following:
   how many keys are there?
   add “str”: {1:”X”} to the dictionary
   is there something stored with key “strx?”
   what about the key “str”?
   remove the number 3 from the list stored under “B” -
     print the results
Sets
Similar to lists but:
  no order
  every element is unique
Can create set from list (duplicates are then
 removed)
Add elements with
  myset = set()
  myset.add(elem)
Neat trick - how to create unique list:
  newlist = list(set(oldlist))
Set operations
Intersection – found in both sets
  set1.intersection(set2)
Union – all elements from both sets
  set1.union(set2)
Difference
  set1 – set2
Symmetrical difference
  set1.symmetric_difference(set2)
Set exercise
Create these lists:
 [“a”, “B”, 1, “a”, 4], [“c”, 1, 2, “A”, “c”, “a”]
make sets from these two lists
Figure out:
  the number of unique elements in each list
  the elements present in both
  the elements that are not shared
  the number of unique elements altogether
  the elements that are present in the second set,
    but not in the first
Input from terminal
Can get input from terminal (user)
Code:
  variable = raw_input(“Promt text”)
Prompt text will be printed to screen and the
 text the user types in will be stored in
 variable
Indentation and scope
Python does not use brackets or other
 symbols to delineate a block of code
Python uses indentation – either tab or
 space
Note: variables can only be seen and used
 within the block of code it is in – this is
 called scope
Flow control
Flow control determines which blocks of
  code that will to be executed
One conditional statement
  If – else
Two iteration statements
  For: iterate over group of elements
  While: do until something is true
If
Structure:
  if <boolean expression>:
     code block 1
  elif <boolean expression>:
     code block 2
  else:
     code block 3
Only one of these code blocks are executed
Executed block: the one whose expression
 first evaluates to True
Boolean expressions
Comparisons
    A> B                 A greater than B
    A< B                 A smaller than B
    A >= B               A greater than or equal to B
    A <=B                A smaller than or equal to B
    A == B               A equal to B
    A != B               A not equal to B

Comparisons can be combined:
   and, or, and not
   B != C and B > A - results evaluated left-right
Other values
   True: non-empty lists, sets, tuples etc
   False: 0 and None
If exercise
Use the interactive python shell
Create the following:
  Empty list
  List with elements
  A variable with value 0
  A variable with value -1
  A variable with value None
Use these in an if structure to see which
 ones that evaluate to True
If script
Create variable that takes input from user
Test to see if:
  The sequence contains anything else than
    ATGC
  The sequence is at least 10 nucleotides long
Report results to user
If script
inputstring = raw_input("Input your DNA string: ")
mystring = inputstring.upper()
mylength = len(mystring)
myAs = mystring.count("A")
myCs = mystring.count("C")
myTs = mystring.count("T")
myGs = mystring.count("G")

nucleotidesum = myAs + myCs + myTs + myGs

if nucleotidesum < mylength:
    print "String contains something else than DNA"
elif mylength < 10:
    print "Length is below 10"
else:
    print "Sequence is ok"
For
Structure:
  For VAR in ITERABLE:
     code block
Code block executed for each element in
 ITERABLE
VAR takes on value of current element
Iterables are:
  Strings, lists, tuples, xrange, byte arrays,
    buffers
For example
Use the python interactive shell
Create string “ATGGCGGA”
Print out each letter in this string
  >>> a = "ATGGCGGA"
  >>> for var in a:
  ...     print var
  ...
  A
  T
  G
  G
  C
  G
  G
  A
  >>>
For exercise
Define list of numbers 1-9
Show each number multiplied with itself
  >>> a = [1,2,3,4,5,6,7,8,9]
  >>> for var in a:
  ...     print var*var
  ...
  1
  4
  9
  16
  25
  36
  49
  64
  81
  >>>
xrange
Iterate over a range of numbers
xrange(int): numbers from 0 to int
xrange(start, stop, step):
  Start at start, stop at stop, skip step
    between each
  >>> for i in xrange(0,10,2):
  ...     print i
  ...
  0
  2
  4
  6
  8
  >>>
For exercise
Create dictionary where:
  Keys are all combinations of A, B, C
  Values are increasing from 1 and up
Hints
  Can use two for loops
  Adding to an integer variable:
     i += 1
For exercise

letters = "ABC"
valuedict = {}
i = 1
for letter1 in letters:
    for letter2 in letters:
        k = letter1 + letter2
        i += 1
        valuedict[k] = i
print valuedict


[karinlag@freebee]~/tmp/course% python forloopdict.py
{'AA': 2, 'AC': 4, 'AB': 3, 'BA': 5, 'BB': 6, 'BC': 7,
'CC': 10, 'CB': 9, 'CA': 8}
[karinlag@freebee]~/tmp/course%
While
Structure
  while EXPRESSION:
     code block
Important: code block MUST change truth
  value of expression, otherwise infinite loop
While example
>>>   a=10
>>>   while True:
...   if a<40:
...   print a
...   else:
...   break
...   a += 10
...
10
20
30
Break
Can be used to break out of a loop
Can greatly improve legibility and efficiency
What happens when next tuple is iterated
 over, after 'blue' is found?
Homework
ATCurve.py
  take an input string from the user
  check if the sequence only contains DNA – if
    not, promt for new sequence.
  calculate a running average of AT content along
    the sequence. Window size should be 3, and
    the step size should be 1. Print one value per
    line.
Note: you need to include several runtime
 examples to show that all parts of the code
 works.
Homework
CodonFrequency.py
 take an input string from the user
 check if the sequence only contains DNA
   – if not, promt for new sequence
 find an open reading frame in the string (note,
    must be multiple of three)
    – if not, prompt for new sequence
 calculate the frequency of each codon in the
   ORF

More Related Content

What's hot

Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
python codes
python codespython codes
python codes
tusharpanda88
 
Python
PythonPython
Python
대갑 김
 
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 Programming
Muthu Vinayagam
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
primeteacher32
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Biopython
BiopythonBiopython
Biopython
Karin Lagesen
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
SHAMJITH KM
 
Python Basics
Python BasicsPython Basics
Python Basics
tusharpanda88
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
Panimalar Engineering College
 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
 
Python programing
Python programingPython programing
Python programing
hamzagame
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang 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
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
amiable_indian
 

What's hot (20)

Python programming
Python  programmingPython  programming
Python programming
 
python codes
python codespython codes
python codes
 
Python
PythonPython
Python
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Python ppt
Python pptPython ppt
Python ppt
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
 
Python basic
Python basicPython basic
Python basic
 
Biopython
BiopythonBiopython
Biopython
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
Python basics
Python basicsPython basics
Python basics
 
Python programing
Python programingPython programing
Python programing
 
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
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 

Viewers also liked

Functions
FunctionsFunctions
python Function
python Function python Function
python Function
Ronak Rathi
 
Input and Output
Input and OutputInput and Output
Input and Output
Marieswaran Ramasamy
 
Python datatype
Python datatypePython datatype
Python datatype
건희 김
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
Amit Upadhyay
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
Martin McBride
 

Viewers also liked (10)

Functions
FunctionsFunctions
Functions
 
Functions in python
Functions in python Functions in python
Functions in python
 
python Function
python Function python Function
python Function
 
Input and Output
Input and OutputInput and Output
Input and Output
 
Python datatype
Python datatypePython datatype
Python datatype
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 

Similar to Day2

Python introduction
Python introductionPython introduction
Python introduction
leela rani
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
easyPy-Basic.pdf
easyPy-Basic.pdfeasyPy-Basic.pdf
easyPy-Basic.pdf
Mina Firoozgohar
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
Mohammed Khan
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
Ayush Mishra
 
Python review2
Python review2Python review2
Python review2
vibrantuser
 
Python review2
Python review2Python review2
Python review2
vibrantuser
 
Array
ArrayArray
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 

Similar to Day2 (20)

Python introduction
Python introductionPython introduction
Python introduction
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
easyPy-Basic.pdf
easyPy-Basic.pdfeasyPy-Basic.pdf
easyPy-Basic.pdf
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Python review2
Python review2Python review2
Python review2
 
Python review2
Python review2Python review2
Python review2
 
Array
ArrayArray
Array
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 

Recently uploaded

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 

Recently uploaded (20)

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 

Day2

  • 1. Dictionaries, sets and flow control Karin Lagesen karin.lagesen@bio.uio.no
  • 2. Dictionaries Stores unordered, arbitrarily indexed data Consists of key-value pairs Dict = {key:value, key:value, key:value...} Note: keys must be immutable! ergo: numbers, tuples or strings Values may be anything, incl. another dictionary Mainly used for storing associations or mappings
  • 3. Create, add, lookup, remove Creation: mydict = {} (empty), or mydict = { mykey:myval, mykey2:myval2 } Adding: mydict[key] = value Lookup: mydict[key] Remove: del mydict[key]
  • 4. Dictionary methods All keys: mylist.keys() - returns list of keys All values: mydict.values() - returns list of values All key-value pairs as list of tuples: mydict.items() Get one specific value: mydict.get(key [, default]) if default is given, that is returned if key is not present in the dictionary, else None is returned Test for presence of key: key in mydict – returns True or False
  • 5. Dictionary exercise Log in to freebee as before Do module load python, then start python Create this dictionary: {“A”: 1, 1:”A”, “B”:[1,2,3]} Find out the following: how many keys are there? add “str”: {1:”X”} to the dictionary is there something stored with key “strx?” what about the key “str”? remove the number 3 from the list stored under “B” - print the results
  • 6. Sets Similar to lists but: no order every element is unique Can create set from list (duplicates are then removed) Add elements with myset = set() myset.add(elem) Neat trick - how to create unique list: newlist = list(set(oldlist))
  • 7. Set operations Intersection – found in both sets set1.intersection(set2) Union – all elements from both sets set1.union(set2) Difference set1 – set2 Symmetrical difference set1.symmetric_difference(set2)
  • 8. Set exercise Create these lists: [“a”, “B”, 1, “a”, 4], [“c”, 1, 2, “A”, “c”, “a”] make sets from these two lists Figure out: the number of unique elements in each list the elements present in both the elements that are not shared the number of unique elements altogether the elements that are present in the second set, but not in the first
  • 9. Input from terminal Can get input from terminal (user) Code: variable = raw_input(“Promt text”) Prompt text will be printed to screen and the text the user types in will be stored in variable
  • 10. Indentation and scope Python does not use brackets or other symbols to delineate a block of code Python uses indentation – either tab or space Note: variables can only be seen and used within the block of code it is in – this is called scope
  • 11. Flow control Flow control determines which blocks of code that will to be executed One conditional statement If – else Two iteration statements For: iterate over group of elements While: do until something is true
  • 12. If Structure: if <boolean expression>: code block 1 elif <boolean expression>: code block 2 else: code block 3 Only one of these code blocks are executed Executed block: the one whose expression first evaluates to True
  • 13. Boolean expressions Comparisons A> B A greater than B A< B A smaller than B A >= B A greater than or equal to B A <=B A smaller than or equal to B A == B A equal to B A != B A not equal to B Comparisons can be combined: and, or, and not B != C and B > A - results evaluated left-right Other values True: non-empty lists, sets, tuples etc False: 0 and None
  • 14. If exercise Use the interactive python shell Create the following: Empty list List with elements A variable with value 0 A variable with value -1 A variable with value None Use these in an if structure to see which ones that evaluate to True
  • 15. If script Create variable that takes input from user Test to see if: The sequence contains anything else than ATGC The sequence is at least 10 nucleotides long Report results to user
  • 16. If script inputstring = raw_input("Input your DNA string: ") mystring = inputstring.upper() mylength = len(mystring) myAs = mystring.count("A") myCs = mystring.count("C") myTs = mystring.count("T") myGs = mystring.count("G") nucleotidesum = myAs + myCs + myTs + myGs if nucleotidesum < mylength: print "String contains something else than DNA" elif mylength < 10: print "Length is below 10" else: print "Sequence is ok"
  • 17. For Structure: For VAR in ITERABLE: code block Code block executed for each element in ITERABLE VAR takes on value of current element Iterables are: Strings, lists, tuples, xrange, byte arrays, buffers
  • 18. For example Use the python interactive shell Create string “ATGGCGGA” Print out each letter in this string >>> a = "ATGGCGGA" >>> for var in a: ... print var ... A T G G C G G A >>>
  • 19. For exercise Define list of numbers 1-9 Show each number multiplied with itself >>> a = [1,2,3,4,5,6,7,8,9] >>> for var in a: ... print var*var ... 1 4 9 16 25 36 49 64 81 >>>
  • 20. xrange Iterate over a range of numbers xrange(int): numbers from 0 to int xrange(start, stop, step): Start at start, stop at stop, skip step between each >>> for i in xrange(0,10,2): ... print i ... 0 2 4 6 8 >>>
  • 21. For exercise Create dictionary where: Keys are all combinations of A, B, C Values are increasing from 1 and up Hints Can use two for loops Adding to an integer variable: i += 1
  • 22. For exercise letters = "ABC" valuedict = {} i = 1 for letter1 in letters: for letter2 in letters: k = letter1 + letter2 i += 1 valuedict[k] = i print valuedict [karinlag@freebee]~/tmp/course% python forloopdict.py {'AA': 2, 'AC': 4, 'AB': 3, 'BA': 5, 'BB': 6, 'BC': 7, 'CC': 10, 'CB': 9, 'CA': 8} [karinlag@freebee]~/tmp/course%
  • 23. While Structure while EXPRESSION: code block Important: code block MUST change truth value of expression, otherwise infinite loop
  • 24. While example >>> a=10 >>> while True: ... if a<40: ... print a ... else: ... break ... a += 10 ... 10 20 30
  • 25. Break Can be used to break out of a loop Can greatly improve legibility and efficiency What happens when next tuple is iterated over, after 'blue' is found?
  • 26. Homework ATCurve.py take an input string from the user check if the sequence only contains DNA – if not, promt for new sequence. calculate a running average of AT content along the sequence. Window size should be 3, and the step size should be 1. Print one value per line. Note: you need to include several runtime examples to show that all parts of the code works.
  • 27. Homework CodonFrequency.py take an input string from the user check if the sequence only contains DNA – if not, promt for new sequence find an open reading frame in the string (note, must be multiple of three) – if not, prompt for new sequence calculate the frequency of each codon in the ORF