0% found this document useful (0 votes)
5 views78 pages

01 Basics of Programming 2

The document provides an overview of programming basics using Python, including data types, operators, and functions. It also discusses the history of programming languages and recent trends in their usage. Additionally, it highlights the importance of naming conventions and variable scope in Python programming.

Uploaded by

iboromoon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views78 pages

01 Basics of Programming 2

The document provides an overview of programming basics using Python, including data types, operators, and functions. It also discusses the history of programming languages and recent trends in their usage. Additionally, it highlights the importance of naming conventions and variable scope in Python programming.

Uploaded by

iboromoon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

Numerical Analysis & Computer Programming

Part 1: Basics of Programming


With Python

P. Arumugam (आरुमुगम)

Department of Physics
[email protected]
Phone: 8979890366
History of programming languages
High performance computation (HPC)

2
Recent trends

3
https://www.tiobe.com/tiobe-index/

4
More Infographics
Most used programming languages among
developers worldwide as of 2023
0% 10% 20% 30% 40% 50% 60% 70%
JavaScript 63.61%
52.97%
Python 49.28%
48.66%
TypeScript 38.87%
32.37%
Java 30.55%
27.62%
C++ 22.42%
19.34%
PHP 18.58%
13.59%
Go 13.24%
13.05%
Kotlin 9.06%

Note(s): Worldwide; May 8, 2023 to May 19, 2023; 87,585


respondents; Software developers
Source(s): Stack Overflow; ID 793628

5
Famous companies that use python

6
Basic architecture

7
A 1-bit computer

8
9
A motherboard

10
Compiler vs Interpreter

11
Data types

• Integers: Integers are 32 bits long,–232 to 232 – 1.


• Long Integers: unlimited precision, limited by the memory
• Floating Point Numbers: Floating-point numbers are also known as double-
precision numbers and use 64 bits.
• Boolean: It can hold only one of two possible values: True or False.
• Complex Number: has a real and an imaginary component, both represented
by float types. 2+3j is a complex number.
• Strings: Sequences of Unicode characters.
• Lists: Ordered sequences of values.
• Tuples: Ordered, immutable sequences of values.
• Sets: Unordered collections of values.
• Dictionaries: Unordered collections of key-value pairs.

12
Naming rules

• You can use any names you want, as long as they follow these rules:
• Names must start with either a letter or an underscore character ( _ ).
• You can't use any of Python's reserved words or keywords.

These are words that have specific meanings to Python, such as if (which
begins an if statement).
• Names are case-sensitive. num is different from NUM and nUm.
• By convention, most Python programmers use lowercase for names that
stand for values. They use other rules for names that stand for functions and
classes
• It's a Good Idea to use meaningful names. If you name everything with a
single-letter, for example, you may have trouble remembering what the name
stands for later.

13
Continuation Lines

• A physical line is a line that you see in a program.


