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

Python Scientific Programming - Complete Study Notes

The document provides comprehensive study notes on Python scientific programming, covering topics such as scientific programming definitions, data types, string manipulation, logical expressions, and error handling. It explains the use of built-in and user-defined functions, control structures like loops and conditionals, and the importance of libraries like NumPy and Matplotlib. Additionally, it includes examples and explanations of key programming concepts and syntax in Python.

Uploaded by

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

Python Scientific Programming - Complete Study Notes

The document provides comprehensive study notes on Python scientific programming, covering topics such as scientific programming definitions, data types, string manipulation, logical expressions, and error handling. It explains the use of built-in and user-defined functions, control structures like loops and conditionals, and the importance of libraries like NumPy and Matplotlib. Additionally, it includes examples and explanations of key programming concepts and syntax in Python.

Uploaded by

insiyanura00
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

Python Scientific Programming — Complete Study


Notes

clear view

📝 SHORT ANSWER QUESTIONS

1. What is Scientific Programming? Why is Python the Most Popular Choice?


Scientific Programming is the use of programming languages to solve scientific and mathematical
problems — including data analysis, simulations, numerical computation, visualization, and algorithm
design.

Why Python?

Reason Details

Simple Syntax Reads almost like English, easy to learn

Rich Libraries NumPy, SciPy, Matplotlib, Pandas, SymPy

Open Source & Free No licensing cost

Interpreted Run code line by line, great for experimentation

Community Support Huge community, abundant tutorials

Versatile Used in AI, ML, data science, web, automation

Jupyter Notebooks Interactive environment perfect for science

2. Basic Data Types vs Sequential Data Types | Mutable & Immutable


Basic (Scalar) Data Types:

Type Example Description

int 5 Whole numbers

[Link] 1/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

Type Example Description

float 3.14 Decimal numbers

bool True/False Logical values

complex 3+4j Complex numbers

Sequential Data Types:

Type Example Description

str "hello" Sequence of characters

list [1, 2, 3] Ordered, mutable sequence

tuple (1, 2, 3) Ordered, immutable sequence

Key Difference:

Basic types store a single value


Sequential types store multiple values in order, support indexing, slicing, and iteration

Mutable vs Immutable:

Mutable (can change) Immutable (cannot change)

list int, float, bool, complex

dict str

set tuple

3. What is a String? String Slicing & Negative Indexing


A string is a sequence of characters enclosed in single ' ' or double " " quotes.

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

Negative Indexing — counts from the end of the string:

s = "Python"
print(s[-1]) # n (last character)
print(s[-2]) # o
print(s[-6]) # P (first character)

String Slicing — Syntax: s[start : stop : step]

Returns characters from start up to (but not including) stop .

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)

Common String Operations:

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']

4. Logical Expressions, Logical Operators & Comparison Operators


A logical expression is an expression that evaluates to either True or False .

Comparison Operators:

Operator Meaning Example

== Equal to 5 == 5 → True

!= Not equal 5 != 3 → True

[Link] 3/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

Operator Meaning Example

> Greater than 7 > 3 → True

< Less than 2 < 5 → True

>= Greater or equal 5 >= 5 → True

<= Less or equal 3 <= 4 → True

Logical Operators:

Operator Meaning Example

and Both must be True True and False → False

or At least one True True or False → True

not Reverses the value not True → False

Programs:

# Program 1: Basic logical operations


P = True
Q = False
print(P and Q) # False
print(P or Q) # True
print(not P) # False

# Program 2: Law of Noncontradiction


# P AND (NOT P) is always False
P = True
print(P and (not P)) # False
P = False
print(P and (not P)) # False

# Program 3: De Morgan's Law


# NOT(P OR Q) == (NOT P) AND (NOT Q)
P, Q = True, False
print(not(P or Q) == (not P and not Q)) # True
print(not(P and Q) == (not P or not Q)) # True

# Program 4: Combined comparison


a, b = 10, 25
print((a < b) and (a == b)) # False (True AND False)
print((a < b) or (a == b)) # True (True OR False)

[Link] 4/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

5. import Keyword, Packages, Modules, Functions & Math Package


Definitions:

Package: A folder/directory containing multiple modules (e.g., numpy, math)


Module: A single .py file containing functions and variables (e.g., math)
Function: A block of code that performs a task (e.g., [Link]() )

Using import:

import math # import full module


import math as m # import with alias
from math import sqrt # import specific function
from math import * # import everything (not recommended)

Math Package — Key Functions:

Function Purpose Example

[Link](x) Square root [Link](25) → 5.0

[Link](x) Sine (radians) [Link]([Link]/2) → 1.0

[Link](x) Cosine [Link](0) → 1.0

[Link] Value of π 3.14159...

[Link](x) e^x [Link](1) → 2.718

