Unit 1: Python Environment Setup, Core Syntax, Types & Expressions
1. Introduction: History, Design Philosophy & Execution Model
Python is an interpreted, high-level, dynamically typed, multi-paradigm programming language created by Guido van Rossum at the Centrum Wiskunde & Informatica (CWI) in the Netherlands and released in February 1991. The language was deliberately architected to emphasize code readability, human expressiveness, and programmer productivity through clean syntax and uncluttered visual layout.
The Zen of Python (PEP 20)
Guido's core architectural tenets are encapsulated in the Zen of Python (accessible by running import this in any Python shell):
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Readability counts.
- There should be one-- and preferably only one --obvious way to do it.
Python Compilation and Execution Pipeline
Unlike purely compiled languages (such as C++ or Rust) that translate source directly to native machine code, or purely interpreted languages that parse text on every cycle, Python employs a two-stage hybrid compilation model:
CODE+--------------------------------------------------------------------------+ | CPYTHON EXECUTION PIPELINE | +--------------------------------------------------------------------------+ | 1. Source Code (.py) -> Human-readable Python script | | | | | v (Bytecode Compilation) | | 2. Python Bytecode (.pyc) -> Platform-independent intermediate code | | stored in __pycache__/ | | | | | v (Virtual Machine Execution) | | 3. Python Virtual Machine -> PVM interprets bytecode into native | | (PVM / CPython Runtime) CPU machine instructions in real time | +--------------------------------------------------------------------------+
Major Python Implementations
- CPython: The reference, standard implementation written in C. It uses the Global Interpreter Lock (GIL) to synchronize thread access to memory.
- PyPy: High-performance Python with a Just-In-Time (JIT) compiler, often speeding up numerical loops by 4x to 10x.
- Jython: Python runtime targeting the Java Virtual Machine (JVM).
- IronPython: Python runtime integrated with Microsoft .NET CLR.
2. Development Environments and Execution Modes
Python programs can be authored and executed across multiple interactive and scripted environments.
Development Environments
- Interactive REPL (Read-Eval-Print Loop):
- Launched by typing
pythonorpython3in the system terminal. - Ideal for quick prototyping, mathematical calculations, and exploring library APIs interactively.
- Launched by typing
- Integrated Development Environments (IDEs):
- Visual Studio Code (VS Code): Lightweight, highly extensible editor equipped with Microsoft's Pylance/Pyright language server, debugging tools, and Git integration.
- PyCharm (JetBrains): Professional full-featured Python IDE providing advanced static code analysis, refactoring tools, and Django/Flask support.
- Data Science Platforms:
- Anaconda: Comprehensive scientific distribution pre-packaging CPython alongside NumPy, Pandas, SciPy, Matplotlib, and the Conda package/environment manager.
- Jupyter Notebook: Interactive web-based computational document platform pairing live code execution cells with rich markdown, LaTeX equations, and rendered visual plots.
Script Execution and the Shebang Line
In Unix-like operating systems (Linux/macOS), adding a shebang on the first line specifies the interpreter path:
python#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print("Python execution initiated.")
To run the script via terminal:
python3 app.py
3. Core Syntax, Indentation & Identifiers
Indentation as Block Scoping
Unlike languages such as C, Java, or JavaScript that delineate code blocks using curly braces { ... }, Python utilizes whitespace indentation to define structural control blocks.
- Standard (PEP 8): Exactly 4 spaces per indentation level.
- Tabs vs. Spaces: Never mix tab characters and spaces in the same file. In Python 3, mixing tabs and spaces raises a fatal
TabError: inconsistent use of tabs and spaces in indentation.
python# Valid block indentation:
score = 88
if score >= 90:
grade = "A"
print("Excellent work!")
elif score >= 80:
grade = "B"
print("Very good performance.")
else:
grade = "C"
Identifiers and Naming Rules
An identifier is a name assigned to a variable, function, class, module, or package:
- May contain uppercase and lowercase letters (
a-z,A-Z), digits (0-9), and underscores (_). - Must never begin with a digit (e.g.,
2countis illegal;count2is valid). - Case-sensitive:
totalScore,TotalScore, andTOTALSCOREare three distinct identifiers. - Cannot match reserved keywords (
if,elif,else,while,for,def,class,import,return,try,except,with,pass,break,continue,yield,lambda,is,in,and,or,not,None,True,False).
PEP 8 Naming Conventions
- Variables & Functions:
snake_case(e.g.,calculate_tax(),user_account_id). - Constants:
UPPER_SNAKE_CASE(e.g.,MAX_RETRIES,DEFAULT_TIMEOUT). - Classes:
PascalCaseorCapWords(e.g.,StudentRecord,DatabaseConnection).
4. Variables, Dynamic Typing & Memory Model
Dynamic and Strong Typing
- Dynamically Typed: Variable identifiers do not possess static types; values (objects) do. A variable is merely a named reference pointer pointing to an object in heap memory:
python
x = 42 # x references an int object x = "LPU BTech" # x now references a str object (perfectly valid!) - Strongly Typed: Python does not perform implicit type coercion between incompatible types (unlike JavaScript):
python
# '5' + 5 # Throws TypeError: can only concatenate str (not "int") to str
Identity (id()) vs. Equality (==)
Every Python entity is an object possessing an identity, a type, and a value:
id(obj): Returns the unique integer memory address of the object in CPython.type(obj): Returns the data type class of the object.==(Value Equality): Compares whether two objects hold the same semantic contents.is(Identity Equality): Compares whether two references point to the exact same physical memory address (id(a) == id(b)).
pythona = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (Identical contents)
print(a is b) # False (Two distinct list objects allocated in heap memory)
[!NOTE]
Small Integer Caching: CPython pre-allocates and caches an internal array of singleton integer objects for values between-5and256. For integers in this range,x = 100andy = 100will returnx is y -> True. However, you should never rely onisfor numerical comparison; always use==.
5. Primitive Data Types in Python 3
CODE+--------------------------------------------------------------------------+ | PYTHON 3 DATA TYPES | +--------------------------------------------------------------------------+ | Numeric Types: | | - int: Arbitrary precision signed integers (e.g., 42, -999, 10**100) | | - float: IEEE 754 double-precision 64-bit floating point (e.g., 3.14) | | - complex: Complex numbers with real and imaginary parts (e.g., 3+4j) | | | | Boolean Type: | | - bool: Subclass of int with exactly two constants: True (1) / False(0)| | | | Text Sequence: | | - str: Immutable sequence of Unicode code points (e.g., "Hello World")| | | | Null Object: | | - NoneType: Singleton object 'None' denoting absence of a value | +--------------------------------------------------------------------------+
Arbitrary Precision of Integers
In Python 3, integers have unbounded precision. Unlike C/Java where integers overflow at 32-bit () or 64-bit (), Python integers dynamically expand memory allocation to store numbers of arbitrary size:
pythonbig_num = 2 ** 100
# 1267650600228229401496703205376 (No integer overflow occurs!)
Floating Point Representation
Floats are IEEE 754 double precision (64 bits). Because binary floats cannot represent base-10 decimals exactly, rounding artifacts occur:
0.1 + 0.2 evaluates to 0.30000000000000004.
To achieve exact financial calculations, standard library from decimal import Decimal is used.
Type Conversion (Casting)
int("125")125float("3.14")3.14str(950)"950"bool(0)False,bool("text")True
6. Operators and Expression Evaluation
Arithmetic Operators
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 5 | 15 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication | 10 * 5 | 50 |
/ | True / Float Division | 7 / 2 | 3.5 (Always returns float!) |
// | Floor / Integer Division | 7 // 2 | 3 (Rounds down to nearest integer) |
% | Modulus (Remainder) | 7 % 2 | 1 |
** | Exponentiation (Power) | 2 ** 3 | 8 |
[!IMPORTANT]
In Python 3, the/operator always produces a float, even when dividing evenly (e.g.,4 / 2yields2.0, not2). Use//if integer result is required.
Comparison / Relational Operators
==(equal),!=(not equal),<(less),<=(less or equal),>(greater),>=(greater or equal).- Chained Comparisons: Python uniquely supports intuitive mathematical chaining:
python
x = 15 if 10 < x < 20: # Evaluates as: (10 < x) and (x < 20) print("x is strictly between 10 and 20.")
Logical Operators and Short-Circuiting
and: Returns first falsy operand, or the last operand if all are truthy.or: Returns first truthy operand, or the last operand if all are falsy.not: Inverts boolean value (not TrueFalse).- Short-Circuit Evaluation:
- In
A and B: IfAis falsy,Bis never evaluated. - In
A or B: IfAis truthy,Bis never evaluated.
- In
Membership and Identity Operators
- Membership:
inandnot intest whether a value resides in a sequence:pythonvowels = "aeiou" print('e' in vowels) # True print('z' not in vowels) # True - Identity:
isandis nottest whether two identifiers point to the identical memory address (a is b).
Operator Precedence (Highest to Lowest)
- Parentheses:
( ) - Exponentiation:
** - Unary signs:
+x,-x,~x - Multiplication, Division, Floor Div, Modulus:
*,/,//,% - Addition, Subtraction:
+,- - Bitwise shifts:
<<,>> - Bitwise AND:
& - Bitwise XOR:
^ - Bitwise OR:
| - Comparisons, Identity, Membership:
==,!=,<,>,is,in - Boolean NOT:
not - Boolean AND:
and - Boolean OR:
or
7. Input, Output & Modern String Formatting
Console Output: The print() Function
pythonprint(*objects, sep=' ', end='
', file=sys.stdout, flush=False)
sep: String inserted between multiple printed objects (default is single space' ').end: String appended at the conclusion of output (default is newline' ').
pythonprint("2026", "10", "15", sep="-") # Output: 2026-10-15
print("Loading", end="...")
print("Done!") # Output: Loading...Done!
Console Input: The input() Function
The input(prompt) function displays a prompt, halts execution until the user presses Enter, and always returns input as a string (str).
python# CRITICAL: Must explicitly cast input to numeric types!
user_age = int(input("Enter your age: "))
print(f"In 5 years, you will be {user_age + 5}.")
Modern String Formatting (F-Strings)
Introduced in Python 3.6 (PEP 498), Formatted String Literals (F-Strings) provide the fastest, cleanest string interpolation syntax:
pythonname = "Aditya"
cgpa = 9.4285
# F-string with precision formatting and expressions:
message = f"Student: {name.upper()} | CGPA: {cgpa:.2f} | Status: {'Passed' if cgpa >= 5.0 else 'Failed'}"
print(message)
# Output: Student: ADITYA | CGPA: 9.43 | Status: Passed
Legacy alternatives:
str.format():"Hello, {}!".format(name)%formatting:"Hello, %s!" % name
8. Built-in Math Functions and the math Module
Standard Built-in Math Functions
abs(x): Absolute value of a number.round(x, n): Rounds floatxtondecimal places (uses round-half-to-even bankers rounding).min(a, b, ...),max(a, b, ...): Finds minimum or maximum values.pow(base, exp, [mod]): Efficient modular exponentiation.divmod(a, b): Returns tuple(a // b, a % b).
The Standard math Module
pythonimport math
# Mathematical Constants
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# Functions
print(math.sqrt(64)) # 8.0
print(math.floor(3.85)) # 3 (Rounds down to nearest integer)
print(math.ceil(3.12)) # 4 (Rounds up to nearest integer)
print(math.factorial(5)) # 120 (5 * 4 * 3 * 2 * 1)
print(math.gcd(48, 18)) # 6 (Greatest Common Divisor)
print(math.sin(math.radians(90))) # 1.0
9. Basic Decision-Making Structures
The if...elif...else Construct
pythonmarks = 76
if marks >= 90:
grade = "O (Outstanding)"
elif marks >= 80:
grade = "A+ (Excellent)"
elif marks >= 70:
grade = "A (Very Good)"
elif marks >= 60:
grade = "B+ (Good)"
else:
grade = "Reappear"
Conditional Expressions (Ternary Operator)
Python provides a compact inline syntax for assignment based on a condition:
pythonstatus = "Adult" if age >= 18 else "Minor"
10. Common Pitfalls and Developer Best Practices
| Anti-Pattern / Pitfall | Underlying Cause | Correct Architectural Solution |
|---|---|---|
| Mixing Tabs and Spaces | Different editors render tab widths inconsistently | Configure IDE to insert 4 spaces per tab press; adhere strictly to PEP 8. |
Forgetting input() is str | input() + input() concatenates strings ("10" + "20" = "1020") | Explicitly wrap inputs in int() or float(): int(input()). |
Using is for Value Equality | is tests physical memory address identity, not content equality | Always use == for comparisons; reserve is exclusively for None (x is None). |
| Unexpected Float Division | Expecting / to return an integer as in C/Java | Use // for floor integer division when whole numbers are required. |
| Floating Point Inaccuracies | IEEE 754 precision issues (0.1 + 0.2 != 0.3) | Use math.isclose(a, b) for float equality, or use the Decimal module for money. |
11. Quick Revision & Exam Summary
Essential Operators & Precedence
**has higher precedence than*,/,//,%.notbeatsand, which beatsor.//rounds down toward negative infinity (-7 // 2evaluates to-4).
Truth Value Testing Cheat Sheet
- Falsy Values in Python:
None,False,0,0.0,0j,"",[],(),{},set(),range(0). - All other values are Truthy.
String Formatting Formats
- F-String:
f"{value:.2f}"(Recommended). - Print kwargs:
sep=",",end="".