CSR101Semester 1 • 4 CreditsSpecialization Subjects

Python Programming

This course develops proficiency in Python programming, covering core syntax, control structures, functions, recursion, strings, data structures, object-oriented programming, modules, packages, exception handling, numerical and matrix operations, and data analysis and visualization using Python libraries.

6 Units • Notes • Model Answers • MCQs
Select Course Unit (6 Units)
Active: Unit 1
Unit 1:Python Environment Setup, Core Syntax, Types & Expressions
15 min read•High-Yield Unit Guide

Python Environment Setup, Core Syntax, Types & Expressions

Unit 1 Exam Focus & Core Takeaways

Review the core definitions, standard architectures, and syntax patterns below. Pay special attention to sections highlighted with bullet points for your mid-term and end-term subjective questions.

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

  1. Interactive REPL (Read-Eval-Print Loop):
    • Launched by typing python or python3 in the system terminal.
    • Ideal for quick prototyping, mathematical calculations, and exploring library APIs interactively.
  2. 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.
  3. 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:

  1. May contain uppercase and lowercase letters (a-z, A-Z), digits (0-9), and underscores (_).
  2. Must never begin with a digit (e.g., 2count is illegal; count2 is valid).
  3. Case-sensitive: totalScore, TotalScore, and TOTALSCORE are three distinct identifiers.
  4. 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: PascalCase or CapWords (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)).
python
a = [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 -5 and 256. For integers in this range, x = 100 and y = 100 will return x is y -> True. However, you should never rely on is for 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 (2imes1092 imes 10^9) or 64-bit (9imes10189 imes 10^{18}), Python integers dynamically expand memory allocation to store numbers of arbitrary size:

python
big_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") ightarrow ightarrow 125
  • float("3.14") ightarrow ightarrow 3.14
  • str(950) ightarrow ightarrow "950"
  • bool(0) ightarrow ightarrow False, bool("text") ightarrow ightarrow True

6. Operators and Expression Evaluation

Arithmetic Operators

OperatorDescriptionExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/True / Float Division7 / 23.5 (Always returns float!)
//Floor / Integer Division7 // 23 (Rounds down to nearest integer)
%Modulus (Remainder)7 % 21
**Exponentiation (Power)2 ** 38

[!IMPORTANT]
In Python 3, the / operator always produces a float, even when dividing evenly (e.g., 4 / 2 yields 2.0, not 2). 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 True ightarrow ightarrow False).
  • Short-Circuit Evaluation:
    • In A and B: If A is falsy, B is never evaluated.
    • In A or B: If A is truthy, B is never evaluated.

Membership and Identity Operators

  • Membership: in and not in test whether a value resides in a sequence:
    python
    vowels = "aeiou"
    print('e' in vowels)      # True
    print('z' not in vowels)  # True
    
  • Identity: is and is not test whether two identifiers point to the identical memory address (a is b).

Operator Precedence (Highest to Lowest)

  1. Parentheses: ( )
  2. Exponentiation: **
  3. Unary signs: +x, -x, ~x
  4. Multiplication, Division, Floor Div, Modulus: *, /, //, %
  5. Addition, Subtraction: +, -
  6. Bitwise shifts: <<, >>
  7. Bitwise AND: &
  8. Bitwise XOR: ^
  9. Bitwise OR: |
  10. Comparisons, Identity, Membership: ==, !=, <, >, is, in
  11. Boolean NOT: not
  12. Boolean AND: and
  13. Boolean OR: or

7. Input, Output & Modern String Formatting

Console Output: The print() Function

python
print(*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 ' ').
python
print("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:

python
name = "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 float x to n decimal 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

python
import 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

python
marks = 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:
variable=value_if_trueifconditionelsevalue_if_false\text{variable} = \text{value\_if\_true} \quad \mathbf{if} \quad \text{condition} \quad \mathbf{else} \quad \text{value\_if\_false}

python
status = "Adult" if age >= 18 else "Minor"

10. Common Pitfalls and Developer Best Practices

Anti-Pattern / PitfallUnderlying CauseCorrect Architectural Solution
Mixing Tabs and SpacesDifferent editors render tab widths inconsistentlyConfigure IDE to insert 4 spaces per tab press; adhere strictly to PEP 8.
Forgetting input() is strinput() + input() concatenates strings ("10" + "20" = "1020")Explicitly wrap inputs in int() or float(): int(input()).
Using is for Value Equalityis tests physical memory address identity, not content equalityAlways use == for comparisons; reserve is exclusively for None (x is None).
Unexpected Float DivisionExpecting / to return an integer as in C/JavaUse // for floor integer division when whole numbers are required.
Floating Point InaccuraciesIEEE 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 *, /, //, %.
  • not beats and, which beats or.
  • // rounds down toward negative infinity (-7 // 2 evaluates 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="".