Python Scientific Programming - Complete Study Notes
Python Scientific Programming - Complete Study Notes
clear view
Why Python?
Reason Details
[Link] 1/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
Key Difference:
Mutable vs Immutable:
dict str
set tuple
s = "Python"
Indexing:
P y t h o n
0 1 2 3 4 5 ← Positive Index
[Link] 2/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
-6 -5 -4 -3 -2 -1 ← Negative Index
s = "Python"
print(s[-1]) # n (last character)
print(s[-2]) # o
print(s[-6]) # P (first character)
s = "Python"
print(s[0:3]) # Pyt (index 0,1,2)
print(s[2:]) # thon (from index 2 to end)
print(s[:4]) # Pyth (from start to index 3)
print(s[-4:-1]) # tho (using negative index)
print(s[::-1]) # nohtyP (reverse the string)
print(s[::2]) # Pto (every 2nd character)
s = "hello"
print([Link]()) # HELLO
print([Link]()) # hello
print(len(s)) # 5
print([Link]('l','r')) # herro
print("ell" in s) # True
print([Link]('l')) # ['he', '', 'o']
Comparison Operators:
== Equal to 5 == 5 → True
[Link] 3/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
Logical Operators:
Programs:
[Link] 4/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
Using import:
Programs:
import math
# 1. Area of triangle
base, height = 10, 12
area = 0.5 * base * height
print(area) # 60.0
# 2. Factorial of 6
print([Link](6)) # 720
[Link] 5/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# 5. Compute sinh(2)
x = 2
sinh_val = ([Link](x) - [Link](-x)) / 2
print(sinh_val) # matches [Link](2)
# 6. sin(87°)
print([Link]([Link](87))) # 0.9986
print(type(len)) # builtin_function_or_method
print(len("hello")) # 5
print(max([3,1,4])) # 4
Lifetime Created & destroyed with function call Exists throughout program
[Link] 6/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
n = 42
def func():
global n
n = 3 # modifies the global n
func()
print(n) # 3
7. Types of Errors
Three types of errors in Python:
1. Syntax Error Occurs when code violates language rules. Python cannot parse it.
2. Runtime Error (Exception) Occurs during execution. The program runs but crashes at that line.
3. Logic Error Program runs without error but gives wrong output.
Syntax:
try:
# risky code
except ExceptionName:
# what to do if error occurs
How it works:
Examples:
[Link] 8/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# Syntax
if condition:
# block 1
elif another_condition:
# block 2
else:
# block 3
Nested If:
[Link] 9/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
out = 0
return out
For Loop:
# Syntax
for variable in sequence:
# code block
# Example 1: Sum 1 to 3
n = 0
for i in range(1, 4):
n = n + i
print(n) # 6
[Link] 10/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
While Loop:
# Syntax
while condition:
# code block
Syntax:
Programs:
# 1. Square a number
square = lambda x: x**2
print(square(5)) # 25
print(check(7)) # Odd
# 4. Positive/Negative/Zero
sign = lambda x: "Positive" if x > 0 else ("Zero" if x == 0 else "Negative")
print(sign(-5)) # Negative
# 6. Convert to uppercase
upper = lambda s: [Link]()
print(upper("hello")) # HELLO
x, y = add_sub(5, 3) # Unpacking
print(x) # 8
print(y) # 2
[Link] 12/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
🔑 Rule: Number of variables on the left must match number of values in the tuple.
Syntax:
Examples:
# 1. Student or not
is_student = True
person = 'student' if is_student else 'not student'
print(person) # student
# 2. Adult or minor
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
# 3. Even or odd
n = 7
result = "Even" if n % 2 == 0 else "Odd"
print(result) # Odd
# 4. Maximum of two
a, b = 10, 20
maximum = a if a > b else b
print(maximum) # 20
# 5. Absolute value
x = -5
abs_val = x if x >= 0 else -x
print(abs_val) # 5
# 6. Pass or Fail
marks = 45
[Link] 13/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
🔵 1. STRINGS
Definition: An ordered, immutable sequence of characters.
s = "hello"
s = 'world'
s = """multi
line"""
Operations:
s = "Python"
# Indexing
print(s[0]) # P
print(s[-1]) # n
# Slicing
print(s[0:3]) # Pyt
print(s[::-1]) # nohtyP
# Methods
print([Link]()) # PYTHON
print([Link]()) # python
print(len(s)) # 6
print([Link]('P','J')) # Jython
print("Py" in s) # True
print([Link]('t')) # ['Py', 'hon']
# String formatting
name = "Ali"
print(f"Hello, {name}") # Hello, Ali
# Concatenation
[Link] 14/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# Repetition
print("ha" * 3) # hahaha
🟢 2. LISTS
Definition: An ordered, mutable sequence of elements. Can contain mixed types.
lst = [1, 2, 3, 4]
lst = ["apple", "banana", "cherry"]
lst = [1, "hello", 3.14, True] # mixed types
Operations:
# Adding elements
[Link](1, 2) # insert 2 at index 1
[Link](4) # add 4 at end
# Removing elements
[Link](8) # removes first occurrence of 8
[Link]() # removes last element
[Link](0) # removes element at index 0
# Sorting
[Link]() # ascending
[Link](reverse=True) # descending
print(sorted(lst)) # returns sorted copy
# Other operations
print(len(lst)) # length
print(2 in lst) # True/False
[Link]() # reverse in place
[Link] 15/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# List of squares
squares = [n*n for n in [1,2,3,4]]
print(squares) # [1,4,9,16]
🟡 3. TUPLES
Definition: An ordered, immutable sequence. Once created, cannot be changed.
t = (1, 2, 3)
t = ("One", 1)
t = (2, 3, 2, 3, 1) # duplicates allowed
Operations:
# Indexing
print(t[0]) # 10
print(t[-1]) # 50
# Slicing
print(t[1:4]) # (20, 30, 40)
# Tuple Unpacking
student = ("Ali", 18, 90)
name, age, marks = student
print(name, age, marks) # Ali 18 90
# Check membership
print(3 in (1, 2, 3, 4)) # True
print(max(t2)) # 20
print(min(t2)) # 5
print(len(t2)) # 4
🔴 4. SETS
Definition: An unordered collection of unique elements. No duplicates, no indexing.
s = {1, 2, 3}
s = set([1, 2, 2, 3]) # {1, 2, 3} — duplicates removed
Operations:
# Set operations
print(set_a.union(set_b)) # {1, 2, 3}
print(set_a.intersection(set_b)) # {2, 3}
print(set_a.difference(set_b)) # set()
# Add / Remove
s = {1, 2, 3}
[Link](4)
[Link](2)
print(s) # {1, 3, 4}
# Membership
print(3 in {1, 2, 3}) # True
[Link] 17/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
🟣 5. DICTIONARIES
Definition: An unordered collection of key-value pairs. Keys must be unique and immutable.
Operations:
# Loop through
for key, value in [Link]():
print(key, value)
[Link] 18/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
Indexed ✅ ✅ ❌ By key
Use Case General sequence Fixed data Unique items Key-value mapping
import math
# 1. Area of Triangle
def my_triangle(b, h):
return 0.5 * b * h
print(my_triangle(10, 5)) # 25.0
# 3. Sum of Squares
def my_square_sum(a, b):
return a**2 + b**2
print(my_square_sum(3, 4)) # 25
# 4. Celsius to Fahrenheit
def temperature(c):
return (9/5) * c + 32
[Link] 19/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
print(temperature(30)) # 86.0
# 5. Quadratic Roots
def my_n_roots(a, b, c):
D = b**2 - 4*a*c
if D > 0:
r1 = (-b + [Link](D)) / (2*a)
r2 = (-b - [Link](D)) / (2*a)
return 2, [r1, r2]
elif D == 0:
return 1, [-b/(2*a)]
else:
return -2, []
# 6. Greeting Function
def greeting(name, age):
return f"Hi, my name is {name} and I am {age} years old."
print(greeting("Sara", 20))
# 7. Split Function
def my_split_function(f, g, a, b, x):
if x <= a: return f(x)
elif x >= b: return g(x)
else: return 0
[Link] 20/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# 14. my_circ_calc
def my_circ_calc(r, calc):
if calc == 'area':
return [Link] * r**2
elif calc == 'circumference':
return 2 * [Link] * r
print(my_circ_calc(2.5, 'area')) # 19.63
print(my_circ_calc(3, 'circumference')) # 18.84
# 1. FACTORIAL
def factorial(n):
if n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive step
print(factorial(3)) # 6
print(factorial(6)) # 720
# 2. FIBONACCI (Recursive)
def fibonacci(n):
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
for i in range(1, 6):
print(fibonacci(i)) # 1 1 2 3 5
[Link] 21/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
c = a + b
a = b
b = c
return a
print(fib_iter(4)) # 5
import numpy as np
def greet():
print("Hello")
f = greet
f() # Hello
[Link] 22/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
return f(x) + 1
print(my_fun_plus_one([Link], [Link]/2)) # 2.0
print(my_fun_plus_one([Link], [Link]/2)) # 1.0
print(my_fun_plus_one([Link], 25)) # 6.0
print(my_fun_plus_one(lambda x: x+2, 2)) # 5.0
print(apply_function(square, 3)) # 9
print(apply_function(cube, 3)) # 27
print(apply(increment, 10)) # 11
print(apply(decrement, 10)) # 9
f = lambda x: x**2
g = lambda x: x + 10
print(my_split_function(f, g, 2, 5, 1)) # 1 (f(1)=1)
print(my_split_function(f, g, 2, 5, 6)) # 16 (g(6)=16)
print(my_split_function(f, g, 2, 5, 3)) # 0 (between a and b)
# is_odd
def is_odd(number):
if number % 2 == 0: return 'even'
else: return 'odd'
[Link] 23/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# Thermostat
def my_thermo_stat(temp, desired_temp):
if temp < desired_temp - 5: status = 'Heat'
elif temp > desired_temp + 5: status = 'AC'
else: status = 'off'
return status
print(my_thermo_stat(65, 75)) # Heat
print(my_thermo_stat(75, 65)) # AC
print(my_thermo_stat(65, 63)) # off
# Circle calculator
def my_circ_calc(r, calc):
if calc == 'area':
return 3.14159 * r**2
elif calc == 'circumference':
return 2 * 3.14159 * r
# List
fruits = ["apple","banana","cherry"]
for fruit in fruits:
print(fruit)
# Tuple
t = (10, 20, 30)
for item in t:
print(item)
# Dictionary
d = {"One":1, "Two":2, "Three":3}
for key, value in [Link]():
print(key, "→", value)
# With enumerate
for i, val in enumerate(fruits):
print(i, val) # 0 apple, 1 banana...
While Loop:
# Count down
n = 5
while n > 0:
print(n)
n -= 1
[Link] 24/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes
# List comprehension
squares = [i**2 for i in range(5)] # [0,1,4,9,16]
evens = [i for i in range(10) if i%2==0] # [0,2,4,6,8]
# Dictionary comprehension
sq_dict = {x: x*x for x in range(1,6)}
even_sq = {x: x*x for x in range(10) if x%2==0}
✅ This covers all Short Answer and Long Answer topics completely. Use this as your exam
preparation guide! 🎯
[Link] 25/25