Introduction to Python
Python is a high-level, interpreted, object-oriented programming language with dynamic semantics. Created by Guido van Rossum in 1989 during the Christmas holidays in Amsterdam, it was initially intended as a scripting companion to the ABC language. Guido, a fan of the comedy group Monty Python, named the language accordingly.
Historical Milestones
- CNRI Era: Early development supported by the Corporation for National Research Initiatives; versions up to 1.5 were released here.
- BeOpen & Digital Creations: Python 2.0 emerged during this phase, introducing significant enhancements over 1.x.
- Modern Era: Python 3.0 marked a major redesign to rectify fundamental design flaws, though adoption took years due to backward incompatibility.
Python has received accolades like the TIOBE Programming Language of the Year, reflecting its widespread popularity—though such rankings measure community interest, not technical superiority.
Key Features
- Readability: Emphasizes clean, pseudo-code-like syntax that prioritizes problem-solving over syntactic complexity.
- Interpreted Execution: Code runs directly from source via an interpreter (e.g., CPython), without explicit compilation.
- Portability: Runs across platforms including Windows, macOS, and Linux due to its open-source nature.
- Comprehensive Standard Library: Offers modules for tasks ranging from web requests (
urllib) to data serialization (json), threading, and GUI development. - Extensibility: Integrates with C/C++ and serves as a "glue language" to bind components written in other languages.
Real-World Applications
- Google uses Python for search engine infrastructure and web crawling.
- YouTube’s backend is largely built with Python.
- NASA employs it for scientific computing and automation scripts.
Limitations
- Performance: Slower than compiled languages like C++; performance-critical sections are often rewritten in C extensions.
- Source Visibility: Being open-source, code isn’t natively obfuscated—though this matters less for server-side or SaaS applications.
- Ecosystem Fragmentation: Multiple web frameworks (Django, Flask, FastAPI) offer flexibility but lack a single dominant standard like Ruby on Rails.
Environment Setup
Installing Python
On Ubuntu:
sudo apt update
sudo apt install python3 python3-pip
python3 --version
Using Anaconda
Anaconda is a Python distribution tailored for data science, bundling 180+ packages (e.g., NumPy, Pandas). Install via:
bash Anaconda3-*-Linux-x86_64.sh
# Accept license, confirm installation path
source ~/.bashrc
To disable auto-activation of the base environment:
conda config --set auto_activate_base false
Manage environments with:
conda env list # List environments
conda activate base # Activate base
Enhanced REPL: IPython
Install and launch an improved interactive shell:
pip install ipython
ipython
Basic Syntax and Execution
Comments
# Single-line comment
"""
Multi-line
comment
"""
Input/Output
name = input("Enter your name: ")
age = input("Enter your age: ")
print(f"{name} is {age} years old.")
Script Execution
Save as hello.py:
#!/usr/bin/env python3
print("Hello, world!")
Run with:
python3 hello.py
Bytecode Compilation
Python compiles .py files to bytecode (.pyc) stored in __pycache__ for faster module loading:
import py_compile
py_compile.compile("hello.py")
Optimized bytecode (removes assertions):
python3 -O -m py_compile hello.py
Batch compile a directory:
import compileall
compileall.compile_dir("./scripts")
Data Types and Variables
Built-in Types
- Numeric:
int,float,complex,bool(True/False) - Sequences:
str,list,tuple - Mappings:
dict
Examples:
num = 42 # int
pi = 3.14 # float
valid = True # bool
name = "Alice" # str
Variable Rules
- Names must start with a letter or underscore, followed by letters, digits, or underscores.
- Case-sensitive:
Name ≠ name. - Avoid reserved keywords (check via
import keyword; print(keyword.kwlist)).
Variables are references to objects:
a = 100
print(type(a)) # <class 'int'>
a = 3.14
print(type(a)) # <class 'float'>
Swapping values:
x, y = 1, 2
x, y = y, x # Swap without temporary variable
Operators and Type Conversion
Arithmetic Operators
Precedence: ** > * / // % > + -
print(7 // 2) # 3 (floor division)
print(7 % 2) # 1 (modulo)
Assignment Operators
a = 5
a += 3 # Equivalent to a = a + 3
Comparison and Identity
==copmares values.ischecks if two variables reference the same object.
x = y = 100
print(x == y) # True
print(x is y) # True (due to integer caching)
Type Conversion
int("42") # 42
float("3.14") # 3.14
bool(0) # False
str(123) # "123"
Note: int("10.5") raises ValueError; use int(float("10.5")) instead.
Control Flow
Conditional Statements
hour = int(input("Enter hour (0-23): "))
if 22 <= hour or hour < 2:
print("Zi Shi")
elif 2 <= hour < 4:
print("Chou Shi")
# ... additional cases ...
else:
print("Invalid input")
Loops
For loop:
for i in range(1, 101):
if i % 7 == 0 or '7' in str(i):
print(i)
While loop:
import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess (1-100): "))
attempts += 1
if guess == secret:
print(f"Correct! Attempts: {attempts}")
break
elif guess > secret:
print("Too high")
else:
print("Too low")
Jump Statements
break: Exits the innermost loop.continue: Skips to the next iteration.
Data Structures
Strings
Immutable sequences supporting slicing and formatting:
msg = "Hello, Andy!"
print(msg[0:5]) # "Hello"
print(f"Message: {msg}") # f-string (Python 3.6+)
Common methods:
str.upper(),str.lower()str.split(),str.join()str.strip()
Lists
Mutable ordered collections:
fruits = ["apple", "banana"]
fruits.append("cherry")
fruits.extend(["date", "elderberry"])
fruits.sort(reverse=True)
Tuples
Immutable sequences:
point = (3, 4)
x, y = point # Tuple unpacking
Dictionaries
Key-value mappings:
person = {"name": "Andy", "age": 19}
person["city"] = "Hong Kong" # Add/update
print(person.get("phone", "N/A")) # Safe access
Functions
Parameters
- Default arguments:
def greet(name, age=30): print(f"{name}, age {age}") - Variable-length arguments:
def process(*args, **kwargs): print(args) # Tuple of positional args print(kwargs) # Dict of keyword args
Return Values
Multiple returns are packed into a tuple:
def divide(a, b):
return a // b, a % b
quotient, remainder = divide(10, 3)
Scope
Use global to modify global variables inside functions:
counter = 0
def increment():
global counter
counter += 1
File Handling
Reading/Writing Files
# Write
with open("data.txt", "w") as f:
f.write("Hello\nWorld")
# Read
with open("data.txt", "r") as f:
content = f.read()
print(content)
File Positioning
tell(): Returns current file position.seek(offset, whence): Moves position (whence=0for start,1for current,2for end).
Example:
with open("data.txt", "r") as f:
f.read(5) # Read first 5 bytes
print(f.tell()) # Position: 5
f.seek(0) # Go back to start