#!/usr/bin/env python # coding: utf-8 # Introduction to Python (2) # === # Sequence types # === # # Lists # --- # # Mutable sequences of values. # In[1]: l = [2, 5, 2, 3, 7] type(l) # Lists can be heterogeneous, but we typically don't use that. # In[2]: a = 'spezi' [3, 'abc', 1.3e20, [a, a, 2]] # Sequence types # === # # Tuples # --- # # Immutable sequences of values. # In[3]: t = 'white', 77, 1.5 type(t) # In[4]: color, width, scale = t width # Sequence types # === # # Strings (1/2) # --- # # Immutable sequences of characters. # In[5]: 'a string can be written in single quotes' # Strings can also be written with double quotes, or over multiple lines with triple-quotes. # In[6]: "this makes it easier to use the ' character" # In[7]: """This is a multiline string. You see? I continued after a blank line.""" # Sequence types # === # # Strings (2/2) # --- # # A common operation is formatting strings using argument substitutions. # In[8]: '{} times {} equals {:.2f}'.format('pi', 2, 6.283185307179586) # Accessing arguments by position or name is more readable. # In[9]: '{1} times {0} equals {2:.2f}'.format('pi', 2, 6.283185307179586) # In[10]: '{number} times {amount} equals {result:.2f}'.format(number='pi', amount=2, result=6.283185307179586) # Sequence types # === # # Common operations (1/2) # --- # # All sequence types support concatenation, membership/substring tests, indexing, and slicing. # In[11]: [1, 2, 3] + [4, 5, 6] # In[12]: 'bier' in 'we drinken bier vanaf half 5' # In[13]: 'abcdefghijkl'[5] # Sequence types # === # # Slicing # --- # # Slice `s` from `i` to `j` with `s[i:j]`. # In[14]: 'abcdefghijkl'[4:8] # In[15]: 'abcdefghijkl'[:3] # We can also define the step `k` with `s[i:j:k]`. # In[16]: 'abcdefghijkl'[7:3:-1] # Sequence types # === # # Common operations (2/2) # --- # # Contrary to strings and tuples, lists are mutable. We can also get their length, smallest/largest item, and number/position of certain items. # In[17]: len('attacgataggcatccgt') # In[18]: max([17, 86, 34, 51]) # In[19]: ('atg', 22, True, 'atg').count('atg') # Sequence types # === # # Additional operations with lists # --- # # We can replace, add, remove, reverse and sort items in-place. # In[20]: l = [1, 2, 3, 4] l[3] = 7 l.append(1) l[1:3] = [3, 2] l.sort() l.reverse() # In[21]: l # Dictionaries # === # # Dictionaries map *hashable* values to arbitrary objects # --- # # * All built-in immutable objects are hashable. # * No built-in mutable objects are hashable. # In[22]: d = {'a': 27, 'b': 18, 'c': 12} type(d) # In[23]: d['e'] = 17 'e' in d # In[24]: d.update({'a': 18, 'f': 2}) d # Dictionaries # === # # Accessing dictionary content # --- # In[25]: d['b'] # In[26]: d.keys() # In[27]: d.values() # In[28]: d.items() # Sets # === # # Mutable unordered collections of hashable values without duplication # --- # In[29]: x = {12, 28, 21, 17} type(x) # In[30]: x.add(12) x # In[31]: x.discard(21) x # Sets # === # # Operations with sets # --- # # We can test for membership and apply many common set operations such as union and intersect. # In[32]: 17 in {12, 28, 21, 17} # In[33]: {12, 28, 21, 17} | {12, 18, 11} # In[34]: {12, 28, 21, 17} & {12, 18, 11} # Booleans # === # # Boolean values and operations # --- # # The two boolean values are written `False` and `True`. # In[35]: True or False # In[36]: True and False # In[37]: not False # Booleans # === # # Comparisons # --- # # Comparisons can be done on all objects and return a boolean value. # In[38]: 22 * 3 > 66 # We have two equivalence relations: value equality (`==`) and object identity (`is`). # In[39]: a, b = [1, 2, 3], [1, 2, 3] a == b # In[40]: a is b # Booleans # === # # `if` statements # --- # # (The `print` statement writes a string representation of the given value.) # In[41]: if 26 <= 17: print 'Fact: 26 is less than or equal to 17' elif (26 + 8 > 14) == True: print 'Did we need the ` == True` part here?' else: print 'Nothing seems true' # Booleans # === # # `while` statements # --- # # Our first looping control structure just repeats until the given expression evaluates to `False`. # In[42]: i = 0 while i < 5: print i i += 1 # Hands on! # === # # Try to guess the outcome of the following statements: # # 2 * 3 > 4 # 2 * (3 > 4) # 2 * (4 > 3) # Notes about syntax # === # # Indentation # --- # # Python uses indentation to delimit blocks # # * Instead of `begin ... end` or `{ ... }` in other languages. # * Always increase indentation by *4 spaces*, never use tabs. # * In any case, be consistent. # In[43]: if False: if False: print 'Why am I here?' else: while True: print 'When will it stop?' print "And we're back to the first indentation level" # Some editors can be configured to behave just like that. # Notes about syntax # === # # Comments # --- # # Comments are prepended by `#` and completely ignored. # In[44]: # Add 42 to this list. l.append(42) # `pass` statements # --- # # If you ever need a statement syntactically but don't want to do anything, use `pass`. # In[45]: while False: # This is never executed anyway. pass # Useful built-ins # === # # Getting help # --- # # You can get help on almost any object with `help`. # In[46]: help(range) # In IPython you can do it faster by typing: # In[47]: get_ipython().run_line_magic('pinfo', 'range') # Useful built-ins # === # # We'll shortly use the following built-in functions. # In[48]: range(5, 16) # In[49]: zip(['red', 'white', 'blue'], range(3)) # In[50]: list('abcdefghijk') # Iteration # === # # Iterating over a sequence # --- # In[51]: colors = ['red', 'white', 'blue', 'orange'] cities = ['leiden', 'utrecht', 'warmond', 'san francisco'] # The `for` statement can iterate over sequence items. # In[52]: for color in colors: print color # In[53]: for character in 'blue': print character # Iteration # === # # Python anti-patterns # --- # # These are common for programmers coming from other languages. # In[54]: i = 0 while i < len(colors): print colors[i] i += 1 # In[55]: for i in range(len(colors)): print colors[i] # We call them *unpythonic*. # Iteration # === # # Using values *and* indices # --- # In[56]: for i, color in enumerate(colors): print i, '->', color # Taking two sequences together # --- # In[57]: for city, color in zip(cities, colors): print city, '->', color # Iteration # === # # Other iterables # --- # # Iterating over a dictionary yields keys. # In[58]: for key in {'a': 33, 'b': 17, 'c': 18}: print key # Iterating over a file yields lines. # In[59]: for line in open('data/short_file.txt'): print line # There are many more useful iterables in Python. #
#

