Introduction to Python Programming: Program Design, Variables, and Data Types
Course Administration and Logistics
- Teaching Assistant: Amna serves as the course teaching assistant and conducts the instructional session in place of Dr. Tebi (also referred to as Dr. Debbie).
- Class Schedule: No class is held on Friday due to Dr. Tebi's absence; the subsequent class convenes on Tuesday.
- Course Materials: Lecture presentation slides (PowerPoint) are uploaded to the learning management platform following class.
- Software Environment: Demonstrations, exercises, and assignments are executed using the IDLE development environment for Python on student laptops.
Program Design Process
- Cycle of Program Design: Program construction follows a recurring, multi-step engineering loop:
- Problem Comprehension: Understand the explicit requirements and constraints of the problem statement before writing code.
- Logic Formulation: Determine the algorithmic logic and decompose tasks into granular, sequential steps.
- Initial Code Implementation: Draft a simple program directly addressing the logic.
- Code Review and Syntax Error Checking: Review source code line-by-line to identify syntactic or typographical errors.
- Program Testing: Execute the program with test cases to evaluate correctness.
- Iterative Refinement: If errors, incorrect calculations, or unexpected outputs occur, repeat the cycle from problem re-analysis and logic adjustment.
- Definition: An algorithm is the logical blueprint and structured sequence of operational steps designed to execute a specified task prior to writing actual software code.
- Decomposition: Complex tasks are decomposed into smaller, sequential steps (referred to as "baby steps").
- Numeric Summation Example:
- Objective: Calculate the sum of two numbers.
- Algorithmic Procedure: Acquire two distinct numbers into memory, apply the addition operation to combine them, and record the resulting sum.
- Trip Planning Analogy:
- Formulating an algorithm directly mirrors planning an itinerary for travel.
- Step-by-step decisions include determining the geographical destination, arranging lodging accommodations, and sequencing specific daily activities.
- Constructing these procedural decisions in the mind establishes a definitive plan before undertaking travel, just as an algorithm establishes logical execution paths prior to coding.
Pseudocode
- Definition: Pseudocode is an informal, high-level description of an algorithm written in natural language rather than rigid programming syntax.
- Structural Properties:
- Syntax Rules: Pseudocode has no formal syntax rules or language constraints.
- Execution: It cannot be compiled, interpreted, or directly executed by a computer.
- Purpose: Serves as a thinking and design medium to record ideas and algorithmic logic plainly before translating them into a formal programming language such as Python.
Flowcharts and Graphical Logic
- Definition: A flowchart is a diagrammatic representation mapping the step-by-step logic, operational pathways, and control flow of a program.
- Standard Flowchart Shapes:
- Ovals (Terminal Symbols): Represent the boundary points of a program, explicitly marking the starting point (
Start) and ending point (End). - Parallelograms (Input/Output Symbols): Designate data input operations (accepting user inputs) and output operations (displaying or returning values).
- Rectangles (Processing Symbols): Designate calculations, arithmetic manipulations, and general operational data processing.
- Arrows (Flowlines): Indicate the precise sequential direction and control flow connecting geometric symbols.
- Flowchart Case Study: Sum of Two Numbers:
- An oval symbol initiates execution at
Start. - A parallelogram symbol records the first numeric input (e.g., inputting the value 3).
- A second parallelogram symbol records the second numeric input.
- A rectangle symbol performs the arithmetic addition of the two inputs.
- A terminating oval concludes the sequence at
End.
- Flowchart Case Study: Gross Pay Calculation:
- An oval symbol designates
Start. - Directed arrows lead to a parallelogram accepting initial input parameters (such as hours worked).
- A subsequent parallelogram accepts the secondary input parameter (such as hourly pay rate).
- A rectangle (processing block) computes gross pay by calculating the product of the inputs.
- A parallelogram displays the computed gross pay as output.
- A final oval symbol terminates the routine at
End.
- Three Core Architectural Stages:
- Input: The computer receives data, values, or instructions from an external source or user.
- Processing: The central processing system executes operations on the input using pre-written functions, mathematical calculations, or logical conditions.
- Output: The computer returns the processed result to the user or an external interface.
- Command Line Execution:
- Submitting
print("hello world") into the IDLE interactive shell provides an input instruction. - The Python interpreter executes the internal operations associated with the
print function. - The terminal renders the text
hello world as the program output.
Functions, Arguments, and Order of Execution
- Function: A modular, pre-written block of code engineered to execute a specific, reusable operation (such as the standard
print() command). - Argument: The specific data value, literal, or variable passed into a function call for processing (e.g., in
print("hello world"), the text "hello world" serves as the argument). - Order of Execution:
- Statements in standard procedural scripts execute strictly in sequential order from top to bottom as they appear in the file.
- Sequential Example:
- Statement 1:
print("programming") - Statement 2:
print("is") - Statement 3:
print("fun") - Output appears consecutively on individual lines:
programming, followed by is, followed by fun.
Strings, String Literals, and Quotation Rules
- String: A sequential arrangement of characters treated as textual data within a computer program.
- String Literal: The explicit character sequence as typed directly into source code, surrounded by matching quotation marks.
- Quoting Conventions:
- Strings may be enclosed using either single quotation marks (
'...') or double quotation marks ("..."). - Enclosure Matching: The opening quote delimiter must strictly match the closing quote delimiter. A string initialized with a single quotation mark must terminate with a single quotation mark; a string initialized with a double quotation mark must terminate with a double quotation mark.
- Definition: Non-executable explanatory notes placed within program code to explain logic, intent, and functionality.
- Syntax: Prefixed by the hash symbol (
#). Any character sequence appearing after # on that line is ignored by the Python interpreter and excluded from output. - Practical Applications:
- Clarifies programmatic intent for external reviewers, graders, and collaborating engineers.
- Differentiates idiosyncratic algorithmic implementations when multiple students construct distinct programmatic solutions for identical assignments.
- End-line Comments: Annotations positioned at the immediate end of an executable line of code to explain the specific operational purpose of that line.
Variables, Expressions, and Assignment Operators
- Definition: A named identifier referencing a specific storage location in computer memory, utilized to store, retrieve, and manipulate data.
- Reference Mechanism: A variable references (points to) the memory location holding the underlying value.
- Assignment Statement Architecture:
- Syntax structure:
variable = expression (e.g., age = 29). - Left-Side Requirement: The receiving variable identifier must strictly reside on the left side of the assignment operator.
- Assignment Operator: The single equals symbol (
=) evaluates the expression on the right and binds the variable on the left to that resulting value. - Expression: The value, literal, or mathematical operation evaluated on the right-hand side (e.g., the numeric literal 29).
- Operational Rules:
- Variable identifiers must never be enclosed within quotation marks; enclosing an identifier in quotes converts it into a string literal.
- Variables can be supplied directly as arguments inside function calls (e.g.,
print(age)). - A variable cannot be referenced, evaluated, or read until a value has been formally assigned to initialize it.
- Multiple Assignment Syntax:
- Python permits assigning multiple variables simultaneously in a single line using comma delimiters.
- Structure:
x, y, z = 0, 1, 2 assigns x=0, y=1, and z=2.
Variable Naming Rules and Identifiers
- Syntactic Rules for Python Identifiers:
- Reserved Keywords: Variable names cannot duplicate reserved Python keywords.
- Whitespace: Whitespace is strictly forbidden within identifiers; underscores (
_) must be used to separate multi-word names. - Starting Character: An identifier must begin with an alphabetic letter (a-z, A-Z) or an underscore (
_). An identifier cannot start with a numeric digit. - Subsequent Characters: Following the initial character, identifiers may incorporate alphabetic letters, numeric digits, and underscores.
- Case Sensitivity: Identifiers are strictly case-sensitive (
age, Age, and AGE represent three entirely distinct memory references).
- Evaluation of Variable Name Examples:
units_per_day: Valid identifier; contains only alphabetic characters and separating underscores.- CamelCase or Capitalized Names (e.g., containing capital letters like
O): Valid identifier; Python supports mixed-case letters. 3DGraph: Invalid identifier; begins with a numeric digit (3). To make it legal, it must begin with a letter or underscore (e.g., ThreeDGraph or D3Graph).June1997: Valid identifier; starts with an alphabetic letter, permitting subsequent digits.mixture#3: Invalid identifier; contains the illegal character #, which Python interprets as a comment delimiter rather than a valid identifier character.
Dynamic Typing, Variable Reassignment, and Garbage Collection
- Outputting Multiple Items:
- The
print() function accepts multiple comma-separated items within a single call, printing them sequentially on one line separated by spaces (e.g., print(age, "years old")).
- Variable Reassignment:
- Variable bindings are dynamic and can be redirected to reference alternative values during runtime execution.
- Incremental Reassignment Example:
- Initial assignment: age=29
- Reassignment expression: age=age+1
- Resulting value: age=30
- Dynamic Typing Across Data Types:
- A variable initially bound to an integer can be subsequently reassigned to reference a string literal or float.
- Garbage Collection:
- When a variable is reassigned to a new object, the previous value reference is severed.
- Values in memory with zero active variable references become "garbage values."
- Python automatically identifies and reclaims memory occupied by dereferenced objects through an internal background process called garbage collection.
- Example: If x=99 is subsequently updated such that x references a string, the integer 99 becomes an orphaned object collected by the garbage collector.
Python Data Types and Type Inspection
- Data Type Classification: Dictates how values are classified, stored in physical memory, and operated upon by programmatic expressions.
- Primary Data Types:
- Integer (
int): Whole numbers lacking fractional or decimal components, including positive and negative numbers (e.g., 1, 2, 3, 4, 5, 25, 29, 99). - Float (
float): Real numbers containing a fractional component represented by a decimal point (e.g., 25.5, 0.0). - String (
str): Sequential character text enclosed in single or double quotes (e.g., "years old").
- Intrinsic Rule: Any written number lacking a decimal point is evaluated as an integer; any number written with a decimal point is evaluated as a float.
- Type Inspection Function:
- The built-in
type() function returns the exact data type of any literal or variable reference. - Example: Executing
type(25) yields <class 'int'>; executing type(25.5) yields <class 'float'>.
Assignment 1 Specifications and Submission Guidelines
- Assignment Identifier: Assignment 1 (initially misspoken as Assignment 3).
- Due Date: September 15 / September 5 (designated as "due on 15, September 5").
- Required Steps:
- Launch the IDLE application.
- Create a new file editor script.
- Write a Python program that executes a
print() function displaying any chosen statement.
- File Naming Convention:
- Files must strictly be saved using the specified format:
[Student Name] assignment 1. - Grade Penalty Warning: Failure to adhere to this precise file naming standard will result in direct point deductions.
Questions & Discussion
- Presentation Slide Distribution:
- Student Query: Inquiries regarding where and when the lecture PowerPoint presentation would be accessible.
- Response: The slides will be uploaded to the course site later by the professor.
- Variable Selection for Personal Data:
- Prompt: Which variable representation among the presented options is best structured to store a name?
- Response: The final option, positioning a valid identifier on the left without quotation marks.
- Character Legality in Identifiers:
- Prompt: Why is the identifier
mixture#3 illegal in Python? - Response: Identifiers are strictly restricted to letters, numbers, and underscores; special characters such as the hash symbol (
#) are prohibited.
- Data Type Classification Drill:
- Prompt: What data type categorizes the value 25?
- Response: Integer (
int), because it contains no decimal point. - Prompt: What data type categorizes the value 25.5?
- Response: Float (
float), because it contains a decimal point. - Prompt: What data type categorizes the literal
"years old"? - Response: String (
str), because it consists of text enclosed in quotes. - Prompt: What data type categorizes the values 99 and 29?
- Response: Integer (
int).
- Variable Reassignment Drill:
- Prompt: Given an initial assignment of V1=99 followed by a reassignment of V1=0, what value outputs when executing
print(V1)? - Response: The output is 0, because the most recent assignment overwrites the variable reference.
- Hands-On Practical Validation:
- Students engaged in interactive IDLE execution, testing the
print() function with arbitrary strings, querying object types using the type() command, and demonstrating variable reassignment on their laptops.