[Link](x) Natural log [Link](math.e) → 1.0

[Link](n) n! [Link](6) → 720

[Link](x) Degrees → Radians [Link](90) → π/2

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

# 3. Distance between (3,4) and (5,9)


d = [Link]((5-3)**2 + (9-4)**2)
print(d) # 5.385

# 4. Verify sin²x + cos²x = 1


x = [Link] / 4
print([Link](x)**2 + [Link](x)**2) # 1.0

# 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

6. Built-in vs User-Defined Functions | Local vs Global Variables


Built-in Functions: Pre-defined in Python, always available — len() , type() , sum() , max() , min() ,
range() , print() , input() .

print(type(len)) # builtin_function_or_method
print(len("hello")) # 5
print(max([3,1,4])) # 4

User-Defined Functions: Defined using def .

def my_adder(a, b, c):


"""Adds three numbers"""
out = a + b + c
return out
print(my_adder(1, 2, 3)) # 6

Local vs Global Variables:

Local Variable Global Variable

Defined Inside a function Outside all functions

Scope Only inside that function Everywhere in the program

Lifetime Created & destroyed with function call Exists throughout program

[Link] 6/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

def my_adder(a, b, c):


out = a + b + c # 'out' is LOCAL
print(f"Inside: {out}") # 6
return out

out = 1 # 'out' is GLOBAL


d = my_adder(1, 2, 3)
print(f"Outside: {out}") # Still 1 — not affected!

Using global keyword to modify global variable:

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.

1 = x # SyntaxError: can't assign to literal


if True # SyntaxError: invalid syntax (missing colon)
(1] # SyntaxError: invalid syntax

2. Runtime Error (Exception) Occurs during execution. The program runs but crashes at that line.

1/0 # ZeroDivisionError: division by zero


x = [2]
x + 2 # TypeError: can only concatenate list to list
print(a) # NameError: name 'a' is not defined
[Link](2) # AttributeError: module has no attribute 'sni'

3. Logic Error Program runs without error but gives wrong output.

# Wrong factorial (initialized to 0 instead of 1)


def my_bad_factorial(n):
out = 0 # ← Bug! Should be 1
[Link] 7/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

for i in range(1, n+1):


out = out * i
return out
print(my_bad_factorial(4)) # Output: 0 (WRONG! Should be 24)

8. Try/Except — Concept & Examples


A Try-Except block lets the program handle errors gracefully instead of crashing.

Syntax:

try:
# risky code
except ExceptionName:
# what to do if error occurs

How it works:

Python tries to run the try block


If no error → except block is skipped
If error occurs → jumps to matching except block
If exception doesn't match → error propagates up

Examples:

# Example 1: Catch TypeError


x = '6'
try:
if x > 3:
print('X is larger than 3')
except TypeError:
print("Oops! x was not a valid number.")
# Output: Oops! x was not a valid number.

# Example 2: Multiple except blocks


def test_exceptions(x):
try:
x = int(x)
if x > 3:
print(x)
except TypeError:
print("Oops! x was not a valid number.")
except ValueError:

[Link] 8/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

print("Oops! Cannot convert x to integer.")


except:
print("Unexpected error")

test_exceptions([1, 2]) # TypeError


test_exceptions('s') # ValueError

# Example 3: Raising custom exception


x = 10
if x > 5:
raise Exception('x should be less than or equal to 5')

9. For Loop, If-Else, Nested If, While Loop


If-Else:

# Syntax
if condition:
# block 1
elif another_condition:
# block 2
else:
# block 3

# Example: is_odd function


def is_odd(number):
if number % 2 == 0:
return 'even'
else:
return 'odd'
print(is_odd(11)) # odd

Nested If:

def my_nested_branching(x, y):


if x > 2:
if y < 2:
out = x + y
else:
out = x - y
else:
if y > 2:
out = x * y
else:

