hello_wo
rld.py
• • •
# My first Python pr
ogram
def greet():
print("Hello, Python
World!")
print("Let's start le
arning...")
greet()
Python Programming
A Comprehensive Guide
Based on Hans-Petter Halvorsen's Textbook
Made with Genspark
What is Python?
Python is a high-level, interpreted programming language known for its readability and simplicity. Created by Guido van Rossum in 1991, it
emphasizes code readability with its notable use of significant whitespace.
Key Features Why It's Popular
Simple, readable syntax Easy to learn and use
Dynamically typed Versatile for many applications
Interpreted language Large and active community
Object-oriented approach Rich ecosystem of frameworks/libraries
Extensive standard library Cross-platform compatibility
Common Applications Technical Advantages
Python is the #1 language in TIOBE
Data Science & Analysis Multi-paradigm approach index (2023)
Web Development Memory management with garbage collection
Machine Learning & AI Strong integration capabilities
Scripting & Automation Portable (Windows, macOS, Linux)
Scientific Computing Extensible in C/C++
Made with Genspark
Python Development Environment
Python Installation Python Editors & IDEs
Python.org:Official distribution, best for standard development
Anaconda:Scientific distribution with pre-installed packages
Microsoft Easy Windows installation but limited IDLE VS Code
Simple built-in editor, good for Powerful, customizable editor with
Store: functionality
beginners extensions
Windows macOS Linux
Download installer Homebrew Often pre-installed
from python.org or installation or or apt/yum package
use Microsoft Store Python.org installer managers
Spyder Jupyter
Scientific development Interactive notebooks for data
environment science
Getting Started
Interactive Mode:Typepythonin terminal
Script Mode:Save code as.pyfile, run withpython filename.py
# Your first Python script
Path Add Python to system PATH for easy command- print("Hello, Python world!")
Configuration: line access
# Interactive mode example
>>> 2 + 2
4
>>> print("Welcome to Python")
Welcome to Python
Made with Genspark
Python Basics
Variables & Core Concepts Data Types
Dynamic typing:No type declaration needed
Numeric String Boolean
Case sensitive:nameandNameare different variables int: 42 "Hello Python" True
Multiple assignment:x, y, z = 1, 2, "three" float: 3.14159 'Single quotes' False
Naming Start with letter or underscore complex: 3+4j """Multi-line""" bool(0) → False
rules:
Cannot start with number
List Dictionary Tuple
Can only contain alphanumeric characters and
[1, 2, 3, 4, 5] {"name": "John"} (1, 2, 3)
underscore
['a', 'b', 'c'] {"key": value} Immutable
[1, "mix", True] Access: tuple[0] → 1
# Variable declaration examples dict["key"]
name = "John" # String variable
age = 25 # Integer variable Type Conversion
height = 1.85 # Float variable
is_student = True # Boolean variable int("123") → 123 str(42) → "42"
float("3.14") → 3.14 bool(1) → True
Basic Operations
Arithmetic String Operations Comparison & Logical
a + b # Addition s1 + s2 # Concatenation a == b # Equal to
a - b # Subtraction s1 * 3 # Repetition a != b # Not equal
a * b # Multiplication s[0] # Indexing a > b # Greater than
a / b # Division a <= b # Less or equal
s[1:4] # Slicing
a % b # Modulus len(s) # Length and # Logical AND
a ** b # Exponentiation "x" in s # Membership or # Logical OR
a // b # Floor division not # Logical NOT
Made with Genspark
Python Control Structures
If-Else Statements For Loops While Loops
if condition: # Basic for loop with range # Basic while loop
# Code to execute if condition is True for i in range(5): count = 0
statement1 print(i) # 0, 1, 2, 3, 4 while count < 5:
elif another_condition: print(count)
# Code for this condition # Iterating through items count += 1
statement2 for item in ["a", "b", "c"]:
else: print(item) # With break statement
# Executed if all conditions are False while True:
statement3 # Nested loops if condition:
for i in range(3): break
for j in range(2): # statements
Indentation defines code blocks
print(i, j)
Multipleelifblocks allowed
Executes as long as condition isTrue
Condition evaluates to boolean Can iterate over any sequence
Requires condition update
Condition? Action range(start, stop, step)
Careful of infinite loops
Supportsbreak&continue
Control Flow Comparison
Feature If-Else For Loop While Loop
Purpose Decision making Iterating sequences Repeat while condition true
When to use Branching logic Known number of iterations Unknown number of iterations
Key control if, elif, else break, continue, else break, continue
Example use case Input validation Processing list items User input until valid
Loop Control Statements Common Patterns
break: Exit the loop completely Counting loops with range()
continue: Skip current iteration, go to next Enumerating items: enumerate(list)
else: Executes after loop completes normally Loop with index: for i, val in enumerate(list)
Made with Genspark
Python Functions
Function Basics Parameters & Arguments
Type Description Example
def function_name(parameters):
Required Must be provided def func(x, y):
# Function body
# Code block that performs a task Default Optional with default value def func(x=10):
statement1
statement2 Keyword Name-value pairs func(name="John")
return result # Optional Variable-length
Arbitrary number of
def func(*args):
arguments
# Function call
Keyword def
result = function_name(arguments) Arbitrary keyword arguments
variable func(**kwargs):
Reusability:Write once, use multiple times
Modularity:Break complex tasks into smaller parts
# Function with different parameter types
Scope:Variables inside function are local
def display_info(name, age=25, *courses, **info):
Documentation:Use docstrings to describe function print(f"Name: {name}, Age: {age}")
print("Courses:", courses)
print("Additional Info:", info)
Input Output # Function call with mixed arguments
(Arguments) (Return Value) display_info("Alice", 30, "Python", "Data Science",
function_name() city="New York", job="Developer")
Processing Logic
Return Values & Function Examples
Return Values Function Examples
Mathematical Function String Manipulation
# Single return value def calculate_area(radius): def greet(name):
def square(x): return 3.14 * radius**2 return f"Hello, {name}!"
return x * x
# Multiple return values Data Processing Lambda Function
def min_max(numbers): def filter_even(numbers): # Anonymous function
return min(numbers), max(numbers) return [n for n in numbers square = lambda x: x**2
if n % 2 == 0]
# Unpacking multiple returns
minimum, maximum = min_max([1, 5, 3, 9, 2]) Best Practices
Follow naming conventions (snake_case)
returnends function execution
One function = one task (single responsibility)
Noreturn→ returnsNone
Add descriptive docstrings
Multiple values returned as tuple
Keep functions small and focused
Made with Genspark
Python Classes & Object-Oriented Programming
Class Definition & Basics
OOP Core Concepts
# Class Definition Concept Description
class Person:
# Class attribute Class Blueprint for creating objects
species = "Homo sapiens"
Object Instance of a class
# Constructor method
Attributes Data stored in a class/instance
def __init__(self, name, age):
# Instance attributes Methods Functions defined in a class
self.name = name
self.age = age Self Reference to the current instance
# Instance method Inheritance Deriving a class from another class
def display_info(self):
return f"{self.name} is {self.age} years old." The __init__() Method
# Static method Automatically called when creating a new object
@staticmethod
Used to initialize object attributes
def is_adult(age):
return age >= 18 First parameter is alwaysself
Method Types
Instance methods: Access instance data
# Creating objects (instances)
person1 = Person("Alice", 25) Class methods: Access class-level data (@classmethod)
person2 = Person("Bob", 17) Static methods: Independent of class/instance (@staticmethod)
# Accessing attributes and methods
print(person1.name) # Alice
print(person1.display_info()) # Alice is 25 years old.
print(Person.species) # Homo sapiens
print(Person.is_adult(20)) # True
Inheritance & Polymorphism Special Methods & Best Practices
Special Methods (Magic/Dunder
# Parent class Methods)
class Animal:
def __init__(self, name):
self.name = name Object Lifecycle
__init__(self, ...) # Constructor
def speak(self): __del__(self) # Destructor
pass # Abstract method
Operator Overloading
# Child class inherits from Animal __add__(self, other) # +
class Dog(Animal): __eq__(self, other) # ==
def speak(self):
String Representation
return f"{self.name} says Woof!"
__str__(self) # str() and print()
# Another child class __repr__(self) # repr()
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!" OOP Best Practices
Use Encapsulation: keep attributes private (start
# Polymorphism in action
animals = [Dog("Buddy"), Cat("Whiskers")] with _)
Follow the DRY principle (Don't Repeat Yourself)
for animal in animals: Use descriptive class and method names
print(animal.speak())
Add docstrings to document classes and methods
Animal
Dog Cat
Inheritance:Child classes inherit attributes and methods
Polymorphism:Child classes can override parent methods
Multiple inheritance:Python allows inheriting from multiple classes
Made with Genspark
Python Modules
Module Definition Importing Modules
What is a A Python file containing code (variables, functions,
Module: classes)
# Import entire module
Purpose:Organize code logically and promote reusability import math
Namespace:Prevents naming conflicts across projects result = math.sqrt(16) # 4.0
Types:Built-in, third-party, and custom modules # Import specific functions
from math import sqrt, pi
Module Structure result = sqrt(16) # 4.0
# Import statements # Import with alias
import numpy as np
# Constants & Variables arr = np.array([1, 2, 3])
# Functions definitions # Import all (not recommended)
from math import *
# Class definitions
# Main executable code (if any) Import Method When to Use Namespace
import module Standard usage module.function()
from module import Need specific
math os random datetime function()
x components
Mathematical Operating Random Date and time
functions system number utilities import module as
Long module names alias.function()
interface generators alias
Avoidfrom module import *- can cause naming conflicts
Python searches for modules insys.pathlocations
Creating Custom Modules & Package Management
Creating Custom Modules Python Packages
Package:Directory containing multiple modules + __init__.py
Hierarchy:Organizes modules in a structured way
# File: mymodule.py
Subpackages:Nested packages for deeper organization
# Define a variable
pi = 3.14159
Package Structure Example
# Define a function mypackage/
def square(x): ├── __init__.py
return x * x ├── module1.py
├── module2.py
# Define a class └── subpackage/
class Circle: ├── __init__.py
def __init__(self, radius): └── module3.py
self.radius = radius
Package Management
def area(self):
return pi * self.radius ** 2 PIP Commands Virtual Environments
pip install package # Create virtual env
pip uninstall package python -m venv myenv
pip list # Activate (Windows)
# Using our custom module pip freeze > requirements.txt myenv\Scripts\activate
import mymodule
Popular Python Packages
# Access the variable
print(mymodule.pi) # 3.14159 NumPy Pandas Matplotlib SciPy TensorFlow Django Flask
Scikit-learn
# Call the function
result = mymodule.square(4) # 16
# Use the class
circle = mymodule.Circle(5)
area = circle.area() # 78.53975
Made with Genspark
Python File Handling
File Operations Basics File Modes
Mode Description Creates File?
1. Open 2. 3. Close
Read/Write
Connect to
file
Process
Release
resources
'r' Read (default) No
data 'w' Write (truncates) Yes
'a' Append Yes
'x' Create exclusive Error if exists
# Traditional approach
file = open('data.txt', 'r') '+' Update (read/write) No
content = file.read()
file.close() 'b' Binary mode N/A
# Recommended: with statement (context manager) 't' Text mode (default) N/A
with open('data.txt', 'r') as file:
content = file.read()
# File is automatically closed when block ends Common Mode Combinations:
'rb' - read binary
Always close filesto prevent resource leaks
'wb' - write binary
'r+' - read and write
Usecontext managers(with statement) to ensure proper file handling 'a+' - append and read
Handleexceptionswhen working with files
Warning: 'w' mode erases existing file content
Reading & Writing Files
Reading Files Writing Files
with open('data.txt', 'r') as file: with open('output.txt', 'w') as file:
# Read entire file # Write a string
content = file.read() file.write("Hello, Python!\n")
# Read line by line # Write multiple lines
file.seek(0) # Reset cursor to beginning lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
first_line = file.readline() file.writelines(lines)
# Read all lines into a list # Append to a file
file.seek(0) with open('output.txt', 'a') as file:
lines = file.readlines() file.write("Appended text\n")
# Iterate through lines
file.seek(0) Logging Data Example:
for line in file:
import logging
print(line.strip()) # strip() removes \n
# Configure logging
logging.basicConfig(
Efficient Reading of Large Files: filename='app.log',
# Process line by line (memory efficient) level=logging.INFO,
with open('large_file.txt', 'r') as file: format='%(asctime)s - %(levelname)s - %(message)s'
for line in file: )
process_line(line)
# Write log entries
logging.info("Program started")
logging.warning("Low disk space")
Useread(size)to control memory usage logging.error("Failed to connect to database")
Handle encoding withopen(file, mode, encoding="utf-8")
Remember:write()doesn't add newlines automatically
writelines()doesn't add newlines between items
Advanced File Handling
Binary Files File Position CSV Files
# Read/write binary data # Get current position import csv
with open('image.jpg', 'rb') as f: pos = file.tell()
binary_data = f.read() with open('data.csv', 'r') as f:
# Change position csv_reader = csv.reader(f)
file.seek(10) # Move to byte 10 for row in csv_reader:
print(row)
Made with Genspark
Python Error Handling
Types of Errors Try-Except Structure
Syntax Errors Exceptions try except else finally
Code Handle Run if Always
Errors in code structure that prevent Errors during program execution
execution (runtime)
that
specific
no
executed
might exceptions exceptions
raise
exceptions
# Missing colon # Division by zero
if x > 5 x = 10
print(x) y = 0 try:
result = x / y file = open('data.txt', 'r')
# Output: content = file.read()
File "script.py", line 1 # Output: value = int(content)
if x > 5 Traceback (most recent call last): except FileNotFoundError:
^ File "script.py", line 3, in <module> print("The file was not found")
SyntaxError: invalid syntax result = x / y except ValueError:
ZeroDivisionError: division by zero print("Could not convert data to integer")
except: # Catch any other exception
print("An unexpected error occurred")
else: # Executes if no exceptions
ZeroDivisionError TypeError ValueError NameError IndexError KeyError
print(f"The value is {value}")
FileNotFoundError ImportError
finally: # Always executes
if 'file' in locals():
file.close()
print("File closed")
Multiple except can handle different exception
blocks types
Useexcept Exception as to access exception
e information
finallyguarantees execution (resource cleanup)
Best Practices & Custom Exceptions
Best Practices Custom Exceptions
Create custom exceptions for application-specific error handling
Be Specific
Catch specific exceptions, not all exceptions
# Define custom exceptions
Proper Cleanup class InsufficientFundsError(Exception):
Use finally blocks or context managers (with) for cleanup def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
Avoid Bare Excepts
self.message = f"Cannot withdraw ${amount} " \
Don't use plain except: without specifying exceptions f"from balance of ${balance}"
super().__init__(self.message)
Minimize Try Block Size
# Using custom exception
Keep try blocks as small as possible
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
# Bad: too broad
try: def withdraw(self, amount):
process_data() if amount > self.balance:
except: # Catches everything! raise InsufficientFundsError(
print("Error") self.balance, amount)
self.balance -= amount
# Good: specific exception handling return amount
try:
process_data()
except ValueError as e: Exception Hierarchy
print(f"Value error: {e}") BaseException
except FileNotFoundError as e:
└─ Exception
print(f"File error: {e}")
└─ ArithmeticError (ZeroDivisionError)
└─ LookupError (IndexError, KeyError)
└─ OSError (FileNotFoundError)
└─ YourCustomError
Advanced Error Handling Techniques
Context Managers Raising Exceptions Exception Chaining
# Using with statement def divide(a, b): try:
with open('file.txt') as f: if b == 0: process_data()
data = f.read() raise ValueError("Cannot divide by zero") except ValueError as e:
# File automatically closes return a / b raise RuntimeError("Processing failed") from e
Made with Genspark
Python Environments and Distributions
Package & Environment Managers Python Distributions
PIP (Package Installer for Python) Anaconda
Standard package manager for Python libraries Popular Python/R distribution for data science and ML
Includes:1,500+ Python/R packages
Features:Anaconda Navigator (GUI), conda package manager
# Installing packages
pip install numpy scipy matplotlib Built-in tools:Jupyter, Spyder, RStudio
Data Machine Scientific Beginner
# Specific version
Science Learning Computing Friendly
pip install pandas==1.3.0
# Listing installed packages
pip list Miniconda
Minimal installer for conda (lightweight Anaconda)
# Requirements file
pip install -r requirements.txt Includes:Python, conda, essential packages only
Advantage:Smaller size, install only what you need
Virtual Environments Enthought Canopy
Isolated Python environments for different projects Scientific and analytic Python distribution
Focus:Scientific computing and analysis
Creating Virtual Environments
Features:Integrated analysis environment, graphical package
1 python -m venv myenv (Create)
manager
source myenv/bin/activate (Unix) or
2 Scientific Analysis Visualization
myenv\Scripts\activate (Windows)
3 pip install [packages] (Install packages)
PyCharm + venv
4 deactivate (Exit virtual environment)
Standard Python + IDE + virtual environments
Approach:Standard Python with manual setup
Advantage:More control, IDE integration
Conda (Environment Manager)
Cross-platform environment and package manager
# Create environment
conda create --name myenv python=3.9
# Activate environment
conda activate myenv
# Install packages
conda install numpy pandas matplotlib
# List environments
conda env list
Environment Management Comparison
Feature pip + venv Conda Anaconda
Package Management Python packages only Python + other languages 1,500+ pre-installed
Dependency Resolution Basic Advanced Advanced
Environment Management venv module Built-in Built-in
Binary Packages Limited (wheels) Extensive Extensive
System Integration Python ecosystem only Cross-platform Cross-platform + GUI
Size Minimal Medium (~400MB) Large (~3GB)
Best For Web development, small projects Custom environments, space-conscious Data science, beginners
Best Practices When to Choose What
Use virtual environments forevery project Standard Python + venv:Web development, simple apps
Track dependencies withrequirements.txtorenvironment.yml Miniconda:Custom scientific environments
Be explicit about package versions for reproducibility Anaconda:Data science, education, beginners
Made with Genspark
Python Editors
Visual Studio Code POPULAR PyCharm PROFESSIONAL Jupyter Notebook INTERACTIVE
Open-source, lightweight, customizable Dedicated Python IDE by JetBrains Browser-based notebooks with code &
markdown
Powerful extensions ecosystem Advanced code analysis Interactive code cells
Integrated terminal and debugger Refactoring tools Rich output (plots, tables, images)
Git integration Scientific tools & data visualization Markdown documentation
IntelliSense for code completion Web development frameworks support JupyterHub for multi-user environments
BEST FOR: General Dev Web Dev BEST FOR: Professional Large Projects BEST FOR: Data Science Education
Spyder SCIENTIFIC Python IDLE BEGINNER Visual Studio ENTERPRISE
Scientific Python Development Environment Python's built-in development environment Full-featured IDE with Python workload
Similar to MATLAB/RStudio interface Comes bundled with Python Enterprise-grade tools
Variable explorer Simple interface Advanced debugging
Integrated plotting Interactive shell Python & C/C++ mixed mode debugging
IPython console integration Basic debugger Strong .NET integration
BEST FOR: Data Analysis Scientific BEST FOR: Learning Simple Scripts BEST FOR: Enterprise .NET Projects
Editor Comparison
Feature VS Code PyCharm Jupyter Spyder IDLE Visual Studio
Ease of Setup ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐
Code Analysis ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐⭐
Debugging ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐⭐⭐
Data Analysis ⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐
Resource Usage ⭐⭐⭐⭐ ⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐
Made with Genspark
Mathematics in Python
Basic Math Functions Statistics
import math import statistics as stats
import numpy as np
# Basic operations
x = 7.8 data = [5, 7, 8, 9, 10, 12, 14, 18]
y = 3
# Basic statistics
ceil_value = math.ceil(x) # 8 mean_value = stats.mean(data) # 10.375
floor_value = math.floor(x) # 7 median_value = stats.median(data) # 9.5
abs_value = abs(-42) # 42 mode_value = stats.mode(data) # 5
power = math.pow(y, 2) # 9.0 stdev_value = stats.stdev(data) # 4.069
sqrt_value = math.sqrt(16) # 4.0
exp_value = math.exp(2) # e^2 # NumPy alternatives
log_value = math.log(10) # ln(10) np_data = np.array(data)
log10_value = math.log10(10) # 1.0 np_percentile = np.percentile(np_data, 75) # 1
Common Functions
Function Description
math.pi, math.e math.factorial()
Average
mean()
value
math.gcd(), math.lcm() round()
Middle
median()
min(), max(), sum() math.isclose() value
Most
mode() common
value
Standard
stdev()
deviation
Variance of
variance()
data
Trigonometric Functions Polynomials
import numpy as np
import math from numpy.polynomial import Polynomial as P
import numpy as np
# Define polynomial p(x) = x² + 2x + 3
# Convert degrees to radians p = P([3, 2, 1]) # Coefficients: constant, x,
angle_deg = 45
angle_rad = math.radians(angle_deg) # Evaluate at specific points
result = p(5) # p(5) = 5² + 2*5 + 3 = 38
# Basic trig functions
sin_value = math.sin(angle_rad) # 0.7071 # Polynomial arithmetic
cos_value = math.cos(angle_rad) # 0.7071 q = P([1, 1]) # q(x) = x + 1
tan_value = math.tan(angle_rad) # 1.0 sum_poly = p + q # x² + 3x + 4
sin²(θ) + cos²(θ) = 1
prod_poly = p * q # x³ + 3x² + 5x + 3
# Inverse functions tan(θ) = sin(θ) / cos(θ)
asin_value = math.asin(0.5) # 0.5236 # Find roots (where p(x) = 0)
degrees_value = math.degrees(asin_value) # 30° roots = p.roots() # Complex roots
Common Trig Functions
Polynomial
sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) atan2(y,x) hypot(x,y)
Applications
degrees(x) radians(x) Curve fitting
Interpolation
Numerical
integration
Signal
processing
Control systems
Made with Genspark
Practical Python Applications
Data Science & ML Web Development Automation & Scripting
pandas scikit-learn numpy Django Flask FastAPI PyAutoGUI Scrapy Schedule
matplotlib TensorFlow PyTorch SQLAlchemy Fabric
Web Scraping & Data Collection
import pandas as pd
Dj Fl k F tAPI /
import numpy as np
from sklearn.model_selection import t
from sklearn.ensemble import RandomFo
import matplotlib.pyplot as plt Scientific Computing & Visualization
# Load and explore data
df = pd.read_csv('data.csv')
df.head() SciPy SymPy Seaborn NetworkX Mayavi NumPy
df.describe()
Applications
# Prepare features and target
X = df.drop('target', axis=1) Physics Simulations
y = df['target']
Genomics & Biology Made with Genspark
Python Programming: Key Takeaways
Key Topics Covered Python Ecosystem
Python Basics Control Structures
Functions Object-Oriented Programming
Modules & Packages File Handling
Error Handling Mathematics in Python
Python's versatility comes from its extensive
ecosystem. The chart shows popular domains where
Python excels, with numerous libraries supporting each
area.
Exam Preparation Tips
Practice Coding Daily
Further Learning
Implement coding exercises regularly. Python is best learned by writing code,
not just reading about it.
Official Python Documentation
python.org/doc - Comprehensive reference
Focus on Fundamentals
Master the core concepts (data types, control flow, functions) before tackling
Interactive Practice
advanced topics.
Codecademy, LeetCode, HackerRank
Create Small Projects Recommended Books
Build simple applications that combine multiple concepts to solidify your Python Crash Course, Fluent Python
understanding.
Video Tutorials
Corey Schafer, freeCodeCamp, Real Python
Made with Genspark