Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

NUMERICAL METHODS

(MCSC-202)
USING PYTHON
By
Samir Shrestha
Department of Mathematics
Kathmandu University, Dhulikhel

Lecture-3
Outlines

 Branching (if, if-else, if-elif-else)

 for loop

 while loop

 Sequence: String, List, Tuple

 User-defined function
References
1. H. Bhasin, Python Basics A Self-Teaching Introduction, 2019
2. H. P. Langtangen, A Primer on Scientific Programming with Python,
2016
3. Jaan Kiusalaas, Numerical Methods in Engineering with Python 3,
2013
4. Robert Johansson, Numerical Python: Scientific Computing and
Data Science Applications with Numpy, SciPy and Matplotlib, 2019
5. https://www.javatpoint.com/python-tutorial
Branching
Branching
IF, IF-ELSE, IF-ELIF-ELSE Statements

Decision making is the most important aspect of almost all the


programming languages. As the name implies, decision making
allows us to run a particular block of code for a particular decision

Indentation in Python
 In Python, indentation is used to declare a block of codes. If
two statements are at the same indentation level, then they
are the part of the same block
 Generally, four spaces are given to indent the statements
which are a typical amount of indentation in python
 The indentation takes place in branching and other stuff in
python like for and while loops, user-defined function
Branching
The IF Statements
 Executes a group of statements only if a certain condition is true
Otherwise, the statements are skipped
 The test condition of if statement can be any valid logical
expression which can be either evaluated to true or false

Python syntax :
if (test condition):
statements

Example
gpa = 3.4
if gpa > 2.0:
print("Your application is accepted")
Branching
The IF-ELSE Statements
 Executes one block of statements if a certain condition is True,
and a second block of statements if it is False

Python syntax :
if (test condition):
statements
else:
statements
Example
gpa = 3
if gpa > 2.5:
print("Welcome to Kathmandu
University!")
else:
print("Your application is denied.")
Branching
The IF-ELIF-ELSE Statements
 Multiple conditions can be chained with elif

Python syntax :
if (test condition):
statements
elif (test condition):
statements
elif (test condtion):
statements
else:
statements
Branching
The IF-ELIF-ELSE Statements
Example
marks = 75
if marks >= 80 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks >= 60 and marks = 80:
print("You scored grade B + ...")
elif marks >= 40 and marks = 60:
print("You scored grade B ...")
elif (marks >= 30 and marks = 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

Do interactively
for Loop
The for loop
The for loop in Python is used to execute statements finite number of
times until the items in the sequence (list, tuple or dictionary) is empty
Python syntax :
for iteration_var in sequence:
statements
Example:

Next item
for x in range(1, 5):
y = x*x
print(x, "squared is", y)

Output:
squared is 1
squared is 4
squared is 9 Exit the loop
squared is 16

Do interactively
while Loop
The while loop
while loop allows a part of the code to be executed as long as the given condition
is true. It can be viewed as a repeating if statement. The while loop is mostly used in
the case where the number of iterations is not known in advance
Python syntax :
while condition:
statements
Example:
n = 1

Next item
while n <= 200:
n = n*5
print("n = ", n)
Output:
n = 5
n = 25
n = 125 Exit the loop
N = 625
Do interactively
Break, continue, pass
break in a loop
About break
Example:

continue in a loop
About continue
Example:

pass in a loop
About pass
Example:
Sequences
Sequence Types
String
 Strings can be created by enclosing the character or the sequence of characters
in the quotes. Python allows us to use single quotes, double quotes, or triple
quotes to create the string. It is immutable data type.
 Examples
Str1 = ‘Hello‘, Str2 = "Hi Python !"
List
 A list is ordered collection of values or items of different types
 The items in the list are separated with the comma (,) and enclosed with the
square brackets []
 List is mutable data type, so its values can be updated
 Examples:
L1 = [1, 4, 6], L2 = *3.5, 2, ‘Hello‘+
Tuple
 A tuple is ordered collection of values or items of different types
 The items in the tuple are separated with the comma (,) and enclosed with the
round brackets ()
 Tuple is immutable data type, so its values can not be updated
 Examples: T1 = (1, 4, 6), T2 = (3.5, 2, ‘Hello‘)
Sequence Types: String
String Indexing and Slicing
In python, the indexing starts from 0 and also supports negative indexing
Example:
Forward index 0 1 2 3 4
Str = "HELLO"
H E L L O
-5 -4 -3 -2 -1 Backward index
Indexing: Slicing:
Str[0] gives 'H' Str[:] gives 'HELLO' Operations +, * on strings
Str[1] gives 'E' Str[0:] gives 'HELLO'
Str1 = "Hello„
Str[0:4] gives 'HELL' Str2 = "Ram“
Str[2] gives 'L'
Str[0:5] gives 'HELLO' R1 = Str1 + Str2 results 'HelloRam'
Str[3] gives 'L' R2 = Str1 + ' ' + Str2 results 'Hello Ram'
Str[0:-1] gives 'HELL'
Str[4] gives 'O' R3 = 3*Str2 ' results 'RamRamRam‚
Str[2:] gives 'LLO'
Str[-1] gives 'O' + : concatenation operator
Str[2:4] gives 'LL'
Str[-2] gives 'L' *: repetition operator

There are other built-in methods and functions on strings: capitalize(),


partition(), split(), count(), len() naming few
Sequence Types: String
Reassigning strings
The string object doesn't support item assignment. Strings
are immutable in python.
Example:
Str = "HELLO“
Performing:
Str[0] = 'S‘

Traceback (most recent call last):


File "<pyshell#33>", line 1, in <module>
Str[0] = 'S'
TypeError: 'str' object does not support item assignment

Do interactively
Sequence Types: List
List
 A list is ordered collection of values or items of different types
 The items in the list are separated with the comma (,) and enclosed with the
square brackets []
 List is mutable data type, so its values can be updated
 Examples:
L1 = [1, 4, 6], L2 = *3.5, 2, ‘Hello‘+, L3 = [3.1, 'Hi', [2,'KU']]
Let us take a list: Forward index 0 1 2 3 4
List = [3, -2, 5, 0, 7]
3 -2 5 0 7
Indexing: Slicing: -5 -4 -3 -2 -1 Forward index
List[0] gives 3 List[:] gives [3, -2, 5, 0, 7]
List[1] gives -2
List[0:] gives [3, -2, 5, 0, 7] Updating:
List[2] gives 5
List[2:4] gives [ 5, 0] List[0] = 4 gives List = [4, -2, 5, 0, 7]
List[3] gives 0
List[0:5] gives [3, -2, 5, 0, 7] List[-1] = 'H' gives List = [3, -2, 5, 0, 'H']
List[4] gives 7
List[0:-1] gives [3, -2, 5, 0]
List[-1] gives 7 List[1:3]=[-1, 4] gives List = [3, -1, 4, 0, 7]
List[2:] gives [ 0, 7]
List[-3] gives 5
Sequence Types: List
Python List Operations
The concatenation (+) and repetition (*) operator work in the same
way as they were working with the String

Consider two lists: Iteration a list:


L1 = [1, 3, 4], L2 = [5, 2, 7] List = ["John", "David", "James", "Jonathan"]
for i in List:
Concatenation (+): print(i)
L1 + L2 gives [1, 3, 4, 5, 2, 7] Output:
John
David
Repetition (*): James
Jonathan
2*L2 gives [5, 2, 7, 5, 2, 7]
Sequence Types: List
Python List Built-in Functions
Functions Meaning
len(list) used to calculate the length of the list.
max(list) returns the maximum element of the list.
min(list) returns the minimum element of the list.
list(seq) converts any sequence to the list.

Example:
List = [3, 4.5, -2, 0, 1]

len(List) gives 5
max(List) gives 4.5
Sequence Types: List
Python List Methods
Functions Meaning
list.append(obj) The element represented by the object obj is added to the list.
list.clear() It removes all the elements from the list.
list.count(obj) It returns the number of occurrences of the specified object in
the list.
list.extend(seq) The sequence represented by the object seq is extended to the
list.
list.index(obj) It returns the lowest index in the list that object appears.
list.insert(index, obj) The object is inserted into the list at the specified index.
list.pop(obj=list[-1]) It removes and returns the last object of the list.
list.remove(obj) It removes the specified object from the list.
list.reverse() It reverses the list.
list.sort([func]) It sorts the list by using the specified compare function if given.
List = [3, 4.5, -2, 0, 1]
Example: List.append(2) gives List = [3, 4.5, -2, 0, 1, 2]
Do interactively
Sequence Types: Tuple
Tuple
 A tuple is ordered collection of values or items of different types
 The items in the tuple are separated with the comma (,) and enclosed with the
round brackets ()
 Tuple is immutable data type, so its values can not be updated
 Examples: T1 = (1, 4, 6), T2 = (3.5, 2, ‘Hello‘)

Let us take a tuple: Forward index 0 1 2 3 4


T = (3, -2, 5, 0, 7) 3 -2 5 0 7
Indexing: -5 -4 -3 -2 -1 Forward index
Slicing:
T[0] gives 3
T[:] gives (3, -2, 5, 0, 7)
T[1] gives -2
T[2] gives 5 T[0:] gives (3, -2, 5, 0, 7) Updating: Does not work
T[3] gives 0 T[2:4] gives ( 5, 0) List[0] = 4 gives error
T[4] gives 7 T[0:5] gives (3, -2, 5, 0, 7) List[-1] = 'H' gives error
T[-1] gives 7 T[0:-1] gives (3, -2, 5, 0) List[1:3]=[-1, 4] gives error
T[-3] gives 5 T[2:] gives ( 0, 7)
Sequence Types: Tuple
Python Tuple Operations
The concatenation (+) and repetition (*) operator work in the same
way as they were working with the List

Consider two tuples: Iteration a list:


T1 = (1, 3, 4), T2 = (5, 2, 7) Tuple = ["John", "David", "James", "Jonathan"]

Concatenation (+): for i in Tuple:


T1 + T2 gives (1, 3, 4, 5, 2, 7) print(i)
Output:
John
Repetition (*): David
James
2*L2 gives (5, 2, 7, 5, 2, 7)
Jonathan
Sequence Types: Tuple
Python Tuple Built-in Functions

Functions Meaning
len(tuple) used to calculate the length of the tuple.
max(tuple) returns the maximum element of the tuple.
min(tuple) returns the minimum element of the tuple.
tuple(seq) converts any sequence to the tuple.

Example:
tuple = (3, 4.5, -2, 0, 1)

len(tuple) gives 5
max(tuple) gives 4.5

Do interactively
Dictionary and Set
Dictionary
Python Dictionary
 Dictionary is used to implement the key-value pair in python
 The dictionary is the data type in python which can simulate the real-life data
arrangement where some specific value exists for some particular key
 Dictionary is the collection of key-value pairs where the value can be any python
object whereas the keys are the immutable python object, i.e., Numbers, string
or tuple
Creating a Dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the
small brackets () and separated by the colon (:). The collections of the key-value
pairs are enclosed within the curly braces {}.
Syntax
Dict = {"Name": "Ayush","Age": 22}
In the dictionary Dict, the keys are Name, and Age which are the string that is an
immutable object. Corresponding Values are Ayush and 22

There are also dictionary function and methods


Set
Python Set
 An unordered collection of various items enclosed within the curly braces {}. The
elements of the set can not be duplicate. The elements of the python set must
be immutable
 Unlike other collections in python, there is no index attached to the elements of
the set, i.e., we cannot directly access any element of the set by the index.
However, we can print them all together or we can get the list of elements by
looping through the set.
Creating a Set
Created by enclosing the comma separated items with the curly braces {}. Python
also provides the set method which can be used to create the set by the passed
sequence.
Syntax
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

There are also set operations and methods


Python Functions
&
User-Defined Functions
Python Function
 A function is the organized block of reusable code which can be
called whenever required
 Python provide us various in-built functions like range() or print()
 The user can create its functions which can be called user-defined
functions
 By using functions, we can avoid rewriting same logic/code again
and again in a program

Use-defined function
Using def keyword to create the use-defined function
Syntax:
def my_function(input_1, input_2, …,input_n):
statements
return output_1, output_2, …,output_m
The function block is started with the colon (:) and all the same level block
statements remain at the same indentation
User-Defined Function
Examples:
def product(x,y): def sum_poduct(x,y):
p = x*y s=x+y
p = x*y
return p
return s,p
Calling the function: Calling the function:
product(2,3) result 6 sum_product(2,3) results (5, 6)

Problem1: Design a fucntion that finds the roots of the quadratic equation
𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0 (inputs of the function are a, b, c) and output is the roots

Problem2: Design a fucntion y = 𝑥 3 + 𝑠𝑖𝑛𝑥 that takes the input a list


3 𝜋 𝜋 3
x=[-2𝜋, − 𝜋, −𝜋, − , 0, , 𝜋, 𝜋, 2𝜋] and returns output y also a list. Also, plot the
2 2 2 2
graph of y versus x.
Python Lambda Function
 The anonymous function is declared by using lambda keyword.
 lambda function accept any number of arguments, but they can
return only one value in the form of expression.
Syntax:
lambda arguments : expression
Example1: Single argument
f = lambda x: x**2 - 3*x + 1 # It constructs the function 𝑓 𝑥 = 𝑥 2 − 3𝑥 + 1
Calling the Function:
x = 3.5
f(x)
Output: 2.75
Example1: Multiple argument
f = lambda x, y: x**2 + y**2 # It constructs the function 𝑓 𝑥, 𝑦 = 𝑥 2 + 𝑦 2
Calling the Function:
x = 3.5
y = 2.3
f(x,y) Output: 17.54
Python Lambda Function
lambda function with map
Example1:
x = [1, 0, -3, 4, 2, -1, 2]
y = list(map(lambda x : x**3 + x*3 - 1, x))
print(y)

Output:
[-3, -1, -19, 51, 1, 1, 1]

Problem1: Using lambda construct y = 𝑥 3 + 𝑥 − 𝑒 −𝑥 that takes the input a list


x=[0, 1, 2, ..., 20] and returns output y also a list. Also, plot the graph of y versus x.

Do interactively
Take Home Command
Memory Used by Python Objects
Syntax:
import sys
sys.getsizeof(object)

Examples
import sys
sys.getsizeof([1,2,3]) # List
sys.getsizeof((1,2,3)) # Tuple
sys.getsizeof(‘Hello’) # String
sys.getsizeof({1,2,3}) # set
Do interactively
End of Lecture-3

Lecture-4
NumPy
33

You might also like