You are on page 1of 3

Functions and Modules:

# Defining functions ----------------- # Recursive Function -----------------


def Fibo(x):
if x <= 2: # base case
# Arguments! return 1
def Fcn1(x, y): else:
print(x ** 2 + y) return Fibo(x - 1) + Fibo(x - 2)
# self-reference

Fcn1(11, 3)
print(Fibo(8))
# Function Output; Return like C/C++ -

Function scope: ----------------------


def Fcn2(x):
y = x / 2 # Global Scope
return y x = 2
print('PYthon') # Wont be run --- y = 3

Y = Fcn2(21) def FC1(x):


print(Y) print(x)
print(y)

# Help for function using "Docstrings"


def Root1(a, b, c): FC1(4)
"""
This function can output # Pure and Impure function
roots of quadratic equation # Pure Fcn in only dependent on Args
""" # Impure Fcn output is dependent on
delta = (b**2 - 4*a*c)**0.5 Global vars
x1 = b / 2 - delta / 2
x2 = b / 2 + delta / 2 Anonymous Function using Lambda ------
x = [x1, x2]
return x print((lambda x: x/2 + 5*x**2)(6))
# Single Expression

print(Root1(1, 5, 3)) Lf = lambda x, y: x/2 + 5*x**2 + y


# Assigned to another variables
print(Root1(1, 5, 3)) print(Lf(6, 0))

# Function reference can be assigned


# Usually use lambda as inside another
MyRootFcn = Root1 function
print(MyRootFcn(1, 5, 3)) def MyFcn(n):
return lambda x: x**n

# Functions reference can be passed as


arguments Pow2 = MyFcn(2)
Pow5 = MyFcn(5)
def Function1(x, f): print(Pow2(9))
return (x + f(x)) print(Pow5(2))

print(Function1(3, Fcn2))

Python course By: Mansour Torabi


Functions and Modules:

# Modules are libraries!


# Map ========================= # 1) Standard Libs, 2) Installed Libs, 3)
# Apply a function to List Items ----- User Libs
# To use modules, they should be
# take a Function and list imported!

# Syntax: # Syntax:
# map(fcn, List) # import Module_Name

L1 = [1, 2, 3, 4, 5, 6] import math

M1 = map(lambda i: i**2, L1) x = math.pi/2


print(M1) y = math.sin(x)
print(list(M1))
print("Sine of %.3f is: %.3f" % (x, y))
# Filter ============================
# Keep only matched Object
P = math.pi
F1 = filter(lambda x: x % 3 == 0, L1) X = [0, P/6, P/3, P/2, P*2/3, P*5/6, P]
print(F1) Y = []
print(list(F1))
for i in X:
Y.append(math.cos(i))
# Generator ==========================
# Behave a fcn like an iterator
print('X: ', [round(i, 2) for i in X])
print('Y: ', [round(i, 2) for i in Y])
def F_it():
import random
x = 0
R = []
while True:
for i in range(1000):
x = x + 1
R.append(random.random())
yield x
print('Expected Value: {:.5f}
'.format(sum(R)/len(R)))
# for i in F_it():
print(R[1:10])
# print(i)
# Import just specific functions
# Decorator ========================== # Syntax:
# Modify functions using another function # from LibName import FunctionName1,
FunctionName2, VarName
def Decorative1(f1):
def Wrap(): from math import sin, pow, pi
print('The result is:')
f1() Y1 = pow(sin(pi/6), 3)
print('Done') print("Sin(pi/3)^3: {:.3f}".format(Y1))
return Wrap
# Renaming Modules
@Decorative1 # Syntax:
def F1(): # import ModuleName as NewName
print(2**5) import math as M
F1() print(M.pi)

# Some of Std Libs:


# math, random, os, string, re, datetime,
multiprocessing, socket, email, json, ..

Python course By: Mansour Torabi


Functions and Modules:

# ==============================
# Third-party Libs (Modules):
# Mainly are stored in PyPI (Pai Pi I:
(Python Package Index)
# To install: pip program
# Syntax: pip install LibName
# Ex.: pip install numpy
import numpy as np

Module1.py

def Sum(x):
S = 0
for i in range(1, x + 1):
S += i
return S

def CumSum(X):
S = 0
C = []
for i in X:
S += i
C.append(S)
return C

A1 = {1, 4, 6, 7} # set

-------------------------------------------------
import Module1 as M1

x = 10
X = [2, 3, 5, 1, 2, 5]

print(M1.Sum(x))
print(M1.CumSum(X))

for ii in M1.A1:
print(ii, end=' ')

Python course By: Mansour Torabi

You might also like