Fundamentals of Python Programming - Data Types and Variables

Course Overview & Introduction to Python

  • Institutional Context:

    • Institution: National University Science & Technology (NUST)

    • Department: CAT

    • Course Module: Fundamentals of Python Programming — Data Types and Variables (Week02 + Week03)

    • Term: Fall 2026/2027

  • Definition of Python:

    • Python is a general-purpose, interpreted, interactive, object-oriented, and high-level programming language.

  • Historical Background:

    • Created by Guido van Rossum between the years 19851985 and 19901990.

    • The name "Python" was derived from the British television comedy series Monty Python's Flying Circus, not from the reptile.

    • Officially released to the public in the year 20002000.

Key Characteristics & Features of Python

  • Key Characteristics:

    • Interpreted: Source code is executed line-by-line directly by the interpreter. Programs do not require pre-compilation into machine code prior to execution.

    • Interactive: Developers can interact directly with the Python shell prompt (>>>), allowing instant testing of code fragments and rapid learning.

    • Object-Oriented: Fully supports Object-Oriented Programming (OOP) paradigms, structuring applications around reusable objects and class definitions.

    • Beginner-Friendly: Features clean syntax and high readability, making it ideal for entry-level programmers as well as professional environments.

  • Core Features:

    • Easy to Learn: Simple syntax utilizing a minimalistic set of reserved keywords.

    • Easy to Maintain: Highly readable code base makes maintenance and debugging straightforward.

    • Portable: Cross-platform compatibility allows Python programs to run on Windows, Linux, and macOS without modifying source code.

    • Interpreted Nature: Eliminates explicit compilation steps, executing scripts directly.

    • Free and Open-Source: Distributed freely; source code can be viewed, edited, and redistributed without licensing fees.

    • Scalable: Provides robust structure suited for both simple scripting tasks and complex enterprise-level software systems (offering better structural architecture than standard shell scripts).

    • System Integration & Interoperability: Seamlessly integrates with code written in C, C++, Java, JavaScript, and ActiveX components.

  • Application Domains:

    • Web Development

    • Artificial Intelligence (AI) and Machine Learning (ML)

    • Data Analysis and Visualization

    • Automation and System Scripting

    • Cybersecurity

    • Scientific Computing

Interpreter Execution Modes

  • Interactive Mode:

    • Commands are entered and evaluated individually line-by-line at the interactive primary prompt (>>>).

    • Results are displayed immediately on screen upon pressing Enter.

    • Advantages: Provides instant output; ideal for experimenting with syntax, testing expressions, and learning.

    • Disadvantages: Code written in interactive mode is not saved permanently to disc; unsuited for building full applications.

    • Primary Use Cases: Learning Python fundamentals, quick mathematical evaluations, debugging isolated code fragments.


Python Interactive Mode Prompt
  • Interactive Mode Worked Example:

    • Command 1: a = 10

    • Command 2: b = 20

    • Command 3: a + b

    • Shell Output: 3030

  • Script Mode:

    • Source code is written in a standalone file saved with a .py file extension (e.g., program.py).

    • The saved file is executed as a unified script by the Python interpreter.

    • Advantages: Programs are permanently stored, highly reusable, easily modified, and structured for large applications.

    • Disadvantages: Does not produce line-by-line real-time feedback during typing; requires saving and explicit execution steps.

    • Primary Use Cases: Production application development, complex software scripting, real-world commercial projects.

Python Environments & Setup

  • IDLE (Integrated Development Learning Environment):

    • A graphical user interface (GUI) developed entirely in Python.

    • Bundled natively with standard Python software distributions.

    • Core Features:

    • Multi-window text editor equipped with syntax highlighting.

    • Intelligent auto-completion and automated indentation.

    • Integrated Python shell window for executing commands and displaying output.


