Python Notes
Python Notes
1. Introduc0on to Python
• Python: High-level, interpreted language created by Guido van Rossum in 1991,
designed for simplicity, readability, and versa<lity.
• Features:
o Easy to learn and read with simple syntax.
o Cross-plaIorm: Works on Windows, macOS, and Linux.
o Object-oriented: Supports modular and reusable code.
o Supports a large standard library for various tasks (databases, file handling,
networking).
o Popular in web development (Django, Flask), data science (NumPy, Pandas),
scrip<ng, and automa<on.
• Advantages:
o Efficient and produc<ve for developers.
o Dynamic typing: Types are assigned during execu<on.
o Free, open-source, and portable: Code can run across plaIorms without
modifica<on.
o Great community support and resources.
2. Python Installa0on
• Installa0on:
o Download from python.org or use a package manager.
o Python versions: Python 2.7 and Python 3.x (focus on Python 3.x for modern
applica<ons).
o IDEs: Op<ons include IDLE, Jupyter Notebook, and Spyder. Jupyter is highly
favored for data science because of its interac<ve interface and ability to
handle rich text and visualiza<ons.
3. Programming Basics in Python
• Iden0fiers:
o Names for variables, func<ons, classes, etc.
o Must begin with a leher (a-z, A-Z) or underscore, followed by lehers,
numbers, or underscores.
o Case-sensi<ve (e.g., Var and var are different).
• Variables:
o Used to store data.
o Assigned without specifying type (dynamic typing).
o Example:
x = 5 # integer
y = "Hi" # string
z = 3.5 # float
• Comments:
o Single-line: Use #.
o Mul<-line: Use triple quotes (""" comment """).
4. Data Types and Type Conversion
• Basic Data Types:
o int: Integer values.
o float: Decimal numbers.
o str: Text (enclosed in quotes).
o bool: True or False.
• Type Conversion:
o Convert between types using str(), int(), float(), etc.
o Example:
num_str = "10"
num_int = int(num_str) # converts string to integer
5. Operators and Expressions
• Operators:
o Arithme0c: +, -, *, /, // (floor division), % (modulus), ** (power).
o Comparison: ==, !=, >, <, >=, <=.
o Logical: and, or, not.
o Assignment: =, +=, -=, *=, /=, etc.
• Expressions:
o Combine values and operators to perform calcula<ons.
o Example:
a=5
b=2
result = (a + b) * (a - b)
6. Strings and String Opera0ons
• String Basics:
o Enclosed in single ('), double ("), or triple quotes (''', """) for mul<-line.
• String Opera0ons:
o Access characters by index: str[0].
o Slicing: str[start:end] to get a substring.
o Concatenate strings with + and repeat with *.
• String Func0ons:
o len(str): Returns length.
o str.lower(), str.upper(): Changes case.
o str.find("substring"): Finds posi<on of a substring.
o str.replace("old", "new"): Replaces substring.
7. Control Flow
• Condi0onals:
o if, elif, and else statements for decision-making.
o Example:
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
• Loops:
o for: Iterates over items in a sequence.
for i in range(5):
print(i) # prints numbers 0 to 4
o while: Repeats while a condi<on is true.
count = 0
while count < 5:
print(count)
count += 1
8. Python Func0ons
• Defining Func0ons:
o Use def keyword.
o Parameters are defined in parentheses.
o Example:
python
Copy code
def greet(name):
return "Hello, " + name
print(greet("Alice"))
• Built-in Func0ons:
o print(): Outputs data.
o input(): Takes input from the user.
o type(): Returns data type of an object.
1. Operators in Python
• Arithme0c Operators:
o +: Addi<on
o -: Subtrac<on
o *: Mul<plica<on
o /: Division (returns a float)
o //: Floor Division (returns an integer)
o %: Modulus (returns remainder)
o **: Exponen<a<on
a=5
b=3
print(a + b) # 8
print(a ** b) # 125
• Comparison Operators:
o ==: Equal to
o !=: Not equal to
o >: Greater than
o <: Less than
o >=: Greater than or equal to
o <=: Less than or equal to
• Logical Operators:
o and: True if both operands are true.
o or: True if at least one operand is true.
o not: Inverts the truth value.
• Assignment Operators:
o =: Assign value.
o +=, -=, *=, /=: Compound assignment (e.g., x += 3 is equivalent to x = x + 3).
• Membership Operators:
o in: Checks if a value exists in a sequence.
o not in: Checks if a value does not exist in a sequence.
2. Control Flow Statements
• If Statements:
o Basic structure for decision-making.
o Syntax:
if condi<on:
# Code if condi<on is true
elif another_condi<on:
# Code if another_condi<on is true
else:
# Code if none of the condi<ons are true
o Example:
x = 20
if x < 15:
print("x is less than 15")
elif x == 20:
print("x is equal to 20")
else:
print("x is greater than 15 but not 20")
• While Loops:
o Executes a block of code as long as a condi<on is true.
o Syntax:
while condi<on:
# Code to execute
o Example:
i=1
while i <= 5:
print(i)
i += 1
• For Loops:
o Iterates over a sequence.
o Syntax:
for variable in sequence:
# Code to execute
o Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3. Loop Control Statements
• Break Statement:
o Exits the loop immediately.
o Example:
for i in range(5):
if i == 3:
break
print(i)
# Output: 0, 1, 2
• Con0nue Statement:
o Skips the current itera<on and moves to the next.
o Example:
for i in range(5):
if i == 3:
con<nue
print(i)
# Output: 0, 1, 2, 4
• Else with Loops:
o else block executes when the loop completes normally, without encountering
a break.
o Example:
for i in range(5):
print(i)
else:
print("Loop completed")
1. Lists
• Defini0on: An ordered, mutable collec<on that allows duplicate elements.
• Syntax:
my_list = ["apple", "banana", "cherry"]
• Key Proper0es:
o Indexed: Access elements with my_list[index].
o Supports duplicates: Same elements can appear mul<ple <mes.
o Common Methods:
§ append(item): Adds item to the end.
§ insert(index, item): Inserts item at index.
§ remove(item): Removes the first occurrence of item.
§ pop(index): Removes item at index and returns it.
§ clear(): Removes all elements.
§ sort(): Sorts the list.
§ reverse(): Reverses the list order.
o Example:
my_list = [1, 3, 5]
my_list.append(7) # [1, 3, 5, 7]
my_list.sort() # [1, 3, 5, 7]
2. Tuples
• Defini0on: An ordered, immutable collec<on.
• Syntax:
my_tuple = ("apple", "banana", "cherry")
• Key Proper0es:
o Immutable: Cannot modify elements once created.
o Indexed: Access elements with my_tuple[index].
o Supports duplicates.
o Example:
my_tuple = (1, 2, 3)
print(my_tuple[0]) # 1
3. Sets
• Defini0on: An unordered collec<on of unique elements.
• Syntax:
my_set = {"apple", "banana", "cherry"}
• Key Proper0es:
o Unordered: No indexing.
o Unique items only: Duplicates are automa<cally removed.
o Common Methods:
§ add(item): Adds item.
§ remove(item): Removes item, raises error if not found.
§ discard(item): Removes item without error if not found.
§ pop(): Removes and returns an arbitrary element.
§ clear(): Removes all elements.
§ Set Opera0ons:
§ union(): Combines elements from both sets.
§ intersec<on(): Elements common to both sets.
§ difference(): Elements in one set but not the other.
o Example:
my_set = {1, 2, 3}
my_set.add(4) # {1, 2, 3, 4}
4. Dic0onaries
• Defini0on: An ordered collec<on of key-value pairs (as of Python 3.7).
• Syntax:
my_dict = {"brand": "Ford", "model": "Mustang", "year": 1964}
• Key Proper0es:
o Keys are unique and immutable; values can be of any type.
o Access elements by keys (my_dict["brand"]).
o Common Methods:
§ get(key): Returns the value for key.
§ update(): Updates with key-value pairs from another dic<onary.
§ pop(key): Removes key and returns its value.
§ clear(): Removes all items.
o Example:
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
car["year"] = 2020 # Update value
5. List Comprehension
• Defini0on: A concise way to create lists using an expression.
• Syntax:
squares = [x**2 for x in range(10)]
• Example with Condi0on:
evens = [x for x in range(10) if x % 2 == 0]
Summary of Key Points
• Lists: Mutable, ordered, allows duplicates.
• Tuples: Immutable, ordered, allows duplicates.
• Sets: Mutable, unordered, unique items.
• Dic0onaries: Mutable, ordered, key-value pairs.
• List Comprehension: Efficient way to generate lists with condi<ons.
1. Higher-Order Func0ons
• Defini0on: Func<ons that accept other func<ons as arguments or return func<ons as
results.
• Key Proper0es:
o Can store a func<on in a variable.
o Can pass a func<on as an argument to another func<on.
o Can return a func<on from another func<on.
o Commonly used in decorators.
• Examples:
o Passing Func0ons as Arguments:
def shout(text):
return text.upper()
def greet(func):
message = func("Hello!")
print(message)
<mes3 = create_mul<plier(3)
print(<mes3(5)) # Output: 15
2. Decorators
• Defini0on: A decorator is a func<on that wraps another func<on to extend or alter
its behavior without modifying the original func<on's code.
• Syntax: The @decorator_name syntax is used above the func<on defini<on.
• Example:
def my_decorator(func):
def wrapper():
print("Something is happening before the func<on is called.")
func()
print("Something is happening aOer the func<on is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# "Something is happening before the func<on is called."
# "Hello!"
# "Something is happening aOer the func<on is called."
• Common Use Case:
o Error Checking:
def safe_divide(func):
def wrapper(a, b):
if b == 0:
print("Cannot divide by zero!")
return
return func(a, b)
return wrapper
@safe_divide
def divide(a, b):
return a / b
counter = count_up_to(5)
for number in counter:
print(number)
# Output: 1, 2, 3, 4, 5
• Use Cases:
o Infinite sequences: Generators can handle large or infinite sequences without
running out of memory.
o On-demand computa0on: Values are only computed as needed, improving
efficiency.
• Generator Expressions:
o Similar to list comprehensions but use () instead of [], yielding one item at a
<me.
squares = (x * x for x in range(5))
for square in squares:
print(square)
# Output: 0, 1, 4, 9, 16
def objec0ve(x):
return x**2 + 4*np.sin(5*x)
result = minimize(objec0ve, 0)
print("Minimizer:", result.x)
• Sta0s0cs (scipy.stats): Offers func0ons for sta0s0cal analysis, distribu0ons,
hypothesis tes0ng, and probability calcula0ons.
Example:
from scipy.stats import norm
xs = np.array([0, 1, 2, 3])
ys = np.array([0, 1, 4, 9])
interpolator = interp1d(xs, ys, kind='linear')
print("Interpolated value at x=1.5:", interpolator(1.5))
• Special Func0ons (scipy.special): Contains mathema0cal func0ons like Bessel and
gamma func0ons.
x = [1, 2, 3]
y = [2, 4, 1]
plt.plot(x, y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.0tle("Simple Line Plot")
plt.show()
2. Bar Plot:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.scaLer(x, y)
plt.0tle("ScaLer Plot Example")
plt.show()
Advanced Plorng Techniques
• Subplots and Grids:
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot([1, 2, 3, 4], [10, 20, 25, 30])
axs[1, 1].plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.show()
• Customizing Plots:
o linewidth for line thickness, color for color, and marker for point markers.
o Logarithmic and semi-log plots can be created using set_xscale and
set_yscale with arguments "log" or "symlog".
Example: Logarithmic Plot
import numpy as np
import matplotlib.pyplot as plt
x = np.logspace(0.1, 2, 100)
y = np.log(x)
plt.plot(x, y)
plt.xscale("log")
plt.0tle("Logarithmic Scale Example")
plt.show()
result = minimize(objec<ve, 0)
print("Minimized value at x =", result.x)
SciPy's op<mize module offers methods for both constrained and unconstrained problems:
• Unconstrained Op0miza0on: No constraints on decision variables.
• Constrained Op0miza0on: Variables must sa<sfy specified limits.
Types of Op0miza0on Problems:
• Linear Programming: Linear objec<ve func<on and constraints.
• Nonlinear Programming: Nonlinear func<on or constraints.
• Integer and Mixed Integer Programming: Decision variables are integers or mixed
(con<nuous and discrete).
Week 10:
1. Pandas Series
A Series is a one-dimensional labeled array capable of holding any data type. Think of it as a
single column in a table. Useful for storing sequences of data, like <me series or one-
dimensional numerical/character data.
Crea0ng a Series
• Empty Series:
import pandas as pd
series = pd.Series()
print(series)
• Series from List:
data = [10, 20, 30]
series = pd.Series(data)
print(series)
• Series from Dic0onary:
data = {'a': 1, 'b': 2, 'c': 3}
series = pd.Series(data)
• Series with Custom Index:
data = [1, 2, 3]
series = pd.Series(data, index=['x', 'y', 'z'])
Accessing Series Data
• Indexing and Labeling: Access by integer index (series[0]) or label (series['x']).
• ALributes: series.index for index, series.values for data values.
2. Pandas DataFrame
A DataFrame is a two-dimensional, size-mutable, and labeled data structure, ideal for
represen<ng tabular data like rows and columns. Each column can hold different data types,
allowing for heterogeneous data.
Crea0ng DataFrames
• From List of Lists:
data = [[1, 2], [3, 4]]
df = pd.DataFrame(data, columns=['A', 'B'])
• From Dic0onary of Lists:
data = {'Name': ['Tom', 'Jerry'], 'Age': [5, 7]}
df = pd.DataFrame(data)
• From Dic0onary of Series:
data = {'Name': pd.Series(['Tom', 'Jerry']), 'Age': pd.Series([5, 7])}
df = pd.DataFrame(data)
Accessing and Manipula0ng Data
• Selec0ng Columns:
df['Name'] # Single column
df[['Name', 'Age']] # Mul<ple columns
• Selec0ng Rows:
o By Index: df.iloc[0] for the first row.
o By Label: df.loc[0] for label-based indexing.
• Adding Columns:
df['Gender'] = ['M', 'F']
• Dropping Columns:
df.drop('Gender', axis=1, inplace=True)
3. Reindexing in Pandas
Reindexing aligns the DataFrame to a new index. This is essen<al for modifying DataFrame
rows/columns and handling missing data.
• Reindexing Rows:
new_index = ['row1', 'row2']
df_reindexed = df.reindex(new_index)
• Reindexing Columns:
df_reindexed = df.reindex(columns=['A', 'B', 'C'])
• Filling Missing Data During Reindexing:
df_reindexed = df.reindex(new_index, fill_value=0)