SlideShare ist ein Scribd-Unternehmen logo
1 von 27
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Pythonprimeteacher32
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 
Python programing
Python programingPython programing
Python programinghamzagame
 
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
 
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 minutesSumit 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 Twoamiable_indian
 

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie Day2

Python introduction
Python introductionPython introduction
Python introductionleela rani
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to ArraysTareq Hasan
 
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 ArraysMaulen Bale
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Array assignment
Array assignmentArray assignment
Array assignmentAhmad Kamal
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
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 pythonRaginiJain21
 
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 WayUtkarsh Sengar
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Kürzlich hochgeladen (20)

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

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