[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

# Example 2: Loop through string


for c in "banana":
print(c) # b a n a n a

# Example 3: Loop through list


a = [2, 3, 1, 3, 3]
s = 0
for i in a:
s += i
print(s) # 12

# Example 4: Loop through dictionary


d = {"One":1, "Two":2, "Three":3}
for key in [Link]():
print(key, d[key])

# Example 5: Nested for loop (sum of 2D array)


x = [[5,6],[7,8]]
s = 0
for row in x:
for val in row:
s += val
print(s) # 26

break and continue:

# break: stop loop early


for c in 'only4you':
if [Link]():
break # stops when digit found

[Link] 10/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

# continue: skip current iteration


for i in range(5):
if i == 2:
continue # skips printing 2
print(i) # 0 1 3 4

While Loop:

# Syntax
while condition:
# code block

# Example: How many times can 8 be divided by 2?


i = 0
n = 8
while n >= 1:
n /= 2
i += 1
print(f"n={n}, i={i}") # n=0.5, i=4

💡 Use for-loop when number of iterations is known; use while-loop when it is


unknown/conditional.

10. Lambda Functions — Syntax & Programs


A lambda is a small, anonymous, single-expression function.

Syntax:

lambda arguments : expression

Programs:

# 1. Square a number
square = lambda x: x**2
print(square(5)) # 25

# 2. Add two numbers


add = lambda x, y: x + y
print(add(3, 4)) # 7

# 3. Check even or odd


check = lambda x: "Even" if x % 2 == 0 else "Odd"
[Link] 11/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

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

# 5. Maximum of two numbers


maximum = lambda a, b: a if a > b else b
print(maximum(10, 20)) # 20

# 6. Convert to uppercase
upper = lambda s: [Link]()
print(upper("hello")) # HELLO

# 7. Sort tuples by 2nd element


data = [(1,2),(2,0),(4,1)]
print(sorted(data, key=lambda x: x[1])) # [(2,0),(4,1),(1,2)]

# 8. map() — double every element


nums = [1,2,3,4]
print(list(map(lambda x: x*2, nums))) # [2,4,6,8]

# 9. filter() — keep even numbers


nums = [1,2,3,4,5]
print(list(filter(lambda x: x%2==0, nums))) # [2,4]

11. Tuple Unpacking — Concept & Example


Tuple unpacking means assigning multiple return values (or tuple elements) directly to separate
variables in one line.

# Example 1 — Function returning multiple values


def add_sub(a, b):
return a + b, a - b # returns a tuple (8, 2)

x, y = add_sub(5, 3) # Unpacking
print(x) # 8
print(y) # 2

# Example 2 — Unpacking a tuple variable


student = ("Ali", 18, 90)
name, age, marks = student
print("Name:", name) # Ali
print("Age:", age) # 18
print("Marks:", marks) # 90

[Link] 12/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

# Example 3 — Swapping variables


a, b = 5, 10
a, b = b, a # swap using tuple unpacking
print(a, b) # 10 5

🔑 Rule: Number of variables on the left must match number of values in the tuple.

12. Ternary Operator — Syntax & Examples


A ternary operator is a one-line conditional expression.

Syntax:

value_if_true if condition else value_if_false

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

grade = "Pass" if marks >= 50 else "Fail"


print(grade) # Fail

📖 LONG ANSWER QUESTIONS

L1. Lists, Tuples, Sets, Dictionaries & Strings

🔵 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

print("Hello" + " " + "World") # Hello World

# 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:

lst = [1, 8, 9, 15]

# Indexing & Slicing


print(lst[0]) # 1
print(lst[-1]) # 15
print(lst[1:3]) # [8, 9]

# 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

# Convert string to list


s = "Python is great!"
print([Link]()) # ['Python', 'is', 'great!']

[Link] 15/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

# Find even numbers in list


numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 == 0:
print(n) # 2, 4, 6

# Multiply all elements


result = 1
for n in [1,2,3,4]:
result *= n
print(result) # 24

# 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:

t = (10, 20, 30, 40, 50)

# 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

# Max, Min, Length


t2 = (5, 10, 15, 20)
[Link] 16/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

print(max(t2)) # 20
print(min(t2)) # 5
print(len(t2)) # 4

# Convert to set (remove duplicates)


t3 = (2, 3, 2, 3, 1, 2, 5)
print(set(t3)) # {1, 2, 3, 5}

# Looping through tuple


for item in t2:
print(item)

🔴 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_a = {2, 3, 2} # {2, 3}


set_b = {1, 2, 3}

# 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()

# Remove duplicates from tuple


t = (2, 3, 2, 3, 1, 2, 5)
print(set(t)) # {1, 2, 3, 5}

# 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.

d = {"name": "Ali", "age": 18}


d = dict(name="Ali", age=18)

Operations:

d = {"A": "a", "B": "b", "C": "c"}

# Access value by key


print(d["A"]) # a

# Check if key exists


print("B" in d) # True

# Get all keys and values


print([Link]()) # dict_keys(['A','B','C'])
print([Link]()) # dict_values(['a','b','c'])
print([Link]()) # dict_items([...])

# Add / Update / Delete


d["D"] = "d"
d["A"] = "updated"
del d["B"]

# Loop through
for key, value in [Link]():
print(key, value)

# Count character frequency


text = "hello"
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq) # {'h':1, 'e':1, 'l':2, 'o':1}

# Create from two lists


names = ["Ali", "Sara", "John"]
marks = [80, 90, 85]
student = dict(zip(names, marks))
print(student) # {'Ali':80, 'Sara':90, 'John':85}

[Link] 18/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

# Sum of all values


marks = {"Math":80, "Science":90, "English":85}
print(sum([Link]())) # 255