Hands on!

# #
    #
  1. Make a list with 10 integer elements. Sum all the items in the list.
  2. #
  3. Make a new list from the above one that does not include the 0th, 4th and 5th elements. #
  4. Sum only the elements from the first list which are between the 2nd and 6th elements. #
  5. Make a new list that includes only the elements that are greater than 10 from the first list. #
  6. Food. #
      #
    • Create a dictionary for food products called "prices" and put some values in it, e.g., "apples": 2, "oranges": 1.5, "pears": 3, ...
    • #
    • Create a corresponding dictionary called "stocks" and put the stock values in it, e.g., "apples": 0, "oranges": 1, "pears": 10, ...
    • #
    • Print stock and price information for each food item.
    • #
    • Determine and print how much money you would make if you sold all of your food products. #
    #
  7. #
# #
# Homework assignment # === # # https://classroom.github.com/a/QU2iPYKn # $\S$ Exercise: Iterate over a list # === # # First we are going to make a list and fill it with a simple sequence. Then we are going to use this list to print something. # # * Make a list containing the numbers 0, 1, ... 9. # * Print the last 10 lines of the song ''99 bottles of beer'' using this list. # $\S$ Exercise: Analyse a repeat structure # === # # We are going to make a repeating DNA sequence and extract some subsequences from it. # # * Make a short tandem repeat that consists of three "ACGT" units and five "TTATT" units. # * Print all suffixes of the repeat structure. # # **Note:** A suffix is an ending. For example, the word "spam" has five suffixes: "spam", "pam", "am", "m" and "". # # * Print all substrings of length 3. # * Print all unique substrings of length 3. # # **Hint:** All elements in a set are unique. # $\S$ Exercise: Combining lists # === # # Calculate all coordinates of the line x=y with x < 100. # # **Note:** This is the sequence (0, 0), (1, 1), ... (99, 99) # $\S$ Exercise: Dictionaries # === # We are going to store the output of a function ($f(x) = x^2$) together with its input in a dictionary. # # * Make a dictionary containing all squares smaller than 100. # * Print the content of this dictionary in english, e.g., "4 is the square of 2". # In[1]: from IPython.display import HTML def css_styling(): styles = open('styles/custom.css', 'r').read() return HTML('') css_styling() # Acknowledgements # ======== # # Martijn Vermaat # # [Jeroen Laros](mailto:j.f.j.laros@lumc.nl) # # Based on # --------- # [Python Scientific Lecture Notes](http://scipy-lectures.github.io/) # # License # -------- # [Creative Commons Attribution 3.0 License (CC-by)](http://creativecommons.org/licenses/by/3.0)