<jupyter_start><jupyter_text>User defined functionsIt is often useful to define your own function to do something then have your python code call that function.This can be useful when you want to perform the same computation in several different scenarios.  If you put this computation inside a function then you won't have to rewrite your code each time you want to make the computation.There are 2 ways to do this1. defined functions2. lambda functions (inline)<jupyter_code># define a function that takes an input, squares it, adds 7, then returns the answer
def x2p7(x):
    """    this is my documentation string
    it needs to be in triple double quotes
    this function returns x^2 + 7"""
    y = x*x
    z = y+7
    return z

print('x^2 + 7 = ',x2p7(5))
print(x2p7.__doc__)
# if we have a documentation string then we can quickly access it with shift+tab
x2p7
# these functions can be very complicated
def complicated_function(x,y):
    lenx = len(x)
    leny = len(y)
    z = [0]*(lenx*leny)
    counter = 0
    for i in x:
        for j in y:
            z[counter] = i*j
            counter = counter+1
    return z

output = complicated_function([1,2,3,4],[34,234,31,888])
print(output)
# Scope
print(lenx)
# a variable defined inside a function cannot be accessed from outside the function
# but a variable defined outside a function can be accessed from inside the function!
outside_var = 213
def a_function(x):
    return outside_var*x

print(a_function(2))
print(outside_var)
# we can address the scope issue by declaring a variable as global
def another_function(x):
    global global_var
    global_var = 5
    return global_var*x

print(another_function(4))
print(global_var)
# the first function we wrote (x2p7) was actually a very simple function
# we can define such simple functions 'inline' using something called a lambda function

x2p7v2 = lambda x: x*x+7
print(x2p7v2(5))
# lambda functions can also take more than 1 input
another_lambda = lambda x,y,z: x*y + y*z + x/y
print(another_lambda(2,5,6))<jupyter_output>40.4
{'fraction_non_alphanumeric': 0.07474352711284807, 'fraction_numerical': 0.028334147532975085, 'mean_word_length': 3.982968369829684, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '124420', 'license': 'Apache-2.0', 'n_tokens_mistral': 647, 'n_tokens_neox': 618, 'n_words': 271, 'path': '01 Fundementals of AIML/Week 1 - Python Fundamentals/.ipynb_checkpoints/05 Functions-checkpoint.ipynb', 'repo_name': 'senthilprabhut/DataScience', 'size': '2047'}