Unit 2: Introduction to Python
Comprehensive guide to Python programming fundamentals, control structures, data structures, and numerical computing with NumPy.
1. Basics of Python Programming
Python is a high-level, interpreted programming language known for its simplicity and readability. It emphasizes code clarity and uses meaningful indentation.
Key Characteristics:
- Simple Syntax: Easy to learn and read, similar to English
- Interpreted: Code is executed line by line
- Dynamically Typed: Variables don't need type declarations
- Object-Oriented: Supports classes and objects
- Extensive Libraries: Rich collection of built-in modules
First Program:
print("Hello, Python!")
x = 5
y = 10
print(f"Sum: {x + y}")2. Execution Modes
Interactive Mode
Immediate feedback on commands. Type python in terminal to enter.
>>> x = 5 >>> print(x) 5 >>> print(x * 2) 10
Script Mode
Write code in a .py file and execute it with python filename.py
# hello.py
name = input("Enter your name: ")
print(f"Hello, {name}!")3. Program Structure & Indentation
Python uses indentation to define code blocks. Indentation is mandatory and consistent.
# Comments start with #
# Single-line comment
"""
Multi-line comment
Also used for docstrings
"""
# Statements
x = 10
if x > 5:
print("x is greater than 5") # 4-space indentation
# Functions
def greet(name):
message = f"Hello, {name}"
return message4. Identifiers, Keywords & Constants
Identifiers
Names given to variables, functions, classes, etc. Must follow rules:
- Start with letter or underscore, not a number
- Can contain letters, numbers, and underscores
- Case-sensitive:
myVarandmyvarare different - No spaces allowed
Keywords
Reserved words with special meaning in Python:
if, else, elif, while, for, break, continue, def, return, class import, from, try, except, finally, raise, with, as, pass
Constants
Fixed values that don't change. By convention, use uppercase:
PI = 3.14159 MAX_SIZE = 100 GRAVITY = 9.8
5. Variables & Data Types
Variable Declaration
# No explicit type declaration needed x = 10 # int name = "Python" # str score = 9.5 # float is_valid = True # bool # Multiple assignment a, b, c = 1, 2, 3 x = y = z = 0 # All equal to 0
Data Types
Immutable (Cannot be changed):
- int: Integers - 42, -5, 0
- float: Decimals - 3.14, -2.5
- str: Strings - "Hello", 'Python'
- tuple: Ordered, immutable - (1, 2, 3)
- bool: True or False
Mutable (Can be changed):
- list: Ordered, allows duplicates - [1, 2, 3]
- dict: Key-value pairs - {name: "Alice", age: 25}
- set: Unordered, unique - {1, 2, 3}
Type Conversion
# Explicit conversion
str_num = "123"
num = int(str_num) # Convert to int: 123
decimal = float("3.14") # Convert to float: 3.14
text = str(42) # Convert to string: "42"
is_true = bool(1) # Convert to bool: True
# Using type() to check data type
print(type(x)) # <class 'int'>
print(type("hello")) # <class 'str'>6. Operators & Precedence
| Operator Type | Operators | Example | Result |
|---|---|---|---|
| Arithmetic | +, -, *, /, //, %, ** | 10 / 3, 2 ** 3 | 3.33, 8 |
| Relational | ==, !=, <, >, <=, >= | 5 > 3, 2 == 2 | True, True |
| Logical | and, or, not | True and False, not True | False, False |
| Assignment | =, +=, -=, *=, /= | x = 5, x += 2 | 5, 7 |
Operator Precedence (Highest to Lowest)
1. ** (Exponentiation) 2. +x, -x, ~x (Unary) 3. *, /, //, % (Multiplication/Division) 4. +, - (Addition/Subtraction) 5. ==, !=, <, >, <=, >= (Comparison) 6. not (Logical NOT) 7. and (Logical AND) 8. or (Logical OR) # Example result = 2 + 3 * 4 ** 2 # = 2 + 3 * 16 = 2 + 48 = 50
7. Control Statements
if-else Statement
# Simple if-else
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")if-elif-else Statement
# Grade classification
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
else:
print("Grade D")while Loop
# Print 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
# Sum of first n numbers
n = 5
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print(f"Sum: {sum}")for Loop
# Using range
for i in range(1, 6): # 1 to 5
print(i)
# Iterating through list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Using enumerate for index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")break and continue
# break - exits loop
for i in range(1, 11):
if i == 5:
break
print(i) # Prints 1 to 4
# continue - skips current iteration
for i in range(1, 6):
if i == 3:
continue
print(i) # Prints 1, 2, 4, 58. Lists
Creating and Initializing Lists
# Different ways to create lists numbers = [1, 2, 3, 4, 5] mixed = [1, "Python", 3.14, True] empty = [] from_range = list(range(10)) # [0, 1, 2, ..., 9] # Accessing elements print(numbers[0]) # 1 (first) print(numbers[-1]) # 5 (last) print(numbers[1:4]) # [2, 3, 4] (slicing)
List Methods and Operations
| Method | Description | Example |
|---|---|---|
| append() | Add element at end | lst.append(6) |
| insert() | Insert at position | lst.insert(1, 99) |
| remove() | Remove first value | lst.remove(3) |
| pop() | Remove by index | lst.pop(2) |
| sort() | Sort ascending | lst.sort() |
| reverse() | Reverse list | lst.reverse() |
| len() | List length | len(lst) |
| min()/max() | Min/max value | min(lst), max(lst) |
| sum() | Sum of elements | sum(lst) |
Practical Example
scores = [85, 90, 78, 92, 88]
# Traversing
for score in scores:
print(score)
# Manipulation
scores.append(95)
scores.insert(0, 100)
scores.remove(78)
scores.sort()
# Statistics
print(f"Avg: {sum(scores)/len(scores):.2f}")
print(f"Highest: {max(scores)}, Lowest: {min(scores)}")9. Dictionaries
Key-Value Pairs
# Creating dictionary
student = {
"name": "Alice",
"age": 20,
"course": "CS",
"gpa": 3.8
}
# Accessing
print(student["name"]) # Alice
print(student.get("age")) # 20
# Adding/Updating
student["email"] = "alice@mail.com" # Add
student["age"] = 21 # Update
# Deleting
del student["gpa"]Dictionary Methods
| Method | Description | Example |
|---|---|---|
| keys() | Get all keys | dict.keys() |
| values() | Get all values | dict.values() |
| items() | Get key-value pairs | dict.items() |
| len() | Number of items | len(dict) |
| update() | Merge dicts | dict.update(other) |
| clear() | Remove all | dict.clear() |
Practical Example
students = {
"S001": {"name": "Alice", "marks": 85},
"S002": {"name": "Bob", "marks": 92},
"S003": {"name": "Carol", "marks": 78}
}
# Traversing
for roll, details in students.items():
print(f"{roll}: {details['name']} - {details['marks']}")
# Finding highest
highest = max(students.items(), key=lambda x: x[1]["marks"])
print(f"Topper: {highest[1]['name']}")10. Introduction to NumPy
What is NumPy?
NumPy (Numerical Python) is a library for numerical computing. It provides:
- N-dimensional arrays (ndarrays) for efficient operations
- Mathematical functions (linear algebra, statistics)
- Much faster than Python lists for numerical work
- Essential for data science and machine learning
Creating NumPy Arrays
import numpy as np # From Python list arr1 = np.array([1, 2, 3, 4, 5]) print(arr1) # [1 2 3 4 5] # Multi-dimensional array arr2 = np.array([[1, 2, 3], [4, 5, 6]]) # Using built-in functions arr3 = np.zeros(5) # [0. 0. 0. 0. 0.] arr4 = np.ones(3) # [1. 1. 1.] arr5 = np.arange(0, 10, 2) # [0 2 4 6 8] arr6 = np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.]
Array Properties
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr.shape) # (2, 3) - 2 rows, 3 cols print(arr.dtype) # int64 - data type print(arr.size) # 6 - total elements print(arr.ndim) # 2 - dimensions
Array Operations
import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Arithmetic result = arr * 2 # [2 4 6 8 10] result = arr + 10 # [11 12 13 14 15] # Statistical functions print(np.sum(arr)) # 15 print(np.mean(arr)) # 3.0 print(np.max(arr)) # 5 print(np.min(arr)) # 1 print(np.std(arr)) # Standard deviation
Applications of NumPy
Scientific Computing
- Physics simulations
- Statistical analysis
Data Analysis
- Data transformation
- Pattern recognition
Machine Learning
- Feature extraction
- Image processing
Financial Analysis
- Stock analysis
- Risk calculations
Practical Example
import numpy as np
# Grade analysis
grades = np.array([85, 90, 78, 92, 88, 76, 95])
print(f"Average: {np.mean(grades):.2f}")
print(f"Highest: {np.max(grades)}")
print(f"Lowest: {np.min(grades)}")
print(f"Std Dev: {np.std(grades):.2f}")
# Count above average
above_avg = np.sum(grades > np.mean(grades))
print(f"Above average: {above_avg}")Tips & Takeaways
- Use Meaningful Names: Choose variable names that clearly describe their purpose
- Consistent Indentation: Use 4 spaces for indentation throughout your code
- Comments: Write comments to explain complex logic
- Test Frequently: Test your code in interactive mode before writing scripts
- List Comprehension: Use
[x*2 for x in range(5)]for efficient list creation - Dictionary Best Practices: Use dictionaries for structured data like records
- NumPy Performance: Always use NumPy arrays for numerical operations, not lists