IDLE Shell Window Interface
  • Python Standard Distribution Setup:

    • Official source downloads provide setup executable packages (e.g., Python 3.13.0 64-bit installer for Windows).

    • Default installation directory path: C:\Users\MyLingPC\AppData\Local\Programs\Python\Python313.

    • Configuration options include checking administrative privilege access (py.exe) and adding python.exe to the system environment PATH variable.

  • PyCharm IDE Setup:

    • Developed by JetBrains specifically tailored for professional Python software development.

    • Offers advanced code editing, automated syntax highlighting, context-aware code completion, and on-the-fly code inspection.

    • PyCharm Community Edition is provided completely free as an open-source IDE.

    • Official download location: https://www.jetbrains.com/pycharm/download/?section=windows


PyCharm IDE Workspace

Python Syntax & First Program Workflow

  • Fundamental Syntax Rules:

    • Statements are separated by line breaks; each line represents a single statement by default.

    • Standard statements do not require terminating semicolons (;).

    • Code readability and structure are prioritized.

  • Script Execution Procedure in IDLE:

    • Step 1: Open IDLE multi-window text editor.

    • Step 2: Write the Python script.

    • Step 3: Save the file with a .py extension (e.g., first_program.py).

    • Step 4: Press the F5 function key to execute the script.

    • Step 5: Review execution output printed inside the IDLE shell window.

  • Hardcoded Integer Addition Script:

