0% found this document useful (0 votes)
40 views

Python 1

This document provides an introduction to key Python concepts including functions, loops, I/O, NumPy, and Matplotlib. It demonstrates how to define and call simple functions, use for loops to iterate over arrays, read and write files, and perform basic operations with NumPy like generating random numbers and matrix multiplication. It also shows how to create simple plots with Matplotlib by plotting built-in functions, scatter plots, and histograms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Python 1

This document provides an introduction to key Python concepts including functions, loops, I/O, NumPy, and Matplotlib. It demonstrates how to define and call simple functions, use for loops to iterate over arrays, read and write files, and perform basic operations with NumPy like generating random numbers and matrix multiplication. It also shows how to create simple plots with Matplotlib by plotting built-in functions, scatter plots, and histograms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Python – Functions, Loops, I/O,

Numpy, Matplotlib
Rajiv Bhutani
XIM Bhubaneswar
2018-2020
REPL
• Fast Prototyping
• Takes single expression from user, processes it, outputs it
• Helps in exploratory programming and debugging, because
you can see the result before deciding what expression to
input next

• Read – Evaluate – Print – Loop (REPL)

• Vs

• Edit – Compile – Run – Debug


First Function
• In [1]: print("Hello World")
• Hello World

• Functions in python start with def


• def hello():
• print("Hello Hello")

• In [2]: hello()
• Hello Hello

• In[3]: pv = 100
…: pv*(1+0.015)**3
• Out[3]: 104.56783749999997
More Examples
• def fv_f(pv,r,n):
• """Objective: Estimate present value
• formula : pv = fv/((1+r)^n)
• fv: future value
• r: discount rate
• n: time period
• """
• return pv*(1+r)**n

• In[4]: fv_f(100,0.1,2)
• Out[4]: 121.00000000000001

• In[5]: Help(fv_f)
• Help on function fv_f in module __main__:

• fv_f(pv, r, n)
• Objective: Estimate present value
• formula : pv = fv/((1+r)^n)
• fv: future value
• r: discount rate
• n: time period
For Loop
• In[6]: import numpy as np

• In[7]: cashFlows=np.array([-100,50,40,30])

• In[8]: for cash in cashFlows:


• …: print(cash)
• …:
• -100
• 50
• 40
• 30
Tuple Vs Dictionary
• () Used to denote a tuple type of data.
• Values in a tuple can’t be modified
• Useful if some values should never be modified
• Tuples start from 0
• Dictionary stores data with key-value pairs
• Dictionary is not ordered and it requires keys to
be hashable
• Dictionary values can be modified
Tuple Vs List
• In[9]: x=[1,2,3]
• In[10]: x[0]=2
• In[11]: x=(2,2,3)
• Out[11]: [2,2,3]

• In[12]: y=(7,8,9)
• In[13]: y[0]=2
• Traceback (most recent call last):
• File "<ipython-input-51-f39ee00d3d8d>", line 1, in <module>
• y[0]=10
• TypeError: 'tuple' object does not support item assignment

• In[14]: type(x)
• Out[14]: list

• In[15]: type(y)
• Out[15]: tuple
Npv Functions
• def npv_f(rate, cashflows):
• total = 0.0
• for i in range(0,len(cashflows)):
• total += cashflows[i]/(1+rate)**i
• return total
• In[16]: r=0.035
• In[17]: cashflows=[-100,-30,10,40,50,45,20]
• In[18]: npv_f(r,cashflows)
• Out[18]: 14.158224763725372
Npv Functions from Excel
• NPV function from Excel is actually a PV function, i.e. it can be applied only to
future
• def npv_Excel(rate, cashflows):
• total = 0.0
• for i, cashflow in enumerate(cashflows):
• total += cashflow/(1+rate)**(i+1)
• return total

• In[16]: r=0.035
• In[17]: cashflows=[-100,-30,10,40,50,45,20]

• In[18]: npv_Excel(r, cashflows[1:7]+ cashflows[0])


• Out[18]: 14.158224763725372

