Functions

Built-in Functions

print(), input(), len(), str(), int(), float(), map()

Lambda Expressions

A Lambda Expression is also known as anonymous function. It is a function with no name that is used one time. A Lambda Expression is commonly used with built-in functions such as map() and filter()

Named function

In [1]:
def times_two(var):
    return var*2

Lambda function equivalent

In [2]:
lambda var: var*2
Out[2]:
<function __main__.<lambda>>

Example: Using lambda expression with map()

In [3]:
seq = [1,2,3,4,5]
map(lambda num:num*2, seq)
Out[3]:
<map at 0x3ef00d0>
In [4]:
list(map(lambda num:num*2, seq))
Out[4]:
[2, 4, 6, 8, 10]

Example: Using lambda expression with filter()

In [5]:
seq = [1,2,3,4,5]
list(filter(lambda num:num%2==0, seq))
Out[5]:
[2, 4]

Standard Library

You can import modules and get access to new functions. The modules that come with Python are called standard library.

In [6]:
import random, sys, os, math
In [7]:
import random
random.randint(1, 10)
Out[7]:
1
In [8]:
# from random import *
# random.randint(1, 10)

The sys.exit() function will immediately quit your program.

In [9]:
# import sys
# sys.exit()

Third-Party Modules

You can also install third-party modules using the pip tool. To install pip tool, the key is to know where your python is installed (where pip.exe is located) and add the path to environment variables. then you can finally install python modules in command prompt. If you have anaconda installed, use anaconda prompt instead. For more information on installing third-party modules, click [here]

pyperclip

The pyperclip third-party module allows you to copy and paste text for reading and writing text to the clipboard.

To install pyperclip:

In [10]:
# At command prompt/ anaconda prompt
# pip install pyperclip

To use pyperclip:

In [11]:
import pyperclip

pyperclip.copy('Some text')
pyperclip.paste()
Out[11]:
'Some text'

Writing Your Own Function

Functions are like a mini-program inside your program. The main point of functions is to get rid of duplicate code (de-duplicating).

Parameters

The def statement defines a function. The parameters are the variables in between the function's parenthesis in the def statement.

In [12]:
def functionName(param):
  print(param)

You can also set default value for parameter

In [13]:
def my_func(param='default'):
  print(param)

To invoke a function, add () after the function name:

In [14]:
my_func()
default

The return value is specified using the return statement

In [15]:
def functionName(param):
  return param + 1

Every function has a return value. If your function doesn't have a return statement, the default return value is None (meaning lack of value) e.g. the print() function returns None.

Arguments

An argument is the value passed in the function call. Keyword arguments to function are usually for optional arguments. The print() function has keyword arguments end and sep.

The print() function

The print() function automatically add a keyword argument new line to end of function.

In [16]:
print('Hello')
print('World')
Hello
World

However, you can change the Keyword argument by using end

In [17]:
print('Hello', end=' ')
print('World')
Hello World

If you pass multiple strings arguments to print(), it automatically add space between strings

In [18]:
print('cat', 'dog', 'mouse' )
cat dog mouse

You can override this by passing the sep argument to print()

In [19]:
print('cat', 'dog', 'mouse', sep="ABC" )
catABCdogABCmouse

Add Your Own Documentation String to a Function

Add a pair of triple double quotes """ and put you documentation string inside

In [20]:
def my_func(arg=2):
    """
    Docstring goes here!
    """
    return arg*5

You can view the docstring in Jupyter notebook by clicking the line and then press shift-tab

Global and Local Scopes

A scope can be thought of as an area of the source code, and as a container of variables.

The global scope is code OUTSIDE of all functions. Variables assigned here are global variables. The local scope is code INSIDE of a function. Variables assigned here are local variables.

In [21]:
spam = 42 # global variable

def eggs():
  spam = 42 # local variable

print('Some code here')
Some code here

Code in the global scope cannot use any local variable

In [22]:
def spam():
  eggs = 99

spam()
print(eggs) # NameError: name 'eggs' is not defined
<function eggs at 0x03EF9F60>

Code in local scope can access global variable

In [23]:
def spam():
  print(eggs)

eggs = 42
spam() # 42
42

Global Statement

In [24]:
def spam():
  global eggs
  eggs = 'Hello'
  print(eggs)

eggs = 42
spam() # 42
print(eggs) # 42
Hello
Hello

Code in a function's local scope cannot use variables in another local scope

In [25]:
def spam():
  eggs = 99
  bacon()
  print(eggs)

def bacon():
  ham = 101
  eggs = 0

spam() # 99
99

If there's an assignment statement of a variable in a function, that is a local variable unless that variable been marked global with a global statement

Assignment statement = Local variable No assignment statement = Global variable

In [26]:
def spam():
  eggs = 'Hello'
  print(eggs)

eggs = 42
spam() # Hello
print(eggs) # 42
Hello
42

Global statement

In [27]:
def spam():
  # change global eggs var to 'Hello'
  # Do not create local var eggs
  global eggs
  eggs = 'Hello'
  print(eggs)

eggs = 42
spam() # Hello
print(eggs) # Hello
Hello
Hello

The purpose of scope is to isolate code so that the cause of bugs is limited to a particular area of a program.