UNIT 1: Introduction to Python & Fundamentals
1.1 Introduction to Programming & Python
-
What is Programming? The process of designing a sequence of instructions (a program) that a computer can execute to perform a specific task or solve a problem. The programmer writes code in a programming language to communicate with the machine.
-
What is Python? A high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. Its design philosophy emphasizes code readability and simplicity.
-
Key Features:
-
Interpreted: Executed line-by-line by the Python interpreter, no separate compilation step.
-
High-level: Abstracts away low-level details like memory management.
-
General-purpose: Suitable for web apps, data science, AI, automation, etc.
-
Readable Syntax: Uses English keywords and significant whitespace (indentation).
-
Dynamically Typed: Type checking done at runtime.
-
Extensive Standard Library: "Batteries included" philosophy.
-
-
-
Python Philosophy - The Zen of Python (
import this): A collection of 19 aphorisms guiding Python's design. Key principles include:"Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Readability counts."
-
Major Applications: Web development (Django, Flask), Data Science & Analytics (Pandas, NumPy), Artificial Intelligence & Machine Learning (TensorFlow, PyTorch), Automation & Scripting, Scientific Computing.
-
Python 2 vs. Python 3: Python 3 (released 2008) is the current standard. Key differences:
| Feature | Python 2 | Python 3 | | :--- | :--- | :--- | | Print | Statement:
print "Hello"| Function:print("Hello")| | Integer Division |5 / 2 = 2(floor) |5 / 2 = 2.5(true div),5 // 2 = 2| | Unicode |str= ASCII bytes,unicodetype |str= Unicode by default | | xrange() | Exists (memory efficient) | Removed;range()behaves likexrange()| | Error Syntax |except exc, var:|except exc as var:|
[!TIP] Exam Focus: Know that Python 3 is the standard. Be prepared to convert basic Python 2
1.2 Setting Up the Environment
-
Installing Python: Download the official installer from python.org. Choose the version (latest stable, e.g., 3.12+) and ensure to check "Add Python to PATH" during installation on Windows.
-
Python Interpreter (REPL): An interactive shell where you can type Python code and see immediate results. Access via terminal/command prompt by typing
pythonorpython3.- REPL Cycle: Read input → Eval (evaluate) → Print result → Loop.
-
First Program - "Hello World":
-
Create a file
hello.py. -
Write:
print("Hello, World!") -
Run from terminal:
python hello.py
-
-
Code Editors & IDEs:
-
IDLE: Bundled with Python, basic IDE.
-
VS Code: Lightweight, powerful extensions (Python, Pylance).
-
PyCharm: Full-featured IDE (Professional/Community).
-
Jupyter Notebook: Web-based interactive documents, ideal for data science.
-
[!TIP] Common Pitfall: Running
pythonin terminal might open Microsoft Store on some Windows installations if not added to PATH. Usepylauncher on Windows orpython3on macOS/Linux.
1.3 Basic Syntax & Structure
-
Statements vs. Expressions:
-
Statement: A complete instruction that performs an action (e.g.,
x = 5,print(x)). -
Expression: A combination of values, variables, and operators that evaluates to a single value (e.g.,
5 + 3,x * 2).
-
-
Comments:
-
Single-line:
# This is a comment -
Multi-line (docstring):
"""This is a multi-line string often used as a docstring."""or'''...'''. Not true comments but unused strings.
-
-
Indentation: CRITICAL RULE. Python uses whitespace (spaces/tabs) to define code blocks (scope of loops, functions, conditionals). No braces
{}. Inconsistent indentation causesIndentationError.if x > 0: print("Positive") # Indented block print("Done") # Outside block -
Line Continuation:
-
Explicit: Use backslash
\at end of line. -
Implicit: Inside parentheses
(), brackets[], or braces{}.total = 1 + 2 + 3 + \ 4 + 5 my_list = [1, 2, 3, 4, 5]
-
-
Multiple Statements on One Line: Separate with semicolon
;(generally discouraged for readability).x = 5; y = 10; print(x+y)
1.4 Variables and Data Types
-
Variables: Names that reference objects in memory.
-
Naming Rules (snake_case): Start with letter/underscore, case-sensitive, no spaces, avoid Python keywords (
def,class, etc.). -
Assignment:
variable_name = value(binds name to object).
-
-
Dynamic Typing: Variables have no fixed type; they are names bound to objects. The type is associated with the object, not the variable name.
x = 10 # x references an int object x = "hello" # x now references a str object; int object is orphaned -
Core Data Types:
| Type | Description | Example | | :--- | :--- | :--- | |
int| Integers (unlimited precision) |42,-100,0b1010(binary) | |float| Floating-point (decimal) numbers |3.14,-0.001,2.5e-3| |complex| Complex numbers (a + bj) |3 + 4j| |str| Sequence of Unicode characters |'hello',"world",'''multi-line'''| |bool| Boolean truth values |True,False| |NoneType| Represents absence of value |None| -
Type Checking: Use built-in
type()function.print(type(10)) # <class 'int'> print(type(3.14)) # <class 'float'> print(type("hi")) # <class 'str'> print(type(True)) # <class 'bool'>
1.5 Basic Input and Output
-
Output -
print():-
Basic:
print("Hello", 123, True)→Hello 123 True -
Parameters:
-
sep(separator): Default space.print("A", "B", sep="-")→A-B -
end: Default newline\n.print("Hello", end="")→ no newline. -
file: Output stream (defaultsys.stdout).
-
-
-
Input -
input():-
Always returns a string (
str). Must be explicitly converted for numeric use. -
Syntax:
variable = input("Prompt message: ")
age_str = input("Enter your age: ") # User enters "25" age = int(age_str) # Explicit conversion to integer -
-
Simple Program Structure:
input()→ process/convert →print().
[!TIP] Critical Reminder:
input()result is always a string. Forgetting to convert (int(),float()) leads toTypeErrorwhen performing arithmetic.
1.6 Operators
-
Arithmetic Operators:
| Operator | Meaning | Example (
a=10, b=3) | | :--- | :--- | :--- | |+| Addition |a + b = 13| |-| Subtraction |a - b = 7| |*| Multiplication |a * b = 30| |/| True Division (float) |a / b = 3.333...| |//| Floor Division (quotient) |a // b = 3| |%| Modulo (remainder) |a % b = 1| |**| Exponentiation |a ** b = 1000| -
Assignment Operators:
=,+=,-=,*=,/=,//=,%=,**=. Combine assignment with arithmetic.x = 5 x += 2 # Equivalent to x = x + 2; x is now 7 -
Comparison (Relational) Operators:
==,!=,>,<,>=,<=. Returnbool.10 == 10.0 # True (value comparison) -
Logical Operators:
and,or,not. Operate on boolean values.|
A|B|A and B|A or B| | :--- | :--- | :--- | :--- | |True|True|True|True| |True|False|False|True| |False|True|False|True| |False|False|False|False|- Short-circuit Evaluation:
A and Bstops ifAisFalse.A or Bstops ifAisTrue.
- Short-circuit Evaluation:
-
Identity Operators:
is,is not. Check if two references point to the same object in memory.a = [1,2]; b = [1,2] a == b # True (values equal) a is b # False (different objects in memory) -
Membership Operators:
in,not in. Check for membership in sequences (str, list, tuple, set, dict)."a" in "apple" # True 3 in [1,2,3] # True
1.7 Type Conversion (Casting)
-
Implicit Conversion (Coercion): Python automatically converts a smaller type to a larger type in mixed-type expressions.
result = 10 + 3.5 # int (10) implicitly converted to float (10.0) # result is 13.5 (float) -
Explicit Conversion: Using constructor functions to convert between types.
| Function | Converts To | Example | | :--- | :--- | :--- | |
int(x)| Integer |int("10")→10;int(3.9)→3| |float(x)| Floating-point |float("3.14")→3.14| |str(x)| String |str(42)→"42"| |bool(x)| Boolean |bool(0),bool(""),bool(None)→False; others →True| -
Common Pitfalls & Errors:
-
ValueError: Invalid literal for conversion.int("3.5")orint("hello"). -
TypeError: Incompatible operation between types (e.g.,"hello" + 5). -
float('inf'),float('nan')represent infinity and Not-a-Number.
-
[!TIP] Exam Trap:
bool(0),bool(""),bool([]),bool(None)all evaluate toFalse. All other non-zero/non-empty values evaluate toTrue.
1.8 Basic String Operations
-
Concatenation:
+joins two strings."Py" + "thon" # "Python" -
Repetition:
*repeats a string."ha" * 3 # "hahaha" -
Indexing: Access single character using
[index]. Indices start at0. Negative indices count from end (-1is last).s = "Python" s[0] # 'P' s[-1] # 'n' -
Slicing:
[start:stop:step]. Extracts substring fromstart(inclusive) tostop(exclusive). Defaults:start=0,stop=len,step=1.s = "Python" s[1:4] # 'yth' s[:3] # 'Pyt' (start=0) s[3:] # 'hon' (stop=len) s[::2] # 'Pto' (every 2nd char) s[::-1] # 'nohtyP' (reverse) -
Common String Methods (Introduction):
-
.lower(),.upper(): Case conversion. -
.strip(): Remove leading/trailing whitespace. -
.split(sep): Split into list of substrings. -
.join(iterable): Join iterable of strings with this string as separator. -
.find(sub): Return lowest index ofsubor-1if not found. -
.replace(old, new): Replace occurrences. -
Formatted Strings:
-
.format():"Hello, {}".format(name) -
f-strings (Python 3.6+):
f"Hello, {name}"(preferred).
-
-
-
String Immutability: Strings cannot be modified in-place. Operations return new strings.
s = "hello" s[0] = "H" # TypeError: 'str' object does not support item assignment s = "H" + s[1:] # Correct: create new string
1.9 Writing Simple Programs
-
Problem-Solving Steps:
-
Analysis: Understand the problem, inputs, outputs, constraints.
-
Design: Plan algorithm (pseudocode, flowchart).
-
Implementation: Write Python code.
-
Testing: Run with various inputs, check for correctness.
-
-
Example Program Patterns:
-
Simple Calculator: Read two numbers and an operator (
+,-,*,/), perform operation, print result. -
Greeting Program:
input("Name: ")→print(f"Hello, {name}!"). -
Area/Perimeter Calculator: For rectangle (
length,width), circle (radius). Use formulas: Area =l*w, Circumference =2*π*r. -
Temperature Converter: Celsius to Fahrenheit:
F = (C * 9/5) + 32. Fahrenheit to Celsius:C = (F - 32) * 5/9.
-
1.10 Debugging and Common Errors
-
Syntax Errors: Caught by interpreter during parsing. Indentation, missing colon
:, unmatched parentheses/quotes.if x > 5 # SyntaxError: invalid syntax (missing colon) print(x) -
Runtime Errors (Exceptions): Occur during execution.
-
NameError: Name not found (e.g., undefined variable). -
TypeError: Incompatible operation (e.g.,"a" + 1). -
ValueError: Correct type but inappropriate value (e.g.,int("3.5")). -
ZeroDivisionError: Division/modulo by zero. -
IndexError: Sequence index out of range. -
KeyError: Dictionary key not found.
-
-
Logical Errors: Program runs but produces incorrect results. No error message. Hardest to find.
-
Basic Debugging Techniques:
-
Read the Traceback: The last line indicates error type and line number. Read from bottom up.
-
Print Debugging: Insert
print()statements to check variable values and program flow. -
Use an IDE Debugger: Set breakpoints, step through code, inspect variables (in VS Code/PyCharm).
-
Rubber Duck Debugging: Explain code line-by-line to someone (or something) else.
-
[!TIP] Golden Rule: The last line of a traceback is the actual error. The lines above show the call stack (where the error originated). Always start debugging there.