📊 Differences Between All 4 Data Types

Feature List Tuple Set Dictionary

Ordered ✅ ✅ ❌ ❌ (Python 3.7+ insertion order)


Mutable ✅ ❌ ✅ ✅
Duplicates ✅ ✅ ❌ Keys: ❌, Values: ✅

Indexed ✅ ✅ ❌ By key

Syntax [1,2] (1,2) {1,2} {k:v}

Use Case General sequence Fixed data Unique items Key-value mapping

L2. Practice Programs

import math

# 1. Area of Triangle
def my_triangle(b, h):
return 0.5 * b * h
print(my_triangle(10, 5)) # 25.0

# 2. Cylinder Surface Area & Volume


def my_cylinder(r, h):
s = 2 * [Link] * r**2 + 2 * [Link] * r * h
v = [Link] * r**2 * h
return [s, v]
print(my_cylinder(3.0, 5.0)) # [150.79, 141.37]

# 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

# 8. Sort by string length


names = ["Rahul", "Amit", "Priya", "Jo"]
print(sorted(names, key=lambda x: len(x))) # ['Jo','Amit','Rahul','Priya']

# 9. Sort dictionary by values


marks = {"Sara":85, "Ali":92, "John":78}
print(sorted([Link](), key=lambda x: x[1]))

# 10. Leap year check


year = 2024
if (year%4==0 and year%100!=0) or year%400==0:
print("Leap Year")

# 11. Count leap years 1500–2010


count = 0
for year in range(1500, 2011):
if (year%4==0 and year%100!=0) or year%400==0:
count += 1
print(count) # 124

# 12. Distance between two points


def my_dist_2_points(xy_points, xy):
d = []
for p in xy_points:

[Link] 20/25
3/27/26, 10:59 PM Python Scientific Programming — Complete Study Notes

dist = [Link]((p[0]-xy[0])**2 + (p[1]-xy[1])**2)


[Link](dist)
return d
print(my_dist_2_points([[3,2],[2,3],[2,2]], [1,2])) # [2.0, 1.41, 1.0]

# 13. Check if string has digits


def have_digits(s):
for c in s:
if [Link]():
return 1
return 0
print(have_digits('only4you')) # 1

# 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

L3. Recursive Functions — All Programs


A recursive function calls itself with a smaller version of the problem until it reaches the base case.

# 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

# 3. FIBONACCI (Iterative — faster)


def fib_iter(n):
a = 1; b = 1
for i in range(n):

[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

# 4. GCD (Greatest Common Divisor)


def my_gcd(a, b):
if b == 0: # Base case
return a
return my_gcd(b, a % b) # Recursive step
print(my_gcd(48, 18)) # 6

# 5. CHEBYSHEV POLYNOMIAL (1st kind)


def my_chebyshev_poly1(n, x):
def T(n, x_val):
if n == 0: return 1
elif n == 1: return x_val
else: return 2 * x_val * T(n-1, x_val) - T(n-2, x_val)
return [T(n, val) for val in x]
print(my_chebyshev_poly1(3, [0, 1, 2])) # [0, 1, 26]

# 6. SUM OF LIST (Recursive)


def my_sum(lst, i=0):
if i == len(lst): # Base case
return 0
return lst[i] + my_sum(lst, i+1)
print(my_sum([1, 2, 3, 4])) # 10

L4. Functions as Arguments to Functions — All Programs


In Python, functions are first-class objects — they can be passed as arguments to other functions.

import numpy as np

# 1. Assign function to a variable


f = max
print(f([2, 3, 5])) # 5

def greet():
print("Hello")
f = greet
f() # Hello

# 2. Function passed as argument — f(x)+1


def my_fun_plus_one(f, x):

[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

# 3. apply_function — square and cube


def apply_function(f, x):
return f(x)

def square(x): return x * x


def cube(x): return x * x * x

print(apply_function(square, 3)) # 9
print(apply_function(cube, 3)) # 27

# 4. increment and decrement


def apply(f, x):
return f(x)

def increment(x): return x + 1


def decrement(x): return x - 1

print(apply(increment, 10)) # 11
print(apply(decrement, 10)) # 9

# 5. Split function (pass two functions f and g)


def my_split_function(f, g, a, b, x):
if x <= a: return f(x)
elif x >= b: return g(x)
else: return 0

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)

L5. Iterations & Branching Statements — Complete


Branching (If-Elif-Else):

# 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

For Loop — Iterating over Lists, Tuples, Dictionaries:

# 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

# User input loop


while True:
x = int(input("Enter number (0 to stop): "))
if x == 0:
break
print("Square:", x**2)

Comprehensions (Compact Iteration):

# 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]

# Nested list comprehension


pairs = [i+j for i in range(5) for j in range(2)]

# 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

You might also like