Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # DEFINING FUNCTIONS
- # define a function with no arguments and no return values
- ```python
- def print_text():
- print 'this is text'
- ```
- ## call the function
- ```python
- print_text()
- ```
- ## define a function with one argument and no return values
- ```python
- def print_this(x):
- print x
- ```
- ## call the function
- ```python
- print_this(3) # prints 3
- n = print_this(3) # prints 3, but doesn't assign 3 to n
- # because the function has no return statement
- ```
- ## define a function with one argument and one return value
- ```python
- def square_this(x):
- return x**2
- ```
- ## include an optional docstring to describe the effect of a function
- ```python
- def square_this(x):
- """Return the square of a number."""
- return x**2
- ```
- ## call the function
- ```python
- square_this(3) # prints 9
- var = square_this(3) # assigns 9 to var, but does not print 9
- ```
- ## define a function with two 'positional arguments' (no default values) and
- one 'keyword argument' (has a default value)
- ```python
- def calc(a, b, op='add'):
- if op == 'add':
- return a + b
- elif op == 'sub':
- return a - b
- else:
- print 'valid operations are add and sub'
- ```
- ## call the function
- ```python
- calc(10, 4, op='add') # returns 14
- calc(10, 4, 'add') # also returns 14: unnamed arguments are inferred by position
- calc(10, 4) # also returns 14: default for 'op' is 'add'
- calc(10, 4, 'sub') # returns 6
- calc(10, 4, 'div') # prints 'valid operations are add and sub'
- ```
- # use 'pass' as a placeholder if you haven't written the function body
- ```python
- def stub():
- pass
- ```
- ## return two values from a single function
- ```python
- def min_max(nums):
- return min(nums), max(nums)
- ```
- ## return values can be assigned to a single variable as a tuple
- ```python
- nums = [1, 2, 3]
- min_max_num = min_max(nums) # min_max_num = (1, 3)
- ```
- ## return values can be assigned into multiple variables using tuple unpacking
- ```python
- min_num, max_num = min_max(nums) # min_num = 1, max_num = 3
- ```
- # ANONYMOUS (LAMBDA) FUNCTIONS
- primarily used to temporarily define a function for use by another function
- ### define a function the "usual" way
- ```python
- def squared(x):
- return x**2
- ```
- ### define an identical function using lambda
- ```python
- squared = lambda x: x**2
- ```
- ### sort a list of strings by the last letter (without using lambda)
- ```python
- simpsons = ['homer', 'marge', 'bart']
- def last_letter(word):
- return word[-1]
- sorted(simpsons, key=last_letter)
- ```
- ### sort a list of strings by the last letter (using lambda)
- ```python
- sorted(simpsons, key=lambda word: word[-1])
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement