You are on page 1of 29

NUMERICAL METHODS

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

Lecture-2
Outlines
 Basic data types

 Variables and variable assignments

 Operators

 Math functions

 Comments

 Print command
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
Basic Data Types
and
Sequences
Basic Data Types and Sequences
Numbers: Python has three types of numbers
 Integer: It does not have any fractional part
 Floating Point: It can store number with a fractional part
 Complex: It can store real and imaginary parts
Sequences: These are ordered collections of elements
and are three types
 String
 Tuples
 Lists
There are more two types:
Set: This is an un-ordered collection of elements
Dictonary: An unordered collection of data values, used to
store data values like a map. It holds key:value pair
Variables
Variables
 Variable: A named piece of memory that can store a
value

 Usage:
 Compute an expression's result
 store that result into a variable
 and use that variable later in the program

 Variables names are case sensitive and cannot start with


a number
 They can contain combination of letters, numbers, and
underscores
 Examples: temp Temp _Temp _1Temp Temp1
Temp_1
Reserved Words

Python reserved words are not allowed to use as a variable


name

Python reserved words:

and, assert, break, class, continue,


def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or,
pass, print, raise, return, try, while
Variable Assignments
 No variable declaration required
 Data type is declared automatically once
the value is assigned to the variable
>>> a = 5 >>> a = 5.0
>>> type(a) >>> type (a)
<class ‘int’> <class ‘float’>
>>> a = 3-2j >>> a = ‘Nepal’
>>> type(a) >>> type (a)
<class 'complex'> <class ‘str’>
Do interactively
Operators
Operators

Python provides following type of operators

 Arithmetic operators

 Assignment operators

 Logical operators

 Comparison operators
Arthematic Operators
Operators Meaning
+ Addition

- Substraction

* Multiplication

/ Division

** Power

% Modulo Example:
>>> 3+5*4-4/2+2**3
29.0
Assignment Operators
Operators Meaning
= a=4

+= a+=2 (a=a+2)

-= a-=2 (a=a-2)

*= a*=2 (a=a*2)

/= a/=2 (a=a/2)

**= a**=2 (a=a**2)

%= a%=2 (a=a%2)
Logical Operators
Operators Meaning
and True if both the operands are true

or True if one of the operand is true

not True if operand is false

In Python, the two Boolean values are True and False (the capitalization
must be exactly as shown)

Example 1 Example 2 Example 3


>>> x = True >>> x = True >>> x = True
>>> y = False >>> y = False >>> not x
>>> x and y >>> x or y
Comparison Operators
Operators Meaning
> Greater than
< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
Comparison operators are used to compare values. It returns
either True or False according to the condition

Example 1 Example 2 Example 3 Example 4 Example 6


>>> a = 3 >>> a = 3 >>> a = 3 >>> a = 3 >>> a = 3
>>> b = 2 >>> b = 3 >>> b = 3 >>> b = 3 >>> b = 2
>>> a>b >>> a<b >>> a==b >>> a>=b >>> a<=b
Other Special Operators
Operators Name Meaning
Bitwise: operators act on operands as if
&, |, ~,^,>>,<< Bitwise operators: they were strings of binary digits.
They operate bit by bit, hence the
name.
Used to check if two values (or
is, not is Identity operators variables) are located on the same
part of the memory
Used to test whether a value or
in, not in Membership operators variable is found in a sequence
(string, list, tuple, set and dictiona
ry)

Do interactively
Math Functions
Math Functions
The mathematical functions are accessible through
math module. This module has to be imported by
calling import math before the math functions are
used
𝜋 𝑥 3 +𝑡𝑎𝑛 − sinh 𝑥
𝐄𝐱𝐚𝐦𝐩𝐥𝐞: If 𝑥 = 3, 𝜃 = find the value of
3 ln 𝑥 − 𝑒 𝜃
import math
x = 3.0 To Search math
theta = math.pi/3.0 functions in math
num = x**3 + math.tan(theta)-math.sinh(math.sqrt(x)) module:
den = math.log(x)-math.exp(theta) import math
value = num/den help (math)
print('value =',value)

value = -14.845103784722442
Math Functions
List of math function in math module
Function Descripttion
ceil(x) Returns the smallest integer greater than or equal to x.
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
exp(x) Returns 𝑒 𝑥
log(x[, base]) Returns the logarithm of x to the base (defaults to e)
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
acos(x) Returns the inverse cosine of x
asin(x) Returns the inverse sine of x
atan(x) Returns the inverse tan of x
Math Functions
Continue…
Function Descripttion
cos(x) Returns the cosine of x
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
gamma(x) Returns the Gamma function at x
pi Mathematical constant 𝜋
e Mathematical constant 𝑒

Do interactively
Comments
Comments
 Comments are done for well documentation of the
source code ignored by the complier or interpreter
 Comments in Python begin with a hash mark (#) and
whitespace character and continue to the end of the
line

# Print “Hello, World!” to console


print("Hello, World!")

Python Comment using String


''' I am a
multi-line
comment!'''
print ("Hello World")

Do interactively
Print Function
Print
The print() function prints the given object to the
standard output device (screen)
Examples
print("Hello, world!")
age = 45
print("You have", 65 - age, "years until
retirement")

Output:
Hello, world!
You have 20 years until retirement
Print
Output formatting:
The % operator (modulo) can also be used for string formatting

Examples
import math
print('The approx. value of pi is %5.3f.' % math.pi)

Output:
The approx. value of pi is 3.142.

The general syntax for a format placeholder is

%[<flags>][<width>][.<precision>]<type>

Do interactively
Print
Output: Writing into a File
The general syntax:

file_object = open("filename", "mode")

Mode Description
'r' This is the default mode. It Opens file for reading
'w' This Mode Opens file for writing. If file does not exist, it
creates a new file. if file exists it ignore the existing file
'x' Creates a new file. If file already exists, the operation fails
'a' Open file in append mode. If file does not exist, it creates
a new file
'+' This will open a file for reading and writing (updating)
Print
Output: Writing data into a File example
Example
f = open("Calculated_Data.txt","w+")
for i in range(10):
x = i
y = x**2
f.write('%3d \t\t %3d \n'%(x,y))
f.close()

# load data file in python


import numpy as np
a = np.loadtxt('Calculated_Data.txt')

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

Examples
import sys
sys.getsizeof(3) # integer
sys.getsizeof(3.0) # float
sys.getsizeof(‘3’) # string
sys.getsizeof(‘3.0’) # string
Do interactively
End of Lecture-2

Lecture-3
Control Structure, Sequence,
User-Defined Function
29

You might also like