• In[19]: npv_Excel(r, cashflows[1:7]


• Out[19]: 114.15822476372537
If Function
• In[20]: cashFlows = [550,-500,-500,-500,1000]
• In[21]: r=0
• In[22]: while (r<1.0):
• …: r+=0.000001
• …: npv=npv_f(r,cashFlows)
• …: if(abs(npv)<0.0001):
• ...: print(r)
• …:
• 0.07163900000005098
• 0.33673299999790873
Conditional IF
• >>>a=3
• >>>b=2
• >>>If(a>0 and b>0):
• print(“both positive”)
• >>>if(a>0 or b>0):
• print(“at least one is positive”)
if with elif
• >>>grade = 82

• Write in editor:
• if grade>=90:
• print('A')
• elif grade>=80:
• print('B')
• elif grade>=70:
• print('C')
• elif grade>=60:
• print('D')
• else:
• print('F')

• Run the program in editor


Math Library
• In[20]: import math
• In[21]: math.sqrt(2)
• Out[21]: 1.4142135623730951

• In[22]: from math import *


• In[23]: Sqrt(3)
• Out[23]: 1.7320508075688772

• >>>dir(math)
Working with Python
• To find all string related functions
• >>>dir(‘’)

• >>> x='this is great‘


• >>>x.split()
• ['this', 'is', 'great']
Reading a Text File
• Make a text file called test.txt, store somewhere in your PC with
following data
• ab
• 12
• 34
• Now type following:
• In[24]: f = open(“C:/….path name/test.txt”,”r”)
• In[25]: x=f.read()
• In[26]: f.close()
• In[27]: print(x)
• ab
• 12
• 34
Importing through Numpy
• >>> import numpy as np
• >>>r=0.023
• >>>pv=np.array([100,300,500])
• >>>type(r)
• Float
• >>>type(np)
• Numpy.ndarray
• >>>7/3
• 2.3333333333333335
• >>>round(7/3)
• 2
• >>>round(7/3,5)
• 2.33333
Working with Numpy
Command Explanation
A=np.zeros(10) Array with 10 zeros
B=np.zeros((3,2),dtype=float) 3 by 2 with zeros
C=np.ones((4,3),float) 4 by 3 with all ones
D=np.array(range(0,9),float) 0,1,2,3,…,9
E1=np.identity(4) Identity 4 by 4 matrix
E2=np.eye(4) Same as above
E3=np.eye(4,k=1) Starts from k=1
F=np.arange(1,20,3,float) From 1 to 20 interval 3
G=np.array([[2,2,2],[3,3,3]]) 2 by 2 with 2 in 1st row and 3 in 2nd row
H=np.zeros_like(G) All zeros
H=np.ones_like(G) All ones
Working with Numpy
• >>>x=np.array([10,20,30])
• >>>x.sum()
• 60

• >>>x=np.array([[1,2],[5,6],[7,9]])
• >>>print(x)
• >>> y=x.flatten()
• >>>print(x)
• >>>print(y)
• >>>x2=np.reshape(y,[2,3])
• >>>print(x2)
Working with Numpy
• >>>x=np.array([[1,2,3],[3,4,6]])
• >>>np.size(x)
• 6
• >>>np.size(x,0)
• 2
• >>>np.size(x,1)
• 3
• >>>np.size(x,2)
• Error
• >>>np.std(x)
• 1.5723301886761005
• >>>np.std(x,0)
• array([1. , 1. , 1.5])
• >>>np.std(x,1)
• array([0.81649658, 1.24721913])
• >>>Total=x.sum()
• 19
Random Numbers with Numpy
• >>>z=np.random.rand(50)
• >>>print(z)
• >>>y=np.random.normal(50)
• >>>print(y)
• >>>y=np.random.normal(500)
• >>>print(y)
• >>>y=np.random.normal(size=50)
• >>>print(y)
• >>>mean(z)
• >>>avg(z)
• >>>average(z)

• >>>np.mean(z) & np.mean(y)


• >>>np.std(z) & np.std(y)
• >>>r=np.array(range(0,100),float)/100
• >>>print(r)
Matrix multiplication with Numpy
• >>>a=np.array([[1,2,3],[4,5,6]],float)
• >>>b=np.array([[1,2],[3,3],[4,5]],float)
• >>>np.dot(a,b)
• array([[19., 23.],
• [43., 53.]])
Data Output
• >>>f = open(“C:/….path name/out.txt”,”w”)
• >>>x=“This is great learning python”
• >>>f.write(x)
• >>>f.close()

• Check the out.txt file


Plotting using Matplotlib
• >>>import matplotlib
• >>> from matplotlib.pyplot import *
• In Editor:
• plot([1,2,3,9])
• xlabel("x-axis")
• ylabel("y-axis")
• title("my figure")
• show()
Plotting using Matplotlib
• In Editor:
• from pylab import *
• x=np.linspace(-np.pi,np.pi,256,endpoint=True)
• c,s = np.cos(x), np.sin(x)
• plot(x,c), plot(x,s)
• show()

• Note: linspace function has 4 arguments: start,


stop, num and endpoint
Plotting using Matplotlib
• In Editor:

• n=1024
• X=np.random.normal(0,1,n)
• Y=np.random.normal(0,1,n)
• scatter(X,Y)
• show()

You might also like