Dr. Hari V S
Department of Electronics and Communication
College of Engineering Karunagappally
What You will Learn
- You will learn the syntax of Python functions
The Syntax
The syntax used the keyword $def$ followed the name of the function again followed by a colon (:) that is then followed by an indented code block of instructions. The function
def function_name(arg1.arg2,....argN):statements
return results
A Simple Python Function
Needless to say that the statements and the return command should form an indented block.
Consider a simple function that returns the sum of the input values. It is realized as the function below.
def summ(x,y):
return x+y
Unlike MATLAB or IDL, it is possible to execute a function in the Python shell. You may type the above function in a Python shell or an enhanced Python shell such as IPython. Once the function is executed, if you type summ(7,4), it returns 11. If you give summ(2+3*1j,4-2*1j), it returns 6+1j.Python Function for Discrete Fourier Transform (DFT)
Let us consider another function that returns the DFT of a $N$- point sequence, denoted as dftof(x), as listed below.def dftof(x):
return mat(fft(eye(len(x))))*transpose(mat(x))
The command eye(len(x)) returns an $N\times N$ identity matrix, where $N$ is the length of the sequence $x$. The FFT of the identity matrix returns the $N\times N$ DFT matrix, the premultiplication by which returns the DFT of the random vector $x$.Python Function for Fibonacci Series
The following Python function returns the first $N$ Fibonacci numbers.def fibinocci(n):
w=[ ]
y=[0,1]
for i in range(2,n):
t=y[i-1]+y[i-2]
y.append(t)
return y
Observe that $0$ is also included in the series. The first line in the series initiates a blank array $w$. The second lines loads the first two values of the sequence. The remaining values are computed and appended to the blank array using the iterative steps in the for loop.
What You Learned
- You understood the syntax and use of Python functions
Comments
Post a Comment