#!/usr/bin/env python # coding: utf-8 # Introduction to Python (3) # === # Functions # === # # A _function_ is a named sequence of statements that performs some piece of work. # Later on that function can be called by using its name. # # Defining a function # --- # # A function definition includes its _name_, _arguments_ and _body_. # In[1]: def add_two(number): return number + 2 # In[2]: for i in range(5): print add_two(i) # Functions # === # # Keyword arguments # --- # # Besides regular arguments, functions can have keyword arguments. # In[3]: def add_some_other_number(number, other_number=12): return number + other_number # In[4]: add_some_other_number(2, 6) # In[5]: add_some_other_number(3, other_number=4) # In[6]: add_some_other_number(5) # Functions # === # # Docstrings # --- # # Like many other definitions, functions can have docstrings. # # * Docstrings are regular string values which you start the definition body with. # * You can access an object's docstring using `help`. # In[7]: def factorial(n): """Compute factorial of n in the obious way.""" if n == 0: return 1 else: return factorial(n - 1) * n # In[8]: help(factorial) # Functions # === # # Functions are values # --- # # We can pass functions around just like other values, and call them. # In[9]: functions = [add_two, add_some_other_number] for function in functions: print function(7) # Simple anonymous functions can be created with `lambda`. # In[10]: functions.append(lambda x: x * 7) for function in functions: print function(4) # Functions # === # # Higher-order functions # --- # # A function that takes a function as argument is a higher-order function. # In[11]: help(map) # In[12]: map(add_two, [1, 2, 3, 4]) #
#

Hands on!

# #
    #
  1. Write a Python function that returns the maximum of two numbers.
  2. #
  3. Write a Python function that returns the maximum of three numbers. Try to reuse the first maximum of two numbers function.
  4. #
  5. Write a Python function that accepts a string as parameter. Next, it calculates and prints the number of upper case letters and lower case letters. Make us of the `isupper` and `islower` built in methods.
  6. #
# #
# Comprehensions # === # # List comprehensions # --- # # Similar to mathematical set notation (e.g., $\{ x ~|~ x \in \mathbf R \land x > 0\}$), we can create lists. # In[13]: [(x, x * x) for x in range(10) if x % 2] # We can do the same thing using `map` and `filter`, but list comprehensions are often more readable. # In[14]: map(lambda x: (x, x * x), filter(lambda x: x %2, range(10))) # Comprehensions # === # # Set and dictionary comprehensions # --- # # Similar notation can be used for (non-empty) sets. # In[15]: {c for c in 'LUMC-standard' if 'a' <= c <= 'z'} # And dictionaries. # In[16]: colors = ['red', 'white', 'blue', 'orange'] {c: len(c) for c in colors} # Everything is an object # === # # * Objects have properties and methods. # * Explore them using `dir(o)`, or by typing `o.` in the IPython interpreter. # In[17]: dir('abc')[-5:] # In[18]: help('abc'.upper) # In[19]: 'abc'.upper() # Code in files # === # # Running code from a file # --- # In[20]: cat examples/fsquare.py # In[21]: get_ipython().run_cell_magic('sh', '', 'python examples/fsquare.py\n') # Code in files # === # # Working with files in IPython # --- # # The `%run` magic runs the code from a file directly in IPython: # In[22]: get_ipython().run_line_magic('run', 'examples/fsquare.py') # You can edit and run a file with `%edit`. # In[23]: get_ipython().run_line_magic('edit', 'examples/fsquare.py') # Code in files # === # # Saving your IPython session history to a file # --- # # Give the `%save` magic a name and a range of input lines and it will save them to a `.py` file with that name: # # In [4]: %save my_session 1-3 # The following commands were written to file `my_session.py`: # a = 4 # a += 3 # b = a # Further reading # === # # * [The Python Tutorial](http://docs.python.org/2/tutorial/index.html) #
# From the official Python documentation. # # # * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) #
# Book on learning Python by exercises, online available for free. # # # * [The Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) #
# This opinionated guide exists to provide both novice and expert Python developers a best-practice handbook to the installation, configuration, and usage of Python on a daily basis. # # # * [A Primer on Scientific Programming with Python](http://codingcat.com/knjige/python/A%20Primer%20on%20Scientific%20Programming%20with%20Python.pdf) #
# Complete PDF version of the book. The aim of this book is to teach computer programming using examples from mathematics and the natural sciences. # # # * [Python Module of the Week](http://pymotw.com/) #
# Series of articles providing a tour of the Python standard library through short examples. # Homework assignment # === # # https://classroom.github.com/a/QU2iPYKn # 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)