Python Programming Fundamentals: Variables, Data Types, Expressions, and Operators
Variables and Assignment Statements
- Purpose of a Variable: A variable is used to store data in memory so that a program can reference, manipulate, and reuse that stored information at a later point in execution.
- Assignment Statement Definition: An assignment statement creates a variable and binds it to reference a specific value or the evaluated output of an expression.
- Assignment Operator: Python uses the equal sign
= as the assignment operator. - Structural Rules of Assignment Statements:
- Left Side: Must exclusively be a target variable name being created or updated.
- Right Side: Must be a value, string literal, existing variable, or expression that produces a value.
- Flow of Operation: Evaluates the right-hand side first, then assigns the resulting value to the variable specified on the left-hand side.
- Concrete Assignment Examples:
num=10: Creates a new variable named num and assigns it the integer value 10.A=10.23: Creates a new variable named A and assigns it the floating-point decimal value 10.23.hello_world=’hello world’: Creates a variable named hello_world and assigns it the text string literal 'hello world' wrapped in quotation marks.name=’willy’: Creates a variable named name and assigns it the string literal 'willy'.age=18: Creates a variable named age and assigns it the integer value 18.
- Analysis of Invalid Assignment Statements:
- Invalid Syntax Example:
4=b - Reason for Failure: The left side of an assignment statement must be a valid variable identifier. An integer literal like
4 cannot act as a variable target. - Distinguishing Mathematics from Programming: While 4=b is a valid symmetric equality statement in mathematics, it is completely invalid in Python, Java, and other imperative programming languages because the assignment operator
= represents a directional right-to-left data assignment. - Correct Formulation:
b=4 assigns the value 4 to the variable b.
Variable Naming Rules and Rules Evaluation
- Rule 1 (Reserved Keywords): A variable name cannot be a Python keyword. Keywords (such as
True or False) are reserved words with explicit built-in operational meanings in the language. - Rule 2 (Whitespace Exclusion): Variable names cannot contain spaces under any circumstances.
- Rule 3 (First Character Constraints): The first character of a variable name must be an alphabetic letter (A-Z, a-z) or an underscore character
_. It cannot start with a numeric digit. - Rule 4 (Subsequent Character Constraints): After the initial character, variable names may consist of letters, numeric digits, or underscores.
- Valid Example:
A5 (starts with an alphabetic letter, followed by a digit). - Invalid Example:
5A (starts with a numeric digit, violating Rule 3).
- Rule 5 (Case Sensitivity): Variable identifiers are case-sensitive. For instance,
A and a are recognized as two distinct variables in memory. - Naming Conventions and Best Practices:
- Functional Meaning: Variable names should clearly describe their intended purpose or stored state (e.g.,
is_running to indicate whether a vehicle is operating). - Contextual Use: Simple identifiers like
a or x may be acceptable for basic classroom demonstrations, but real-world industry practice mandates descriptive names over non-descriptive single-letter names.
- Evaluation of Specific Identifier Examples:
b_4=5: Valid. Starts with a letter, contains an underscore, and ends with a digit without spaces._b4=5: Valid. Starts with an allowed underscore _, followed by a letter and a digit.my variable=5: Invalid. Contains a space between my and variable.2a=5: Invalid. Begins with the numeric digit 2.a2=5: Valid. Starts with a letter a before using the digit 2.my_underscore_8=5: Valid. Starts with a letter and incorporates underscores and a trailing digit without spaces.
Right-Side Referencing and Variable Reassignment
- Variables on the Right-Hand Side:
- Statement:
a=num - Execution Details: The interpreter reads the variable
num on the right side, retrieves the stored value referenced by num (such as 10), and assigns that retrieved value to variable a on the left side. - Equivalence: If
num stores 10, executing a=num is functionally identical to executing a=10. - Variable Target: Only the variable on the left side (
a) is updated or created. The value of num remains unchanged.
- Self-Referencing Variable Reassignment:
- Statement:
num=num+1 - Operational Flow:
- Evaluates the right-hand side first by reading the current value of
num (e.g., 10). - Performs the addition operation
10+1, resulting in 11. - Updates
num on the left side, replacing its old value 10 with 11.
- Distinction from Algebra: Mathematically, num=num+1 has no solution. In programming, it represents a state update where the variable's new value becomes its previous value incremented by 1.
Printing Variables vs. String Literals
- Evaluation of Print Statements:
print(num): Evaluates the variable num and outputs its underlying value (e.g., outputs 10).print(num+1): Evaluates the expression num+1 and outputs the computed result (e.g., outputs 11).print(’num’): Enclosing num in single quotation marks defines it as a string literal. The interpreter outputs the literal text characters num rather than evaluating a variable.
- Demonstration of Print Outputs:
- Setup:
num=10 - Running
print(num) displays 10. - Running
print(’num’) displays num.
- Numeric Content inside String Literals:
- Any characters inside quotation marks, such as
'10.23', are classified as string literals (str), not numeric data types, regardless of whether the content consists of numbers.
- Complex Text Reference Example:
- Variable Assignment:
name=’Mercer University’ - Executing
print(name) evaluates the variable name and outputs Mercer University. - Executing
print(’name’) evaluates the string literal and outputs name.
Variable Lifecycle and Reassignment Rules
- Prerequisite Creation Rule: A variable must be created via an assignment statement before it can be referenced or used in any program expression.
- Invalid Uninitialized Usage: The statement
num=1+b produces an error if b has not been previously instantiated. - Correct Instantiation Steps:
- Create variable
b via assignment: b=0 or b=num. - Reference
b in subsequent updates: num=num+b.
- Overwriting Variable Values: Python variables are dynamic and can hold updated values across sequential assignment statements.
- Initial assignment:
num=10 binds num to 10. - Subsequent assignment:
num=100 overwrites the reference, updating num to 100.
Python Built-in Data Types
- Significance of Data Types: Data types inform the interpreter about the structure of stored data, governing which specific operational methods and functions can be applied to them.
- Integer (
int):- Represents whole numbers without fractional components (e.g., −5, 0, 10).
- Supports standard mathematical and arithmetic operations.
- Floating-Point (
float):- Represents continuous real numbers containing decimal points (e.g., 10.23, 34.5).
- Supports decimal arithmetic operations.
- String (
str):- Represents an ordered sequence of text characters bounded by quotation marks (e.g.,
'willy', 'Mercer University'). - Supports textual operations such as string concatenation (joining strings together).
- Boolean (
bool):- Represents truth values consisting of exactly two possible outcomes:
True and False. - Formatting Requirement: Must begin with capitalized letters
T and F as keywords. - Binary State: Corresponds directly to a single binary bit state (e.g., on/off, positive/negative charge).
Structure of Expressions and Arithmetic Operators
- Definition of an Expression: A combination of variables, numeric values, and operators that evaluates to a single output value.
- Operational Evaluation: The interpreter replaces any variables within an expression with their current stored values and executes the calculations to compute a final single value.
- Basic Expression Examples:
5+6: Combines two literal integer values using addition to evaluate to 11.34.5a+b: If a=10 and b=20, the numerator evaluates to 30, resulting in 34.530≈0.869565.
- Standard Arithmetic Operators:
- Addition:
+ - Subtraction: −
- Multiplication:
∗ (Asterisk. Symbolic multiplication sign; letters like x must not be used). - Division:
/ (Forward slash. Performs division, returning a floating-point output). - Exponentiation:
∗∗ (Two consecutive asterisks. Computes base raised to a power, e.g., x∗∗y represents xy). - Floor Division:
// (Divides and truncates the decimal portion to return an integer quotient).
Modulus (Remainder) Operator Mechanics and Applications
- Modulus Operator Symbol:
% - Mathematical Definition: Calculates the integer remainder resulting from division between two operands.
- Step-by-Step Remainder Calculation for A(modB):
- Determine the largest integer multiple of B that is less than or equal to A.
- Subtract that multiple from A to obtain the remaining value.
- Step-by-Step Numerical Examples:
- 4(mod3)=1: The largest multiple of 3 below 4 is 3. Remaining: 4−3=1.
- 5(mod3)=2: The largest multiple of 3 below 5 is 3. Remaining: 5−3=2.
- 6(mod3)=0: 6 is fully divisible by 3. Remaining: 6−6=0.
- 7(mod3)=1: The largest multiple of 3 below 7 is 6. Remaining: 7−6=1.
- 8(mod3)=2: The largest multiple of 3 below 8 is 6. Remaining: 8−6=2.
- 10(mod4)=2: The largest multiple of 4 below 10 is 8. Remaining: 10−8=2.
- Remainder Limit Law: For any modulus operation A(modB), the resulting remainder R is strictly bounded by 0≤R<B.
- Parity Testing Algorithm (Odd vs. Even Checking):
- Executing N(mod2) evaluates whether an integer N is odd or even.
- If N(mod2)=0: The number is even (divisible by 2 with zero remainder).
- If N(mod2)=1: The number is odd (leaves a remainder of 1 when divided by 2).
Operator Precedence Rules
- Precedence Hierarchy:
- Parentheses
(): Expressions enclosed within parentheses evaluate first. - Exponentiation
∗∗: Computed prior to multiplication, division, or addition. - Multiplication
∗, Division /, and Modulus %: Equal priority tier; computed left-to-right. - Addition
+ and Subtraction −: Lowest priority tier; computed left-to-right.
- Step-by-Step Walkthrough Example:
- Statement:
(3+5)×32 (written in code as (3 + 5) * 3 ** 2) - Step 1 (Parentheses): Evaluate (3+5)=8. Expression simplifies to 8×32.
- Step 2 (Exponentiation): Evaluate 32=9. Expression simplifies to 8×9.
- Step 3 (Multiplication): Evaluate 8×9=72.
- Final Evaluated Result:
72.
Foundational Learning Methodology and Course Logistics
- Three-Question Analytical Framework for Programming Concepts:
- What is it? (Define the syntax and structural mechanics of the concept).
- Why do we need it? (Understand the underlying purpose and computational necessity).
- How do we use it? (Apply correct syntax to implement the concept in code).
- Assignment Logistics:
- Posting Schedule: First programming assignment posted by Friday at the latest.
- Submission Window: Students receive a 2 week submission period from the date of posting (due on Friday two weeks after release).