Definition
""" Function definition
A function is a named sequence of statements
To end the function, you have to enter an empty line
Split a single instruction on multple lines with \
"""
def myfunc(a):
return a%2
def myprint(x):
return
print(myfunc(3)) # 1
print(myprint("2")) # None
print("Hello " + \
"World") # Hello World
Import
""" Import modules
To use a function from a module, you have to import it
When you save your scripts don't use
Python modules names like math, sys, csv
"""
import math
print(math.pi) # 3.141592653589793
print(math.sin(math.pi/2)) # 1.0
Local variable
""" Local, global variables
Local variable is destroyed after the function is called
To modify a global variable from within a function, use global statement
"""
def myfunc(a, b):
c = a + b # Look Here
return c
n = 0
def parse():
global n # Look Here
for i in range(10):
n = i
print(myfunc(3,4)) # 7
parse(); print(n) # 9
try:
print(c)
except Exception as e:
print(e) # name c not defined
Functions are objects
"""
In Python, functions are objects.
We can easily express constructors difficult to do in other languages.
"""
states = [' Alabama', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda?', 'south carolina##']
# Standard approach
# Apply operations to items
import re
def clear_strings(A):
result = []
for v in A:
v = v.strip()
v = re.sub('[!#?]', '', v)
v = v.title()
result.append(v)
return result
B = clear_strings(states)
print(B)
# Using a list of opperations
# This enable you to easily modify at a very high level
import re
def remove_punctuation(value):
return re.sub('[!#?]', '', value)
def clear_strings_ops(A, ops):
result = []
for v in A:
for func in ops:
v = func(v)
result.append(v)
return result
B = clear_strings_ops(states, [str.strip, remove_punctuation, str.title])
print(B)
# ['Alabama', 'Georgia', 'Georgia', 'Georgia', 'Florida', 'South Carolina']
Lambda
"""
Lambda (or anonymous) functions are used for writing single statement.
The result of a lambda function is the return value.
"""
def short_function(x):
return x*2
equiv_function = lambda x: x*2
# Example, sort by the number of distinc letters
strings = ['foo', 'card', 'bar', 'aaaa']
strings.sort(key=lambda x: len(set(x)))
print(strings)
# ['aaaa', 'foo', 'bar', 'card']
Last update: 10 days ago