• A logical line is a single statement.
• The end of a physical line marks the end of most statements (No ;).
• When a statement is too long to fit on a single line, you can join two adjacent
physical lines into a logical line by ensuring that the first physical line has no
comment and ends with a backslash (\).
• Python also joins adjacent lines into one logical line if an open parenthesis ( ( ),
bracket ( [ ), or brace ( { ) is not closed.

14
Simple Text?

• Unicode is a standard that uses 16-bit characters to represent characters on


your computer. Unlike ASCII (American Standard Code for Information
Interchange), which consists of 8 bits, Unicode uses 16 bits and represents
characters by integer value denoted in base 16.
• A number does not include any punctuation and cannot begin with a leading
zero (0).
• Leading zeros are used for base 2, base 8, and base 16 numbers.
• For example, a number with a leading 0b or 0B is binary, base 2, and uses digits
0 and 1. Similarly, a number with a leading 0o is octal, base 8, and uses the
digits 0 to 7, and a number with a leading 0x or 0X is hexadecimal, base 16, and
uses the digits 0 through 9, plus a, A, b, B, c, C, d, D, e, E, f, and F.

15
Unary Operators

16
Arithmetic Operators

17
Relational Operators

18
Logical Operators

19
Bitwise Operators

20
Assignment Operators

21
Membership and Identity Operators

22
Operator precedence
16*2-2/4=?

PEMDAS
• P–
Parentheses.
• E–
Exponentiatio
n.
• M–
Multiplication.
• D b=0
a="y"; – Division.
• A or
a=="y" – Addition.
a=="s" and
b>=2• S –
Subtraction.
Ans: True

23
Associativity of Operators

• Associativity is the order in which an expression is evaluated that has multiple


operators of the same precedence. Almost all the operators have left-to-right
associativity.
• When two operators have the same precedence, associativity
helps to determine the order of operations.
• For example, multiplication and floor division have the same precedence. Hence,
if both of them are present in an expression, the left one is evaluated first.

# Left-right # Right-left associativity of


associativity **
# Output: 3 # Output: 512
print(5 * 2 // 3) print(2 ** 3 ** 2)

# Output: 0 # Output: 64
print(5 * (2 // 3)) print((2 ** 3) ** 2)

24
Non associative operators

• Some operators like assignment operators and comparison operators do not


have associativity in Python. There are separate rules for sequences of this kind
of operator and cannot be expressed as associativity.
• For example, x < y < z neither means (x < y) < z nor x < (y <
z).
x < y < z is equivalent to x < y and y < z, and is evaluated from left-
to-right.
• Furthermore, while chaining of assignments like x = y = z = 1 is perfectly
valid, x = y = z+= 2 will result in error.
# Non associativity x = y = z = 1
# Output: True
print((1<4)<2) # (Non-associative operators)
# SyntaxError: invalid syntax
# Output: False
print(1<4<2) x = y = z+= 2

25
Formatted print

>>> a=1+1/3.0 1.333333


>>> print("%d" % a) >>> print "%F" % a
1 1.333333
>>> print("%i" % a) >>> print "%g" % a
1 1.33333
>>> print("%u" % a) >>> print "%r" % a
1 1.3333333333333333
>>> print("%e" % a) >>> print "%s" % a
1.333333e+00 1.33333333333
>>> print("%E" % a)
1.333333E+00
>>> print "%f" % a

26
Version Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
Same as "e" if exponent is greater than -4 or less than precision, "f"
g otherwise.
Same as "E" if exponent is greater than -4 or less than precision, "F"
G otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.

27
Formatted print
Flag Meaning
# The value conversion will use the ``alternate form'' (where defined above).
0 The conversion will be zero padded for numeric values.
- The converted value is left adjusted (overrides the "0" conversion if both are given).
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

>>> print("%9.2f" % a) 1.33


>>> print("%9.2e" % a) 1.33e+00
>>> print("%+9.2f" % a) +1.33
>>> print("%-9.2f" % a) 1 . 3 3
>>> print("%09.2f" % a) 0 1 . 3 3

28
Formatted print

>>> print("%9.2f" % a) 1.33


>>> print("%9.2e" % a) 1.33e+00
>>> print("%+9.2f" % a) +1.33
>>> print("%-9.2f" % a) 1 . 3 3
>>> print("%09.2f" % a) 0 1 . 3 3
>>> print("%9.2g" % a)
1.3
>>> print("%9.2g" % 1e-5)
1e-05
>>> print("%9.2g" % 1e-4)
0.0001

29
Formatted print

>>> print("%9.2g %f" % (1e-4, 2))


0.0001 2.000000
>>> print("%d, two, %s" % (1,3))
1, two, 3

Keywords
and assert break class continue def del elif
else except exec finally for from global if
import in is lambda not

30
Using Escape Sequences

\a Bell (beep) print('Hello World\nIt\'s hot today')


print('Festival Discount\b\b\b\b\b\b\b\b\b
\b Backspace
Offer')
\f Form feed print("Isn't it?")
\n Newline print('Isn\'t it?')
\r Carriage return print("He said: \"I am going \"")
print('\\Text enclosed in back slashes\\')
\t Tab print ('Bell sound \a')
\v Vertical tab print('Name\tEmail Address\tContact Number')
\\ Literal backslash
\' Single quote Hello World
It's hot today
\" Double quote Festival Offerunt
Isn't it?
Isn't it?
He said: "I am going "
\Text enclosed in back slashes\
Bell sound
Name Email Address Contact Number
31
Miscellaneous features

Comments
# This program computes area of rectangle
a=2
b=3
a=b*c # values of b and c are multiplied
# and stored in a

Multiple Assignment Statements


a=b=c=1
p,q,r=10,20,30
sum, avg=p+q+r,(p+q+r)/3
del c
del a,b

32
Reading input from user

n = input('Enter a number: ') Enter a number: 10


print('You Entered:', n) You Entered: 10
print('Data type of n:',
Data type of num: <class
type(n))
print(n*2) '1010'
'str'>
n = int(input('Enter a number:
Enter a number: 10
'))
print('Data type of n:',
Data type of num: <class
type(n))
print(n*2) 'int'>
20
n = int(input('Enter a number:
Enter a number: 10.5
'))
ValueError: invalid literal for int() with base 10: '10.5'
n = float(input('Enter a number:
Enter a number: 10.5
'))
print('Data type of n:',
Data type of num: <class
type(n))
'float'>

33
Lists & Tuples

b=[2,9,4] # List variable


c=('apple', 'mango', 'banana') # tuple
variable

A tuple in python language refers to an ordered, immutable


(non-changeable) set of values of any data type.
numbers = [3,4,1,9,6,2,8]
print(numbers) [3, 4, 1, 9, 6, 2, 8]
numbers.insert(11,2)
print(numbers) [3, 4, 11, 1, 9, 6, 2, 8]

numbers = [3,4,1,9,6,2,8] [3, 4, 1, 9, 6, 2, 8]


print(numbers)
numbers.pop(4) [3, 4, 1, 9, 2, 8]
print(numbers)
34
Functions

SYNTAX:
def function-name(Parameter list):
statements, i.e. the function body

Example:
def fahrenheit(T_in_celsius):
return (T_in_celsius*9/5) + 32

t=float(input(“Enter t: ”))
print(t, ": ", fahrenheit(t))

The output of this script looks like this:


22.6 : 72.68
25.8 : 78.44

35
Functions: Optional Parameters

Example:
def Hello(name="everybody"):
print("Hello " + name + "!")

>>> Hello("Peter")
>>> Hello()

The output of this script looks like this:

Hello Peter!
Hello everybody!

36
Functions: Keyword Parameters

def sumsub(a, b, c=0, d=0):


return a - b + c - d

>>> print(sumsub(12,4))
8
>>> print(sumsub(42,15,d=10))
17
>>> print(sumsub(42,15,0,10))
17
>>> print(sumsub())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sumsub() takes at least 2 arguments (0
given)

37
Functions: Return values

def no_return(x,y): >>> res = no_return(4,5)


c = x + y >>> print(res)
None

def empty_return(x,y): >>> res =


c = x + y empty_return(4,5)
return >>> print(res)
None
def return_sum(x,y):
c = x + y >>> res = return_sum(4,5)
return c >>> print(res)
9
def avg(*x):
return sum(x)/len(x) >>> a=[1, 2, 3]
>>> avg(*a)
2 38
Functions: scope of variables
def fun1():
x=4
def fun2():
print x # from fun1's x = 5
scope def fun():
fun2() # Prints 4 print(x)
x=5 fun() # Prints 5
fun2() # Prints 5
x = 5
print x # Prints 5
def fun():
def fun1(): print(x)
x=4 x += 1 # makes x a local
def fun2(): variable!
x=6 fun() # UnboundLocalError!
print x # from fun2's
scope
fun2() # Prints 6
x=5
fun2() # Prints 6
print x # Prints 5
39
Functions: global
>>> myGlobal = 5 >>> myGlobal = 5

def func1(): def func1():


myGlobal = 42 global myGlobal
myGlobal = 42
def func2():
print myGlobal def func2():
>>> func1() print myGlobal
>>> func2() >>> func1()
5 >>> func2()
42

40
Python Scope resolution: LEGB Rule
def fun1():
These rules specific to variable names
x=4
 L, Local — Names assigned in any way within a def fun2():
function (def), and not declared global in that print x
bar() # Prints 4
function.
x=5
 E, Enclosing function locals — Name in the fun2() # Prints 5
print x # Prints
local scope of any and all enclosing functions
5
(def), from inner to outer.
 G, Global (module) — Names assigned at Built-in
the top-level of a module file, or declared Global
global in a def within the file. Enclosing
Local
 B, Built-in (Python) — Names
preassigned in the built-in names
module: open, range,...

41
Lists are mutable  editable in sub blocks
def f(t):
print(a,b) Changing an element in a mutable
a[1]=5 list defined in enclosing function
# b=b+8
c=[1,2,3] UnboundLocalError: local variable 'b'
return t**2 referenced before assignment
a=[1,2,3]
d=a NameError: name 'c' is not defined
b=2
t=f(5)
#c[1]=9 Referencing the same list !
#print(t,a,b,c) NOT creating a new list !!
print(t,a,b,d) Use d=a.copy() for creating

[1, 2, 3] 2
25 [1, 5, 3] 2 [1, 5, 3] Changing “a” changes “d”

42
Flow control in functions
Sequential Function Nested Function
def fun(x): def fun1(x1):
Start
def fun2(x2):

Start
y2=fun2(x2)
y=fun(x)

Line1
Line2 Start
Line3
def fun(x):
Line4 y1=fun1(x1)
return x**2
Line5
x=int(input("x")
)
y=fun(x)
print(y)
43
Flow control

Sequential Conditional Looping

Yes No
?
Yes ?
No

x=int(input("x") x=int(input("x")
Line1 )
)
Line2
Line3 Yes print(x) No Yes n = 1 No
Line4 while n < x:
if x > 5:
Line5
print("x > 5") print(n)

print("end") n += 1
print("end")
44
if – else statements

Yes No Yes No
? ?

x = int(input("x"))
x=int(input("x")
print(x)
) Yes No
if x > 5:
Yes print(x) No
print("x > 5")
if x > 5:
else:
print("x > 5")
print("x <= 5")
print("end")
print("end")

45
if – elif – else: Nesting

Yes No
?  A simple If-else construct

x = int(input("x"))
Yes No print(x)
? Yes
if x > 5: No

Yes No print("x > 5")


? Yes elif x < 5:
No

print("x < 5")


Else:
print("x = 5")
print("end")
46
Examples
x = int(input("x")) number = int(input("Number"))

if x < 0: # outer if statement


x = 0 if (number >= 0):
print('Changed to # inner if statement
zero') if number == 0:
elif x == 0: print('Number is 0')
print('Zero')
elif x == 1: # inner else statement
print('Single') else:
else: print('Number is
print('More') positive')
Exercises
• Quadratic Equation # outer else statement
• else:
Odd or even
print('Number is negative')
• Grades for marks
• Tut1 # Output: Number is positive

47
while loop
# program to calculate the sum of
numbers
# until the user enters zero
total = 0
number = int(input('Enter N: '))
Yes ? while number != 0:
No total += number
number = int(input('Enter next N:
'))
print('total =', total)
x = input("x")
If the condition of a loop is always True, the loop runs
n = 1 for infinite times (until the memory is full).
Yes No
while n < x: age = 32
print(n) # the test condition is always True
while age > 18:
n += 1 print('You can vote')
print("end")

48
while loop with else, break
counter = 0
Yes No
while counter < 3: Inside loop
print('Inside loop') Inside loop
counter = counter + 1 Inside loop
else: Inside else Yes ?
print('Inside else') End No
print('End')

The else block will not execute if the while loop is terminated by a break statement.

counter = 0
Yes while counter < 3: No
if counter == 1: Inside
break loop
End
No
Yes ?
print('Inside loop') ? No
counter = counter + 1 Yes
else:
print('Inside else')
print('End')

49
while loop with continue

No Yes ? No
?
?
No ? Yes
No
Yes
Yes
break continu
e

Continue: skips the current iteration and the control flow goes to the next iteration
num = 0
Yes while num < 10: No
1
num += 1
3
if (num % 2) ==
5
0:
7
continue
9
print(num)
print('End')
50
for loop

A for loop is used to iterate over sequences such as lists, tuples, string, etc.
while: Boolean n=[1,2,3]
for i in 1
expression
n: 2
for: part of sequence? 3
print(i)
Yes ? n=(1,2,3)
1
No for i in
n=[1,2,3] 2
1 n:
for i in n: 3
4 print(i)
print(i)
Yes for i in No n[1]=4 3
1 print(n) [1, 4,
[1,2,3]: 2 3]
print(i) 3
en n=(1,2,3) 1
print("end") d for i in n: 2
print(i) 3
for x in P n[1]=4 TypeError: 'tuple' object does
'PHY': H print(n) not support item assignment
Y
print(x)
51
for loop with break, continue, else

for i in [1,2,3,4]: for i in [1,2,3,4]: 1


if i==3: 1 if i==3:
2 2
break continue 4
print(i) End print(i) End
print('End') print('End')

No
for i in [1,2,3,4]: for i in [1,2,3,4]:
if i==3: if i==3:
1 1
break continue
2 2
print(i) print(i)
End 4
else: else:
else
print('else') print('else')
End
print('End') print('End')

for i in range(2): 0
print(i) 1
print('End') End

52
Nested for loops
for i in [1,2,3,4]:
if i==3:
break
for j in i= 1
  
[1,2,3,4]: j= 1
if j==i: i= 2
break End
print('j= ',j)
print('i= ',i)
print('End') Loops don’t cross and Break exits the inner loop
def fun(n):
for i in for i in [1,2]:
0 1 j=i in: 1 1 1
range(n):
0 2 for i in [1,2]: in: 2 1 2
for j in [1,2]:
1 1 k=i out: 2 1
1 2 2
if i==3: in: 1 2 1
2 1 print('in:',i,j,k)
return 3 in: 2 2 2
2 2 print('out:',i,j,k)
print(i,j) out: 2 2
End
a=fun(5) 2
print('End') print('End') End
53
range command
range(stop)
range(start, stop[, step])
• The arguments to the range constructor must be integers
• Contents of a range r are determined by r[i]=start+step*i where i>=0
• For a positive step r[i]<stop and for a negative step r[i]>stop .
• A range object will be empty if r[0] does not meet the value constraint.
• Ranges do support negative indices, but these are interpreted as indexing from
the end of the sequence determined by the positive indices.
>>> list(range(5, 10)) >>> r = range(0, 20, >>>
[5, 6, 7, 8, 9] 2) r.index(10)
5
>>> list(range(0, 10, 3)) >>> 11 in r
[0, 3, 6, 9] False >>> r[5]
10
>>> list(range(-1, -10, - >>> 10 in r
3)) True >>> r[-1]
[-1, -4, -7] 18
54
More on lists

a = [1,2,3]
print(len(a)) 3

a=[1, "banana",
<class 'list'>
True]
<class 'int'>
print(type(a))
<class 'str'>
for i in a:
<class 'bool'>
print(type(i))
print(a[1]) banana
print(a[-1]) True
print(a[:]) [1, 'banana',
print(a[0:1]) True]
print(a[:1]) [1]
print(a[1:]) [1]
print(a[-3:-1]) ['banana', True]
if "banana" in a: [1, 'banana']
print("success") success

55
More on lists (contd.)
a[1]=5; print(a) [1, 5, True]
a[0:2]=[3,4]; print(a) [3, 4, True]
a[0:1]=[7,8]; print(a) [7, 8, 4, True]
a.insert(1,9); print(a)
[7, 9, 8, 4, True]
a.pop(1); print(a)
[7, 8, 4, True]
a.append('PY’);
[7, 8, 4, True, 'PY']
print(a)
a.append([1,2]);
print(a) [7, 8, 4, True, 'PY', [1, 2]]
a.extend(a); print(a)
a.remove(7); print(a)
[7, 8, 4, True, 'PY', [1, 2], 7, 8, 4, True, 'PY', [1,
2]]
a.sort()
[8, 4, True, 'PY', [1, 2], 7, 8, 4, True,a.count()
'PY', [1,
a.reverse()
a.sort(reverse=Tru
2]] a[::-1] a.index()
e)
i= [n**2 for n in range(1,
Output: [1, 4, 9, 16,
6)]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
25]
newlist = [x for x in fruits if "a" in x];
print(newlist)
['apple', 'banana', 'mango']
56
More on lists (contd.)
fruits = ["apple", "banana",
"cherry"]
[green, yellow, red] = fruits apple banana
print(green,yellow,red) cherry
fruits = ["apple", "banana", "cherry", "strawberry"]
[green, yellow, *red] = fruits
apple banana ['cherry',
'strawberry']
Most of these operations (except those which change the values) are applicable for
tuples also. E.g. sort, append, etc., wont work with tuples
Multi-dimensional arrays are
thistuple = ("apple", "banana", "cherry") possible with lists/tuples. We
y = list(thistuple); y.append("orange") will use numpy arrays (to be
thistuple = tuple(y) defined later) for this purpose
>>> a=[[1,2],[3,4]] >>> a[1][0]
>>> a[0] 3
𝑎=
( 1
3
2
4 )
row index
[1, 2] >>> a[0][1]
>>> a[0][0] 2 ( 𝑎11
𝑎21
𝑎12
𝑎22 ) column index
1
57
Lists vs Tuples

# LIST TUPLE
1 Lists are mutable Tuples are immutable
The implication of iterations is Time- The implication of iterations is
2
consuming comparatively Faster
The list is better for performing A Tuple data type is appropriate for
3
operations, such as insertion and deletion. accessing the elements
Tuple consumes less memory as compared
4 Lists consume more memory
to the list
Tuple does not have many built-in
5 Lists have several built-in methods
methods.
Unexpected changes and errors are more
6 In a tuple, it is hard to take place.
likely to occur

58
Sets & Dictionaries

There are four ways to handle arrays

• List [] is a collection which is ordered and changeable. Allows duplicate members.


• Tuple () is a collection which is ordered and unchangeable. Allows duplicate members.
• Set {} is a collection which is unordered, and unindexed.
 Unchangeable, but you can remove items and add new items.
 No duplicate members.
 .difference, .intersection, .union, etc.,.
• Dictionary is a collection which is ordered and changeable.
 {key1:value1, key2:value2, …}
 No duplicate members.
 Only since v 3.7, dictionaries are ordered
 .get, .items, .keys, .values, etc.

59
match-case
def fundamental_interaction(interaction):
match interaction:
case "Gravitational":
return "Described by Newton's Law of Universal
Gravitation.“
case "Electromagnetic":
return "Described by Maxwell's equations.“
case "Weak Nuclear":
return "Involved in processes like beta decay."
case "Strong Nuclear":
return "Described by Quantum Chromodynamics (QCD)."
case _:
return "Unknown or not a fundamental interaction."

interaction = "Gravitational"
result = fundamental_interaction(interaction)
print(interaction, "Interaction: ", result)
The special pattern _ (and called wildcard) always matches but it doesn’t bind any variables.

60
match-case: def with additional inputs
def calculate_force(interaction_type, quantity1, quantity2, distance):
G = 6.67430e-11 # Gravitational constant in m^3/kg/s^2
k = 8.9875e9 # Coulomb's constant in Nm^2/C^2

match interaction_type:
case "Gravitational":
return (G * quantity1 * quantity2) / (distance ** 2)
case "Electromagnetic":
return (k * abs(quantity1 * quantity2)) / (distance ** 2)
case "Weak Nuclear":
# Custom calculation for weak nuclear force (illustrative)
return quantity1 * quantity2 / distance
case "Strong Nuclear":
# Custom calculation for strong nuclear force (illustrative)
return quantity1 * quantity2 / (distance ** 2)
case _:
return "Unknown interaction type"

interaction = "Gravitational"
quantity1 = 5.972e24
quantity2 = 7.347e22
distance = 384400e3
force = calculate_force(interaction, quantity1, quantity2, distance)
print(interaction, "Interaction Force: ", force, " N")
61
match-case: multiple variables
# point is an (x, y) tuple
match point:
case (0, 0): if x < 0:
print("Origin") raise Exception("only +ve
case (0, y): ")
print(f"Y={y}") if not type(x) is int:
case (x, 0): raise TypeError("Only
print(f"X={x}") integers")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a
point")
-----------------------------------------------
----
ValueError Traceback (most recent call
last)
<ipython-input-4-0e299d68a836> in <module>
5 case _:
----> 6 raise ValueError("Not a point")
7 62
Lambda (inline function)

Python supports the creation of anonymous functions (i.e. functions that are
not bound to a name) at runtime, using a construct called "lambda".

>>> def f (x): return x**2


...
>>> print f(8)
64
>>> ke= lambda m,v: 0.5*m*v**2
>>> g = lambda x: x**2
>>> m = 5.0 # Mass of the object in kg
>>> print g(8) v = 10.0 # Velocity of the object in
m/s
64
print(f"KE = {ke(m,v):.2f} joules.")
>>> g=lambda x,y: x+y
>>> g(2,3)
5

63
Reading Files
file1
• open(filename, mode)
this is line 1
>>> f = open('file1', ‘r')
this is line 2
>>> f=open('file1') this is line 3
>>> f.read()
'this is line 1\nthis is line 2\nthis is line 3\n'
>>> f.read()
''
>>> f.seek(0)
>>> f.read()
'this is line 1\nthis is line 2\nthis is line 3\n'
>>> f.seek(1)
>>> f.read()
'his is line 1\nthis is line 2\nthis is line 3\n'

64
Reading Files

>>> f.readline() file1 >>> f.seek(0)


'this is line 1\n' >>> for line in
this is line 1
f:
>>> f.readline() this is line 2
... print(line)
'this is line 2\n' this is line 3
...
>>> f.readline() this is line 1
'this is line 3\n'
this is line 2
>>> f.readline()
'' this is line 3
>>> f.seek(0)
>>> f.readlines()
['this is line 1\n', 'this is line 2\n', 'this is line
3\n']

>>> f.close()

65
Various modes for opening files

open(filename, mode)

mode Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)

66
Writing files

>>> f2=open('file2','w') [aru@bose]$ cat


>>> f2.write('This is a test \n') file2
This is a test
>>> f2.close()
>>> f1=open('file2')
>>> f1.read() [aru@bose]$ cat file2
'This is a test \n‘ 1.33
The value 1.33 is same as
1.3333
>>> f2=open('file2','w')
>>> f2.write("%9.2f \n" % a)
>>> f2.write("The value %9.2f is same as %9.4f \n" %
(a,a)) [aru@bose]$ cat file2
>>> f2.close() 1.33
The value 1.33 is same as
1.3333
>>> f2=open('file2','a') A new line
>>> f2.write("A new line \n")
>>> f2.close() 67
Binary files
with open('binary_file.bin', 'rb') as file:
binary_data = file.read()

with open('new_binary_file.bin', 'wb') as file:


file.write(binary_data)

• Using the with statement is a good practice because it automatically closes the file
when you're done with it, even if an error occurs within the block.

with open('image.jpg', 'rb') as image_file:


image_data = image_file.read()
with open('copy_image.jpg', 'wb') as copy_file:
copy_file.write(image_data)
print("Image copied successfully!")

• Better suited for storing and working with non-textual data, where preserving the binary
structure of the data is essential.
• Text files are designed for human-readable text and may not handle binary data correctly.

68
Writing & reading floating point data
import numpy as np
numbers = np.array([3, np.pi, 1/3, 12345.678534321231321239])
with open('text1.txt', 'w') as tfile1:
tfile1.writelines(("%12.8f \n" % number) for number in
numbers)
with open('text2.txt', 'w') as tfile2:
tfile2.writelines(f"{number}\n" for number in numbers)
with open('bin.npy', 'wb') as bfile:
np.save(bfile, numbers)
with open('text1.txt', 'r') as tfile1:
tn1 = [float(line.strip()) for line in tfile1]
with open('text2.txt', 'r') as tfile2:
tn2 = [float(line.strip()) for line in tfile2]
bn = np.load('bin.npy')
print("Text file1:", tn1-numbers) • Binary files can preserve precision
print("Text file2:", tn2-numbers) and require less storage space.
print("Binary file:", bn-numbers)
Text file1: [ 0.00000000e+00 -3.58979291e-09 -3.33333333e-09 -
1.22963684e-09]
Text file2: [0. 0. 0. 0.]
Binary file: [0. 0. 0. 0.]
69
Some exceptions/options in Python
>>> import numpy as np
>>> a=b=c=1
>>> a=np.arange(3)
>>> a,b,c=1,2,3
>>> a*3
>>> a
array([0, 3, 6])
1
>>> b=[1]
>>> b
>>> b*3
2
[1, 1, 1]
>>> c
>>> np.array(b)*3
3
array([3])
>>> a,b,c=range(1,4)
>>> a
>>> [1]*3
array([0, 1, 2])
[1, 1, 1]
>>> np.dot(a,a)
5
>>> [[0,0],[0,0]]*3
>>> a = [[1, 0], [0,
[[0, 0], [0, 0], [0, 0], [0, 0],
1]]
[0, 0], [0, 0]]
>>> b = [[4, 1], [2,
2]]
>>> np.dot(a, b)
array([[4, 1], 70
Numpy arrays: some notes
>>> a=np.arange(3*2)
>>> np.mat(b)
>>> a.reshape(2,3)
matrix([[0, 1],
array([[0, 1, 2],
[2, 3]])
[3, 4, 5]])
>>> c=np.mat(b)
>>> a=np.arange(4)
>>> c*c
>>> b=a.reshape(2,2)
matrix([[ 2, 3],
>>> b
[ 6, 11]])
array([[0, 1],
[2, 3]])
>>> np.sqrt(c)
>>> b*b
matrix([[ 0. , 1.
array([[0, 1],
],
[4, 9]])
[ 1.41421356,
1.73205081]])
>>> np.dot(b,b)
array([[ 2, 3],
[ 6, 11]])
>>> np.linalg.inv(c)
matrix([[-1.5, 0.5],
[ 1. , 0. ]])
71
Factorials in a loop: global list is efficient
import time 𝑁 2𝑛 start_time = time.time()
𝑛 𝑥
num_terms=8 cos 𝑥=
0
( − 1)∑ ( 2 𝑛) !
cosine_approx1 = 0
flops1 = 0
𝑛=0
x = 0.5 for n in range(num_terms):
def fact1(n): factv,factf=fact1(2*n)
if n == 0: term = ((-1)**n)*(x**(2*n))/factv
return 1, 0 cosine_approx1 += term
result = 1; flops = 0 flops1 += factf+5
for i in range(1,n+1): end_time = time.time()
result *= i time_taken1 = end_time - start_time
flops += 1
return result, flops start_time = time.time()
flops2=fact2(2*num_terms)
def fact2(n): cosine_approx2 = 0
global gfact; gfact=[1] for n in range(num_terms):
flops = 0
for i in range(1, n + 1): term=((-1)**n)*(x**(2*n))/gfact[2*n]
gfact.append(gfact[i- cosine_approx2 += term
1]*i) flops2 += 6
flops += 1 end_time = time.time()
return flops time_taken2 = end_time - start_time
Time, FLOPs & cosine for Approach 1: 0.000998 seconds, 6720, 0.877583
Time, FLOPs & cosine for Approach 2: 0.000000 seconds, 640, 0.877583

http://10.14.0.51/~aru/ph643/fac_cosine.py 72
Numerical Recipes in C: The Art of Scientific
Computing (1986, Cambridge Univ.)
William T. Vetterling, Brian P. Flannery, William
H. Press, Saul Teukolsky
73
Plots with matplotlib.pyplot
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()

import matplotlib.pyplot as plt


plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

To plot x versus y,
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

74
Formatting plots

import matplotlib.pyplot as plt


plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals


t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles


plt.plot(t,t, 'r--',t, t**2, 'bs',t, t**3,'g^')
plt.show()

75
Working with text
import numpy as np
import matplotlib.pyplot as pl
from matplotlib import rc
rc('text',usetex=True)
x=np.arange(0,11,0.1)
y=x**2

pl.plot(x,y)
pl.xlim(0,10)
pl.title('A Parabola')
pl.xlabel(r'$x$')
pl.ylabel(r'$\psi_n(x)$')
pl.show()

pl.grid(True)
pl.ylabel(r'$\psi_n(x)
$’,fontsize=24,color=‘red’) 76
Working with multiple figures and axes
import numpy as np
import matplotlib.pyplot as plt

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)


t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
The subplot call specifies
plt.subplot(211) numrows, numcols,
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plot_number where
plot_number ranges from
1 to numrows*numcols.
plt.subplot(212) The commas in the subplot call are
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')optional if numrows*numcols<10.
plt.show() subplot(211) is identical
to subplot(2, 1, 1)
77
Other options in a plot

plt.text(60, .025, r'$\mu=100,\ \sigma=15$')

plt.yscale('linear')
plt.yscale('log')

https://matplotlib.org/stable/tutorials/index.html

78

You might also like