```python rest

Simple Python program to add two integers with hardcoded values

num1 = 10 # First integer number num2 = 15 # Second integer number

Add the two numbers

sum = num1 + num2

Display the result

print("The sum of", num1, "and", num2, "is", sum)

- **Program Trace & Output Explanation**:
  - Integer value `1010` is stored in variable `num1`.
  - Integer value `1515` is stored in variable `num2`.
  - The binary arithmetic addition operator `+` calculates `10+15=2510 + 15 = 25`, assigning the result to `sum`.
  - The `print()` function formats and outputs the combined arguments.
  - Program Console Output: `The sum of 10 and 15 is 25`


# Python Data Types

- **Data Type Definition**:
  - Defines the specific operational classification of data values assigned to variables.
  - Instructs Python how to allocate memory space and determines which mathematical or logical operations are permissible.

- **Built-in Data Types Reference**:
  - **`int`**:
    - Description: Stores positive or negative whole numbers without decimal places.
    - Example: `x = 10`
    - Real-Life Analogy: Human age, count of apples.
  - **`float`**:
    - Description: Stores real numbers containing explicit decimal points.
    - Example: `y = 3.14`
    - Real-Life Analogy: Atmospheric temperature, body weight measurement.
  - **`str`**:
    - Description: Stores text strings or sequences of characters wrapped in single or double quotes.
    - Example: `name = "Alice"`
    - Real-Life Analogy: Individual's name, written sentence, text message.
  - **`bool`**:
    - Description: Stores Boolean logical state values (`True` or `False`).
    - Example: `is_on = True`
    - Real-Life Analogy: Binary light switch position (on/off).
  - **`list`**:
    - Description: Stores an ordered and mutable (changeable) collection of items.
    - Example: `fruits = ["apple", "banana"]`
    - Real-Life Analogy: Grocery shopping list.
  - **`tuple`**:
    - Description: Stores an ordered and immutable (unchangeable) collection of items.
    - Example: `colors = ("red", "blue")`
    - Real-Life Analogy: Fixed RGB color values.
  - **`dict`**:
    - Description: Stores data organized as key-value mapping pairs.
    - Example: `person = {"name": "Tom"}`
    - Real-Life Analogy: Telephone directory, student academic record database.


# Python Variables & Identifier Naming Rules

- **Variable Concept**:
  - A named reference bound to a specific memory storage location holding a dynamic value.
  - Values stored inside variables can be altered dynamically during runtime.

- **Purposes of Variables**:
  - Temporarily retain intermediate computation data.
  - Execute numerical and logical calculations.
  - Reuse values across multiple program procedures.
  - Enhance code clarity, maintainability, and structural flexibility.

- **Strict Naming Rules for Identifiers**:
  1. Must begin with a letter (`a–z`, `A–Z`) or an underscore character (`_`).
  2. Cannot begin with a numerical digit (e.g., `1num` is **invalid**).
  3. Must contain only alphanumeric characters and underscores (`a–z`, `A–Z`, `0–9`, `_`).
  4. Special characters and symbols (such as `@`, `$`, `%`, `-`) are strictly prohibited (e.g., `num@1` is **invalid**; `num_1` is **valid**).
  5. Spaces are strictly disallowed anywhere within the identifier name (e.g., `num 1` is **invalid**).
  6. Identifiers are strictly case-sensitive (`x` and `X` represent two separate variables).
  7. Standard reserved Python keywords cannot be used as variable names.

- **Variable Assignment Examples**:
  - `x = 10` (Assigns integer `1010` to identifier `x`)
  - `name = "Ali"` (Assigns string `"Ali"` to identifier `name`)


# Python Keywords

- **Definition & Purpose**:
  - Reserved words built directly into Python syntax possessing fixed system meanings.
  - Keywords formulate structural execution logic and control program flow, conditional branching, iterations, scoping, and exception structures.
  - Cannot be assigned as custom variable names, function names, or program identifiers.

- **Complete Listing of Python Keywords (3333 Total)**:

| | | | | |
|---|---|---|---|---|
| `False` | `class` | `finally` | `is` | `return` |
| `None` | `continue` | `for` | `lambda` | `try` |
| `True` | `def` | `from` | `nonlocal` | `while` |
| `and` | `del` | `global` | `not` | `with` |
| `as` | `elif` | `if` | `or` | `yield` |
| `assert` | `else` | `import` | `pass` | |
| `break` | `except` | `in` | `raise` | |


# Statements, Expressions, Input & Output

- **Core Syntactic Concepts**:
  - **Python Statement**: An instruction executed by Python to perform an explicit action.
    - Example: `x = 10` (Assigns value `1010` to `x`).
  - **Python Expression**: A combination of literals, variables, and operators evaluated to compute a resultant value.
    - Example: `x + 5` (Evaluates to `1515` when `x = 10`).
  - **Python Input**: Obtains data typed by the end-user during program execution via `input()`.
    - String Input Example: `name = input("Enter name: ")`
    - Type Cast Integer Input Example: `age = int(input("Enter age: "))`
    - Type Cast Float Input Example: `price = float(input("Enter price: "))`
  - **Python Output**: Displays processed results or variable values onto the terminal console output via `print()`.
    - Example: `print(name)`


# Computer Architecture & Practical Programs

- **Hardware Processing & Memory Allocation Model**:
  - Data flow sequence: Input Device (Keyboard) `→\rightarrow` CPU Processing `→\rightarrow` Output Device.
  - RAM Storage Allocation: Storage locations in system memory are tagged with variable labels holding raw values (e.g., `num1` holds `100100`, `num2` holds `500500`, `sum` holds calculated output `600600`).

![Hardware Input Processing Storage Output Model](https://assets.knowt.com/pdf-flow-prod/34fbb14f-7b73-4a69-a889-c73cad918124-figures/3.png)

- **User-Input Integer Addition Script**:

python rest num1 = int(input("Enter num1")) num2 = int(input("Enter num2")) sum = num1 + num2 print("Sum=", sum)

- **Rectangle Area Computation Script**:

python rest length = int(input("Enter length")) width = int(input("Enter width")) Area = length * width print("Area =", Area)

  - **Terminal Trace**:
    - User enters length: `10`
    - User enters width: `20`
    - Computation: `Area=10×20=200\text{Area} = 10 \times 20 = 200`
    - Console Output: `Area = 200`

- **Circle Area Computation Script**:

python rest r = int(input("Enter r")) Area = 3.14 * r * r print("Area=", Area)

  - **Terminal Trace**:
    - User enters radius `r`: `2`
    - Computation: `Area=3.14×2×2=12.56\text{Area} = 3.14 \times 2 \times 2 = 12.56`
    - Console Output: `Area= 12.56`

- **Student Grade Average Script**:

python rest name = (input("enter your name:")) course1 = int(input("enter your grade:")) course2 = int(input("enter your grade:")) average = ((course1 + course2) / 2) print("average=", average)

  - **Terminal Trace**:
    - User enters name: `AlBatool`
    - User enters course 1 grade: `90`
    - User enters course 2 grade: `80`
    - Computation: `average=90+802=85.0\text{average} = \frac{90 + 80}{2} = 85.0`
    - Console Output: `average= 85.0`


# Python Comments

- **Definition & Rules**:
  - Comments are non-executable text lines inserted into source code, ignored entirely by the interpreter.
  - Single-line comments begin explicitly with the hash symbol (`#`).
  - Example:

