Functions& Modules
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function:
my_function()
-----------------------------------------------------------------------------------
Function Arguments
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function
is called, we pass along a first name, which is used inside the function to print
the full name:
def my_function(fname):
print( " Hello "+fname)
my_function("Emil")
my_function("Tobias")
my_function("Linus")
-----------------------------------------------------------------------------------
Parameters Vs Arguments
A parameter is the variable listed inside the parentheses in the function
definition.
An argument is the value that are sent to the function when it is called.
----------------------------------------------------------------------------------
The different types of argument passing are:
1. Positional Arguments:
These are the most common type of arguments in Python functions. Positional
arguments are passed based on their position or order in the function definition.
The number and order of arguments passed must match the function signature.
def greet(name, age):
print("Hello " + name +" you are " ,age," years old.")
greet("John", 25) # Positional arguments passed
2. Keyword Arguments:
In this type of argument passing, values are associated with the parameter
names when calling
the function. This allows you to pass arguments in any order as long as you specify
the parameter names.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=25, name="John") # Keyword arguments passed
3. Default Arguments:
Default arguments have a predefined value in the function signature. If
the caller does not provide a value
for that argument, the default value is used.
def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")
greet("John") # Default argument age=30 is used
greet("Kate", 25) # Provided argument age=25 overrides the default value
4. Variable Length Arguments:
a) *args (Non-keyword Variable Length Arguments): This allows passing a
variable number of positional arguments to a function. The arguments are packed
into a tuple, which can be accessed within the function using *args.
def calculate_sum(*numbers):
total = sum(numbers)
print(f"The sum is {total}")
calculate_sum(1, 2, 3, 4) # Variable number of arguments passed
b) **kwargs (Keyword Variable Length Arguments): This allows passing a
variable number of keyword arguments to a function. The arguments are packed into a
dictionary, which can be accessed within the function using **kwargs.
def print_info(**details):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="John", age=25, city="New York") # Variable number of keyword
arguments passed
-----------------------------------------------------------------------------------
----------
Scope of a Function
Local Scope
A variable created inside a function belongs to the local scope of that
function, and can only be used inside
that function.
def myfunc():
x = 300
print(x)
myfunc()
----------------------------------------------------
Function Inside Function
As explained in the example above, the variable x is not available outside the
function, but it is available for any function
inside the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
-----------------------------------------------------
Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
Global variables are available from within any scope, global and local.
x = 300
def myfunc():
print(x)
myfunc()
print(x)
----------------------------------------------------
Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two
separate variables, one available in the global scope (outside the function) and
one available in the local scope
(inside the function):
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
-----------------------------------------------------------
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.
The global keyword makes the variable global.
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
-----------------------------------------------------------------------------------
---------------------------
Python Docstrings
Python documentation strings (or docstrings) provide a convenient way of
associating documentation with
Python modules, functions, classes, and methods.
It’s specified in source code that is used, like a comment, to document a specific
segment of code. Unlike conventional
source code comments, the docstring should describe what the function does, not
how.
Declaring Docstrings:
The docstrings are declared using ”’triple single quotes”’ or “””triple
double quotes””” just below the class,
method or function declaration. All functions should have a docstring.
Accessing Docstrings:
The docstrings can be accessed using the __doc__ method of the object or
using the help function.
def my_function():
'''Demonstrates triple double quotes
docstrings and does nothing really.'''
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
-----------------------------------------------
One-line Docstrings
def power(a, b):
"""Returns arg1 raised to power arg2."""
return a**b
print(power.__doc__)
print(power(3,2))
----------------------
Multi-line Docstrings
def my_function(arg1):
"""
Summary line.
Extended description of function.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
return arg1
print(my_function.__doc__)
-----------------------------------------------------------------------------------
----
Lambda Functions& map
Lambda Function
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one
expression.
syntax
function_name = lambda arguments : expression
ex.1
x = lambda a : a + 10
print(x(5))
ex.2
x = lambda a, b : a * b
print(x(5, 6))
ex.3
x = lambda a,b : a if a>b else b
print(x(4,7))
ex.4
x = lambda a: [i for i in range(a)]
print(x(10))
----------------------------------------------
Python Map Lambda
>>> nums = [1, 2, 3, 4, 5]
>>>
>>> map(lambda n: 2 * n, nums) # print fails, so list() below
<map object at 0x10ce142e8>
>>>
>>> list(map(lambda n: 2 * n, nums)) # e.g. double each n
[2, 4, 6, 8, 10]
>>>
>>> list(map(lambda n: n * -1, nums))
[-1, -2, -3, -4, -5]
>>>
>>> list(map(lambda n: 2 ** n, nums))
[2, 4, 8, 16, 32]
>>>
>>> strs = ['Summer', 'is', 'coming']
>>> list(map(lambda s: [Link]() + '!', strs))
['SUMMER!', 'IS!', 'COMING!']
----------------------------------------------------
Lambda Def Equivalence
Map is often used with lambda, but it works with a def too. With def come the
advantages of multiple lines,
loops, comments, tests and what have you. Here is the above double-n computation
written as a def instead of a lambda:
def double(n):
return n * 2
>>> nums = [1, 2, 3, 4, 5, 6]
>>> list(map(double, nums)) # use name of function "double"
[2, 4, 6, 8, 10, 12]
--------------------------------------------------------
Exercise
1. Write a Python function that takes two numbers as input and returns their sum.
2. Write a Python function to check whether a given number is even or odd.
3. Write a Python function to calculate the factorial of a given number.
4. Write a Python function that takes a list of numbers as input and returns the
largest number in the list.
5. Write a Python function that takes a string as input and returns the number of
vowels in the string.
6. Write a Python function to check if a given string is a palindrome.
7. Write a Python function to calculate the area of a circle given its radius.
8. Write a Python function that takes a list of strings as input and returns a new
list with all the strings capitalized.
[Link] a Python function to find the common elements from two lists.
[Link] a Python function that takes a number as input and returns True if it is a
prime number, and False otherwise.
-----------------------------------------------------------------------------------
------------------------------------------------
Python Create Module
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
------------------
To create a module just save the code you want in a file with the file
extension .py:
Save this code in a file named '[Link]'
def greeting(name):
print("Hello, " + name)
Use a Module
--------------
Now we can use the module we just created, by using the 'import' statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
[Link]("Jonathan")
Variables in Module
---------------------
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Save this code in the file [Link]
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
-------------------
With Using 5 methods, we can naming a Module
Save this code in a file named '[Link]'
def greeting(name):
print("Hello, " + name)
method 1:
import mymodule
[Link]('Jonathan')
method 2:
import mymodule as my
[Link]('Jonathan')
method 3:
from mymodule import *
greeting('Jonathan')
method 4:
from mymodule import greeting
greeting('Jonathan')
method 5:
from mymodule import greeting as hai
hai('Jonathan')
--------------------------------------------------------------------------------
Standard Modules in Python
1. statistics module
mean() --> Arithmetic mean ('average') of data.
median()--> Median (middle value) of data.
median_low()--> Low median of the data is the lower of two middle values when
the number of data elements
is even, else it is the middle value.
2. math module
sqrt(x): Return the square root of x.
ceil(x): Return the ceiling of x, the smallest integer greater than or equal
to x.
floor(x): Return the floor of x, the largest integer less than or equal to x.
factorial(x): Return x factorial.
exp(x): Return e raised to the power x, where e = 2.718281… is the base of
natural logarithms.
[Link] module
random() : Return a random float number between 0.0 to 1.0.
randint(a, b): Return a random integer x, which belongs to the range [a,b].
choice(seq): Return a random element from the non-empty sequence seq.
shuffle(x): Shuffle the sequence x in place.
randrange() : Generate Random Numbers within Range
[Link] Module
getcwd() : The getcwd() function confirms returns the current working
directory.
import os
print([Link]()) #output: 'C:\\Python37'
mkdir() : To create new directory
import os
print([Link]()) #output: 'C:\Python37'
[Link]("MyPythonProject")
chdir() : Changing the Current Working Directory
import os
[Link]("C:\MyPythonProject") # changing current workign directory
print([Link]()) #output: 'C:\MyPythonProject'
rmdir() : Removing a Directory
import os
print([Link]())
[Link]("C:\\MyPythonProject") #PermissionError: [WinError 32] The
process cannot access the file because it is being used by another process
[Link]("..")
[Link]("MyPythonProject")
[Link] Module
[Link] : This is an environment variable that is a search path for all
Python modules.
[Link] : This attribute displays a string containing the version number
of the current Python interpreter.