python rest

This is a comment explaining code logic

print("Hello Python")

- **Primary Applications**:
  - Enhancing source code readability for human programmers.
  - Documenting step-by-step program logic and business workflows.
  - Assisting team collaboration.
  - Temporarily disabling specific code lines during debugging.


# Code Block Indentation Rules

- **Definition & Purpose**:
  - Indentation refers to leading whitespace characters placed at the beginning of a code line.
  - Python uses indentation levels instead of curly brackets (`{}`) to delineate block scope boundaries for functions, loops, and conditional constructs.

- **Standard Indentation Practices**:
  - Standard convention prescribes using **44 spaces** (or single tab key) per indentation level.
  - All statements within the exact same structural block must share identical leading spacing.
  - Omitting indentation or inconsistently indenting statements generates an immediate syntax error (`IndentationError`).

- **Correct Indentation Example**:

python rest if 5 > 3: print("Yes, 5 is greater than 3") print("This line is part of the if block")

print("This line is outside the if block") ```

Complete Operator Reference

  • Arithmetic Operators:

    • + (Addition): Adds numerical values (x + y).

    • - (Subtraction): Subtracts right operand from left operand (x - y).

    • * (Multiplication): Multiplies values (x * y).

    • / (Division): Divides left operand by right operand, producing float outcome (x / y).

    • % (Modulus): Returns remainder of division operation (x % y).

    • ** (Exponentiation): Raises left operand to power of right operand (xyx^y, written as x ** y).

    • // (Floor Division): Divides and truncates fractional decimal parts down to nearest whole integer (x // y).

  • Comparison (Relational) Operators:

    • == (Equal): Returns True if both operands are equal (x == y).

    • != (Not Equal): Returns True if operands are not equal (x != y).

    • > (Greater Than): Returns True if left operand exceeds right operand (x > y).

    • < (Less Than): Returns True if left operand is less than right operand (x < y).

    • >= (Greater Than or Equal To): Returns True if left operand is greater than or equal to right operand (x >= y).

    • <= (Less Than or Equal To): Returns True if left operand is less than or equal to right operand (x <= y).

  • Logical Operators:

    • and: Evaluates to True if both individual expressions are true (x < 5 and x < 10).

    • or: Evaluates to True if at least one expression is true (x < 5 or x < 4).

    • not: Inverts boolean logical output; returns False if evaluated statement is true (not(x < 5 and x < 10)).

  • Assignment & Compound Assignment Operators:

Operator

Example

Equivalent Expansion

=

x = 5

x = 5

+=

x += 3

x = x + 3

-=

x -= 3

x = x - 3

*=

x *= 3

x = x * 3

/=

x /= 3

x = x / 3

%=

x %= 3

x = x % 3

//=

x //= 3

x = x // 3

**=

x **= 3

x = x ** 3

&=

x &= 3

x = x & 3

|=

x |= 3

x = x | 3

^=

x ^= 3

x = x ^ 3

>>=

x >>= 3

x = x >> 3

<<=

x <<= 3

x = x << 3

Questions & Discussion

  • Session Dialogue Summary:

    • Final review covering environment installations, basic variable operations, data types, arithmetic operators, user inputs, output formatting, and indentation block structures.

    • Concluding remarks and module closure for Weeks 02 and 03.