Four Number Systems

Core Python Data Types and Variable Assignment

  • Variable Definition and Mechanics:

    • A variable functions as a named container that reserves space to store a value in the computer's physical memory.

    • Variables are declared and initialized using the assignment operator (=).

    • Python automatically detects and dynamically binds the data type based on the value assigned to the variable; explicit type declaration is not required.

    • Once stored in memory, a variable's value can be retrieved, reused, and reassigned at any point throughout the execution of a program.

    • Storage Box Analogy: A variable operates like a physical labeled storage box. The identifier or label attached to the exterior represents the variable name, while the item placed inside represents the stored data value.


Variable Assignment Storage Box Metaphor
  • The Four Fundamental Python Data Types:

    • Integer (int):

    • Represents positive or negative whole numbers without any fractional or decimal component, including zero (00).

    • Primary programmatic purpose: Discrete counting and whole-quantity tracking.

    • Example literals: 42, -7, 0, 7, -12, 25.

    • Identification syntax: Calling type(age) when age = 14 returns <class 'int'>.

    • Floating-Point Number (float):

    • Represents numeric values containing a decimal point, capable of expressing fractional quantities.

    • Primary programmatic purpose: Continuous measurement, sensor data, and prices.

    • Example literals: 3.14, -0.5, 2.0, 5.0, 1.62, 12.50.

    • A trailing decimal point with no following digit denotes a float: 8. is functionally equivalent to 8.0.

    • Scientific notation is automatically evaluated as a float: 1e3 evaluates to the floating-point value 1000.01000.0, and 2.5e-2 evaluates to 0.0250.025.

    • Identification syntax: Calling type(height) when height = 1.62 returns <class 'float'>.

    • String (str):

    • Represents textual sequences enclosed within matching quotation marks.

    • Enclosure options: Single quotes ('), double quotes ("), or triple quotes (''' or """).

    • Example literals: "Ahmed", "Sara", "Dubai", "Hi", 'A', "42", "True", 'False', "3.14".

    • Numeric String Distinction: Numeric characters enclosed in quotes (e.g., "42", "25") are processed as text data, not numeric literals.

    • Identification syntax: Calling type(name) when name = "Ahmed" returns <class 'str'>.

    • Boolean (bool):

    • Represents truth values in logic systems.

    • Restricted to exactly two literal states: True and False.

    • Strict syntax requirement: Must begin with an uppercase letter. Uncapitalized identifiers (true, false) or all-caps identifiers (TRUE, FALSE) trigger a runtime NameError because Python parses them as variable names.

    • Identification syntax: Calling type(is_enrolled) when is_enrolled = True returns <class 'bool'>.

  • Formatted String Output (f-Strings):

    • F-strings allow inline interpolation of expressions and variable values directly inside strings.

    • Example implementation: python name = "Sara" age = 15 print(f"{name} is {age}") # Outputs: Sara is 15 &nbsp;&nbsp;&nbsp;&nbsp;

Literals, Type Rules, and Type Conversions

  • Literal Definition:

    • A literal is a concrete, fixed value typed directly into the source code rather than derived from a computation or variable reference.

  • Type Checking and Conversion Functions:

    • type(object): Evaluates and returns the exact data type of the argument.

    • int(x): Converts a valid numeric string or floating-point value to an integer (truncates decimal values towards zero).

    • float(x): Converts a valid integer or numeric string into a floating-point number.

    • str(x): Converts any given Python object or literal into its textual string representation.

  • The Golden Rule of User Input:

    • The built-in input() function unconditionally returns a string (str), regardless of whether the user inputs purely numeric digits.

    • Numeric inputs must be explicitly wrapped in int() or float() prior to participating in arithmetic calculations.

  • Type Mixing and Coercion Behaviors:

    • Mixed Arithmetic (int + float):

    • Adding or multiplying an integer with a float implicitly promotes the integer to a float, producing a float result.

    • Example: 3+1.53 + 1.5 evaluates to 4.54.5.

    • Example: 8.+28. + 2 evaluates to 10.010.0 with a type of <class 'float'>.

    • Division Operator (/):

    • The single slash (/) indicates true division and always yields a float, even when the division divides evenly with zero remainder.

    • Example: 6/26 / 2 evaluates to 3.03.0, not 33.

    • Example: 7/27 / 2 evaluates to 3.53.5.

    • Example: 9/39 / 3 evaluates to 3.03.0.

    • String Concatenation (+):

    • The + operator joins two strings together end-to-end without injecting whitespace.

    • Example: "5" + "5" evaluates to "55".

    • Combining a string and an integer via + (e.g., "5" + 5 or "Age: " + 21) raises an immediate runtime TypeError.

    • Resolution: Convert the integer explicitly ("Age: " + str(21) →\rightarrow "Age: 21") or utilize a comma within a print() call.

    • String Repetition (*):

    • Multiplying a string by an integer repeats the string value that specified number of times.

    • Example: "Ha" * 3 evaluates to "HaHaHa".

    • Example: "Hi!" * 3 evaluates to "Hi!Hi!Hi!".

    • Parentheses order controls whether multiplication or concatenation occurs:

      • str(5) * 2 repeats the text "5" twice, yielding "55".

      • str(5 * 2) multiplies the integers first (5×2=105 \times 2 = 10) and converts the product, yielding "10".

    • Evaluation Example with Variables:

    • Given x = "7" and y = 2:

      • int(x) + y evaluates to 7+2=97 + 2 = 9.

      • x * y evaluates to "7" * 2 = "77".

      • x + str(y) evaluates to "7" + "2" = "72".

  • Boolean Numeric Equivalency and Truth Comparisons:

    • Underneath the abstraction, Python booleans behave as integers where True is numerically equivalent to 11 and False is numerically equivalent to 00.

    • Arithmetic operations: True + True evaluates to 1+1=21 + 1 = 2.

    • Relational comparisons: True > False evaluates to True (1>01 > 0); True == 1 evaluates to True.

  • Value Equality vs. Type Equality:

    • Comparing values across different numeric types: 5 == 5.0 evaluates to True because their numeric magnitude is equivalent.

    • Comparing types directly: type(5) == type(5.0) evaluates to False because <class 'int'> is not identical to <class 'float'>.

    • Comparing numeric types to strings: "10" == 10 evaluates safely to False without raising an error. Cross-type equality tests return False, whereas cross-type arithmetic triggers a TypeError.

  • Floating-Point Representation Imprecision:

    • Testing equality on fractional float calculations can yield unexpected results: print(0.1 + 0.2 == 0.3) outputs False.

    • Hardware binary representation cannot store specific decimal fractions precisely, introducing minuscule rounding errors where 0.1+0.20.1 + 0.2 computes to 0.300000000000000040.30000000000000004.

String Quotation Rules, Multiline Strings, and Escape Sequences

  • The Three Core Quotation Rules:

    • Rule 1: Quotes Must Match:

    • A string initialized with a single quote must be terminated with a single quote ('...').

    • A string initialized with a double quote must be terminated with a double quote ("...").

    • Mismatched quotes (e.g., 'Hello" or "Hello') cause an immediate compilation SyntaxError.

    • Rule 2: Use the Opposite Quote Type for Enclosure:

    • When the internal string content requires an apostrophe or single quote, wrap the outer string in double quotes: "It's Monday", "It's fun", "I can't wait".

    • When the internal string content requires double quotation marks, wrap the outer string in single quotes: 'She said "Hi"', 'The "best" day'.

    • Rule 3: Triple Quotes for Multiline and Mixed Quotes:

    • Triple quotation blocks ("""...""" or '''...''') permit strings to span multiple consecutive lines without explicit line breaks.

    • Triple quotes accommodate both single quotes/apostrophes and double quotes concurrently without requiring escape characters: '''She said "It's fun"'''.

  • The Semantic Role of Quotes:

    • Quotes instruct the Python interpreter to treat text as a literal string.

    • Executing print(Hello) without quotation marks causes Python to evaluate Hello as a variable identifier, triggering a NameError: name 'Hello' is not defined if uninitialized. Conversely, print("Hello") prints literal text.

  • Escape Sequences (Backslash Mechanics):

    • The backslash (\) serves as an escape operator, signaling to the interpreter that the subsequent character possesses a specialized syntactic meaning rather than a literal value.

    • Supported escape sequences:

    • : Inserts a line feed (newline). Multiple consecutive instances (`

) generate an empty blank line. *\t: Inserts a horizontal tab (large alignment whitespace). *\`: Escapes the backslash itself to display a single literal backslash (crucial for filesystem paths). * \': Displays an internal single quote safely within a single-quoted string (e.g., 'It\'s fun'). * \": Displays an internal double quote safely within a double-quoted string (e.g., "Say \"Hi\"").

  • Escaped apostrophe application: When constrained to outer single quotes, a phrase containing an apostrophe must use escaping: print('He said "It\'s over"').

    • Character Counting with len():

  • The built-in len() function counts the exact number of characters in a string.

  • Every escape sequence counts strictly as 11 character, not 22.

  • Whitespace characters and newline characters each register as 11 character.

  • Worked calculation: Given s = "Hi A\\B":

    • Character 1: H

    • Character 2: i

    • Character 3: (newline)

    • Character 4: A

    • Character 5: \\ (single backslash)

    • Character 6: B

    • len(s) returns exactly 66.

    • Raw Strings (r"..."):

  • Prepending the prefix letter r or R to an opening quote creates a raw string literal.

  • Raw strings completely suppress escape sequence processing, treating every backslash literally.

  • Example: print(r"C: ew\table") outputs C: ew\table directly rather than converting into a newline and \t into a tab.

    • Example: print(r"C: ew") outputs C: ew.

    • Escape Precedence in Identifiers:

  • In print("Tab\\t"), the paired backslashes (\\) resolve into a single literal backslash, leaving the subsequent t as an ordinary alphanumeric character. The output is Tab\t.

Python Number Systems, Base Representations, and Conversions


Four Number Systems Overview
  • Base (Radix) Principles:

    • The base of a numerical system dictates the total inventory of unique positional digits utilized before rolling over into an additional column.

    • In any base bb, the positional value 10 represents the numeric value of the base itself: 10 in binary is 22, 10 in octal is 88, 10 in decimal is 1010, and 10 in hexadecimal is 1616.

  • The Four Major Number Systems:

    • Decimal (Base 10):

    • Permitted digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

    • Primary domain: Standard human counting and arithmetic.

    • Binary (Base 2):

    • Permitted digits: 0, 1.

    • Primary domain: Digital computing, low-level architecture, memory states (transistor on/off states).

    • Octal (Base 8):

    • Permitted digits: 0, 1, 2, 3, 4, 5, 6, 7.

    • Primary domain: Compact computing representations, operating system file permissions (e.g., POSIX permissions).

    • Hexadecimal (Base 16):

    • Permitted characters: Digits 0–9 and letters A–F (case-insensitive: A=10, B=11, C=12, D=13, E=14, F=15).

    • Primary domain: Memory address representation, byte-level debugging, HTML/CSS hex color codes.

  • Counting Across Number Systems (00 to 1515):

    • Decimal 00 ↔\leftrightarrow Binary 0000 ↔\leftrightarrow Octal 0 ↔\leftrightarrow Hex 0

    • Decimal 11 ↔\leftrightarrow Binary 0001 ↔\leftrightarrow Octal 1 ↔\leftrightarrow Hex 1

    • Decimal 22 ↔\leftrightarrow Binary 0010 ↔\leftrightarrow Octal 2 ↔\leftrightarrow Hex 2

    • Decimal 33 ↔\leftrightarrow Binary 0011 ↔\leftrightarrow Octal 3 ↔\leftrightarrow Hex 3

    • Decimal 44 ↔\leftrightarrow Binary 0100 ↔\leftrightarrow Octal 4 ↔\leftrightarrow Hex 4

    • Decimal 55 ↔\leftrightarrow Binary 0101 ↔\leftrightarrow Octal 5 ↔\leftrightarrow Hex 5

    • Decimal 66 ↔\leftrightarrow Binary 0110 ↔\leftrightarrow Octal 6 ↔\leftrightarrow Hex 6

    • Decimal 77 ↔\leftrightarrow Binary 0111 ↔\leftrightarrow Octal 7 ↔\leftrightarrow Hex 7

    • Decimal 88 ↔\leftrightarrow Binary 1000 ↔\leftrightarrow Octal 10 ↔\leftrightarrow Hex 8

    • Decimal 99 ↔\leftrightarrow Binary 1001 ↔\leftrightarrow Octal 11 ↔\leftrightarrow Hex 9

    • Decimal 1010 ↔\leftrightarrow Binary 1010 ↔\leftrightarrow Octal 12 ↔\leftrightarrow Hex A

    • Decimal 1111 ↔\leftrightarrow Binary 1011 ↔\leftrightarrow Octal 13 ↔\leftrightarrow Hex B

    • Decimal 1212 ↔\leftrightarrow Binary 1100 ↔\leftrightarrow Octal 14 ↔\leftrightarrow Hex C

    • Decimal 1313 ↔\leftrightarrow Binary 1101 ↔\leftrightarrow Octal 15 ↔\leftrightarrow Hex D

    • Decimal 1414 ↔\leftrightarrow Binary 1110 ↔\leftrightarrow Octal 16 ↔\leftrightarrow Hex E

    • Decimal 1515 ↔\leftrightarrow Binary 1111 ↔\leftrightarrow Octal 17 ↔\leftrightarrow Hex F

  • Positional Place Value Calculations:

    • Binary Place Values (2n2^n): Values increase by powers of 22 (8,4,2,18, 4, 2, 1):

    • Converting 1011 to decimal: (1×8)+(0×4)+(1×2)+(1×1)=8+0+2+1=11(1 \times 8) + (0 \times 4) + (1 \times 2) + (1 \times 1) = 8 + 0 + 2 + 1 = 11.

    • Converting 11010 to decimal: (1×16)+(1×8)+(0×4)+(1×2)+(0×1)=16+8+0+2+0=26(1 \times 16) + (1 \times 8) + (0 \times 4) + (1 \times 2) + (0 \times 1) = 16 + 8 + 0 + 2 + 0 = 26.

    • Octal Place Values (8n8^n): Values increase by powers of 88 (64,8,164, 8, 1):

    • Converting 17 to decimal: (1×8)+(7×1)=8+7=15(1 \times 8) + (7 \times 1) = 8 + 7 = 15.

    • Converting 26 to decimal: (2×8)+(6×1)=16+6=22(2 \times 8) + (6 \times 1) = 16 + 6 = 22.

    • Hexadecimal Place Values (16n16^n): Values increase by powers of 1616 (256,16,1256, 16, 1):

    • Converting 1A to decimal: (1×16)+(10×1)=16+10=26(1 \times 16) + (10 \times 1) = 16 + 10 = 26.

    • Converting 16 to decimal: (1×16)+(6×1)=16+6=22(1 \times 16) + (6 \times 1) = 16 + 6 = 22.

    • Converting FF to decimal: (15×16)+(15×1)=240+15=255(15 \times 16) + (15 \times 1) = 240 + 15 = 255.

  • Manual Decimal to Binary Conversion (Repeated Division by 2):

    • Procedure: Divide the decimal number repeatedly by 22, record the integer quotient and the remainder, and continue until the quotient reaches 00. Read the remainders from bottom to top (last remainder becomes the most significant bit).

    • Worked example for decimal 1313:

    • Step 1: 13÷2=613 \div 2 = 6, remainder 11

    • Step 2: 6÷2=36 \div 2 = 3, remainder 00

    • Step 3: 3÷2=13 \div 2 = 1, remainder 11

    • Step 4: 1÷2=01 \div 2 = 0, remainder 11

    • Reading remainders bottom-to-top yields 1101.

    • Check: 8+4+0+1=138 + 4 + 0 + 1 = 13.

  • Python Literals and Base Conversions:

    • Literal Prefixes:

    • 0b or 0B: Binary prefix (e.g., 0b1011 evaluates to 1111; 0b101 evaluates to 55).

    • 0o or 0O: Octal prefix (e.g., 0o17 evaluates to 1515; 0o10 evaluates to 88).

    • 0x or 0X: Hexadecimal prefix (e.g., 0xA evaluates to 1010; 0xFF evaluates to 255255).

    • Integer Storage Behavior:

    • Values assigned using base prefixes are stored internally as standard int types.

    • The print() function automatically renders integers in standard base 10 decimal format: print(0b101, 0o17, 0xA) outputs 5 15 10.

    • Numbers expressed in different bases with identical magnitude compare as equal: 0b1010 == 10 evaluates to True.

    • Writing digits without a prefix (e.g., 10110) creates a decimal integer (10,11010,110). Enclosing them in quotes ("10110") creates a string.

    • Invalid digits within a prefix (e.g., 0o19 or 0b102) trigger a SyntaxError.

    • Conversion Functions:

    • bin(n): Converts an integer to a binary string prefixed with '0b' (e.g., bin(13) returns '0b1101'; bin(6) returns '0b110').

    • oct(n): Converts an integer to an octal string prefixed with '0o' (e.g., oct(8) returns '0o10'; oct(255) returns '0o377').

    • hex(n): Converts an integer to a lowercase hexadecimal string prefixed with '0x' (e.g., hex(255) returns '0xff'; hex(31) returns '0x1f'; hex(64) returns '0x40'; hex(13) returns '0xd').

    • int(string, base): Parses a string in a specified base into a decimal integer: int("1010", 2) returns 1010.

  • Base Detectives Numerical Equivalents:

    • Decimal 1313 →\rightarrow Binary 1101, Octal 15, Hex D

    • Decimal 2525 →\rightarrow Binary 11001, Octal 31, Hex 19

    • Decimal 255255 →\rightarrow Binary 11111111, Octal 377, Hex FF

    • Decimal 6464 →\rightarrow Binary 1000000, Octal 100, Hex 40

  • Real-World Hexadecimal Application (RGB Color Channels):

    • Hex color codes decompose into three distinct 2-digit channels: #RRGGBB.

    • Each hex pair represents an 88-bit value spanning 00 to 255255.

    • Example #FF8000: Red channel 0xFF = 255, Green channel 0x80 = 128, Blue channel 0x00 = 0, producing orange.

Operators, Evaluation Order, and Augmented Assignments

  • Arithmetic Operators and Behaviors:

    • + (Addition), - (Subtraction), * (Multiplication).

    • / (True Division): Always returns a float, even for whole quotients (8/2=4.08 / 2 = 4.0; 9/3=3.09 / 3 = 3.0).

    • // (Floor Division): Divides and rounds down towards negative infinity, discarding fractional remainders. Returns an integer if both arguments are integers (29//6=429 // 6 = 4; 5//2=25 // 2 = 2).

    • % (Modulus / Remainder): Returns the remainder of division (2929 % 6 = 5).

    • Floor division and modulus operate as a complementary pair: n // d yields total full groups, while n % d yields left-over remnants (used in partitioning problems such as packaging goods into cartons or loading vans).

    • ** (Exponentiation): Computes powers (2∗∗5=322 ** 5 = 32).

  • Comparison and Logical Operators:

    • Comparison operators: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to).

    • Comparison expressions evaluate strictly to a boolean (True or False). Example: 5 >= 5.0 evaluates to True.

    • Logical operators: not, and, or.

    • Evaluation: 5 > 3 and 2 > 4 evaluates to True and False, which yields False.

    • Chained comparisons: Expressions such as a == b == c evaluate as (a == b) and (b == c).

  • Operator Precedence (High to Low Hierarchy):

    • Level 1: Parentheses ( ) (innermost evaluated first).

    • Level 2: Exponentiation ** (evaluated strictly right-to-left / right-associative).

    • Example: 2 ** 3 ** 2 evaluates as 2 ** (3 ** 2) = 2 ** 9 = 512. It does not evaluate as (2 ** 3) ** 2 = 64.

    • Level 3: Multiplication *, True Division /, Floor Division //, Modulus % (evaluated left-to-right).

    • Level 4: Addition +, Subtraction - (evaluated left-to-right).

    • Level 5: Relational and comparison operators (<, <=, >, >=, ==, !=).

    • Level 6: Logical operators (not, then and, then or).

  • Step-by-Step Expression Tracing Example:

    • Expression: r = 20 - 6 / 3 * 2 + 1

    • Step 1 (Division): 6/3=2.06 / 3 = 2.0

    • Step 2 (Multiplication): 2.0∗2=4.02.0 * 2 = 4.0

    • Step 3 (Subtraction): 20−4.0=16.020 - 4.0 = 16.0

    • Step 4 (Addition): 16.0+1=17.016.0 + 1 = 17.0

    • Final result: 17.0 (evaluated as a float due to the presence of the division operator).

  • Augmented Assignment Operators:

    • Shorthand syntax combining arithmetic evaluation with in-place reassignment:

    • x += 3 →\rightarrow x = x + 3

    • x -= 3 →\rightarrow x = x - 3

    • x *= 3 →\rightarrow x = x * 3

    • x /= 3 →\rightarrow x = x / 3 (always converts x into a float)

    • x //= 3 →\rightarrow x = x // 3

    • x %= 3 →\rightarrow x = x % 3

    • x **= 3 →\rightarrow x = x ** 3

    • Reassignment sequence tracing:

    • Given n = 20:

      • n -= 2 updates n to 1818.

      • n /= 6 updates n to 3.03.0 (converted to float).

      • n += 1 updates n to 4.04.0.

      • print(n) outputs 4.0.

  • Comment Mechanics:

    • Comments begin with a hash symbol (#) and extend to the termination of the physical line.

    • Can exist as standalone lines or inline comments following valid code.

    • Python has no native block-comment syntax (such as /* ... */). Multiline commenting requires placing # at the start of each individual line.

    • A # enclosed inside a string literal is an ordinary character, not a comment: "Shelf #4" prints verbatim.

Built-in and User-Defined Functions


User-Defined Functions Architecture and Key Terms
  • Function Classification:

    • Built-in Functions: Functions integrated natively within the Python runtime environment, available without imports or manual definitions: print(), input(), int(), float(), str(), len(), type(), hex(), bin(), oct(), abs(), round().

    • User-Defined Functions: Custom code blocks defined and named by the developer using the def keyword to encapsulate logic for modular reuse.

    • Return Value Distinction: A function's return behavior does not dictate its classification. len() returns an integer value and is built-in; print() returns None and is also built-in.

    • Keywords vs. Functions: Reserved statements such as def, return, if, and for are language keywords, not functions. Function calls are distinguished by parentheses: name().

  • Anatomy of a User-Defined Function:

    • Header syntax: Initiated with def, followed by the function identifier, parentheses enclosing optional parameters, and a terminal colon (:).

    • Body: An indented block of statements containing the executable operations.

    • return statement: Halts execution within the function and passes a calculated value back to the call site.

    • Worked implementation: ```python def add(a, b): return a + b

    print(add(5, 3)) # Outputs: 8     ```

    • Component breakdown:

    • def: Keyword initiating the function definition.

    • add: Name assigned to the function.

    • a, b: Parameters defining the variables that receive data.

    • 5, 3: Arguments representing the literal values passed in.

    • return: Keyword transmitting the computed result (88).

  • Tracing Built-in Functions inside Code:

    • Procedure: Scan the target scope line by line, catalog every name(...) invocation, discard keywords, and cross out identifiers created via local def headers.

    • Worked tracing example: ```python def area(w, h): return w * h

    def show(): w = float(input("w: ")) print(area(w, 2))     ```

  • Built-in functions called inside show(): float(), input(), and print().

  • area() is excluded because it is a user-defined function.

  • return is excluded because it is a keyword.

Function Arguments, Parameters, and Execution Traps

  • Key Terminology:

    • Parameters: Variable names declared inside the function's def statement that act as placeholders to receive incoming values.

    • Arguments: Concrete values, variables, or expressions passed to the function within parentheses during an invocation.

  • Positional Arguments vs. Keyword Arguments:

    • Positional Arguments:

    • Arguments matched to function parameters based strictly on sequential order from left to right.

    • Implementation: ```python def student(name, age): print(name, age)

      student("Dhabya", 14)       ```

    • Mapping: name receives "Dhabya", and age receives 14.

  • Keyword Arguments:

    • Arguments explicitly bound to parameters using name=value syntax in the function call.

    • When all arguments use keywords, order does not matter.

    • Implementation: ```python def student(name, age): print(name, age)

      student(age=14, name="Dhabya")       ```

    • Mapping: Python correctly assigns "Dhabya" to name and 14 to age despite reversed placement.

  • Argument Validation Rules and Error Types:

    • Rule 1: Positional arguments must always precede keyword arguments:

    • Placing any positional argument after a keyword argument triggers a compilation SyntaxError.

    • Example: Calling f(a=1, 2) raises SyntaxError: positional argument follows keyword argument before execution starts.

    • Rule 2: A parameter cannot receive multiple values:

    • If a parameter is assigned a value positionally, passing that same parameter via keyword triggers a runtime TypeError.

    • Example: For def f(a, b): pass, calling f(1, a=5) raises TypeError: f() got multiple values for argument 'a'.

    • Rule 3: Argument count must match parameter count:

    • Passing too few or too many arguments raises a runtime TypeError.

  • Three-Step Validation Procedure for Function Invocations:

    • Step 1: Check argument sequencing. Does any positional argument follow a keyword argument? If yes, raise SyntaxError.

    • Step 2: Populate parameters sequentially from left to right with available positional arguments. Check whether any keyword argument refers to an already populated parameter. If yes, raise TypeError.

    • Step 3: Check whether all parameters have received exactly one value. If valid, execute the function.

  • Validation Case Scenarios with def f(a, b): pass:

    • f(1, 2): Valid execution (positional mapping).

    • f(b=2, a=1): Valid execution (keyword mapping).

    • f(a=1, 2): Fails with SyntaxError (positional argument follows keyword argument).

    • f(1, a=5): Fails with TypeError (parameter a receives multiple values).

Interactive Program Output: Formatting with print(), sep, and end

  • Default Parameters of print():

    • By default, print() is configured with sep=" " and end=" ".

    • sep: Defines the string delimiter placed between individual items passed to a single print() call.

    • end: Defines the trailing string printed after all items have been emitted.

  • Formatting Mechanics and Rules:

    • sep acts exclusively between items; it never precedes the first item or follows the final item.

    • end acts exclusively after the final item.

    • Setting end="" keeps the terminal output cursor on the same line, allowing subsequent print() statements to print contiguously.

    • Setting end="-" appends a hyphen instead of advancing to a new line.

    • Setting `end="

"` prints the current items, advances to the next line, and creates an extra blank line.

  • Spaces typed manually inside string literals are printed as-is, independent of the sep configuration.

  • Formatting output across multiple statements on "ONE line" requires modifying end away from " " on all print() calls except the last.

  • Worked Layout Tracing Example:

    • Code: python print("X", "Y", sep="+", end="=") print("Z") &nbsp;&nbsp;&nbsp;&nbsp;

    • Execution trace: print("X", "Y", sep="+") outputs X+Y. The end="=" parameter appends = without a newline. The subsequent print("Z") appends Z directly at the cursor.

    • Final output: X+Y=Z.

  • Common Output Traps:

    • Inadvertently swapping sep and end.

    • Forgetting that setting end=" AED" leaves trailing characters that will directly precede the next printed output.

    • Doubling whitespace when specifying sep=": " alongside string literals that already include trailing spaces.

    • Forgetting that commas in print(a, b, c) automatically insert spaces via the default sep=" ".

Code Tracing, Debugging Exercises, and Error Analysis

  • Systematic Code Tracing Routine:

    • Step 1: Read line by line; ignore comments (#) and uncalled def blocks.

    • Step 2: Annotate variable types (int, float, str, bool) and track reassignments.

    • Step 3: Pre-screen for compile-time syntax errors (quote mismatches, positional after keyword arguments) and runtime exceptions (TypeError on str + int, missing/duplicate arguments).

    • Step 4: Evaluate mathematical and logical expressions using precedence rules.

    • Step 5: Assemble outputs character-by-character, applying sep, end, and escape sequences.

    • Step 6: Eliminate multiple-choice options with incorrect types (e.g., 10 vs. 10.0) or malformed whitespace.

  • Output Prediction Exercises and Analyses:

    • print(type(42)) →\rightarrow <class 'int'> (evaluates whole number).

    • print(type(3.0)) →\rightarrow <class 'float'> (evaluates decimal point).

    • print(type("True")) →\rightarrow <class 'str'> (quotes designate text, overriding boolean).

    • print(7 / 2) →\rightarrow 3.5 (true division).

    • print(6 / 2) →\rightarrow 3.0 (true division returns float even when evenly divisible).

    • print("5" + "5") →\rightarrow 55 (strings concatenate).

    • print(5 > 3 and 2 > 4) →\rightarrow False (True and False evaluates to False).

    • print(0.1 + 0.2 == 0.3) →\rightarrow False (floating-point imprecision produces 0.300000000000000040.30000000000000004).

    • print(0b101) →\rightarrow 5 (binary positional conversion: 4+14 + 1).

    • print(0o10) →\rightarrow 8 (octal positional conversion: 1×8+01 \times 8 + 0).

    • print(0xA) →\rightarrow 10 (hexadecimal symbol conversion: A=10A = 10).

    • print(0xFF) →\rightarrow 255 (hexadecimal positional conversion: 15×16+1515 \times 16 + 15).

    • print(bin(6)) →\rightarrow 0b110 (converts integer 6=4+26 = 4 + 2 to binary string).

    • print(hex(31)) →\rightarrow 0x1f (converts integer 31=1×16+1531 = 1 \times 16 + 15 to hex string).

    • print(int("1010", 2)) →\rightarrow 10 (parses base 2 string into decimal integer: 8+28 + 2).

    • print(0b11 + 0o11 + 0x11) →\rightarrow 29 (cross-base summation: 3+9+17=293 + 9 + 17 = 29).

    • print("A B") →\rightarrow prints A and B on separate lines via .

  • print("Name:\tAli") →\rightarrow prints Name: followed by a tab gap and Ali.

  • print("C:\\Games") →\rightarrow outputs C:\Games via escaped backslash.

  • print('It\'s fun') →\rightarrow outputs It's fun via escaped apostrophe.

  • `print("Hi

Bye")→\rightarrow printsHi, an empty blank line, andBye`.

  • print(r"C: ew") →\rightarrow outputs C: ew (raw string ignores ).

    • print("Tab\\t") →\rightarrow outputs Tab\t (\\ evaluates to a single literal backslash, leaving t unchanged).

  • "Debug Doctors" Clinical Code Repairs:

    • Patient A: print('I can't wait')

    • Fault: Unescaped apostrophe terminates string prematurely.

    • Fix: print("I can't wait") (Rule applied: Enclose in opposite quote type).

    • Patient B: print("Good morning')

    • Fault: Opening double quote mismatched with closing single quote.

    • Fix: print("Good morning") (Rule applied: Matching quote types).

    • Patient C: print("The "best" day")

    • Fault: Unescaped interior double quotes collide with outer double quotes.

    • Fix: print('The "best" day') (Rule applied: Enclose in opposite quote type).

    • Patient D: print("Line 1 Line 2") split raw across lines in source code

  • Fault: Standard quotes cannot span physical lines.

  • Fix: print("""Line 1 Line 2""") (Rule applied: Triple quotes for multiline strings).

    • Patient E: print(Welcome to Python)

    • Fault: Text lacks quotes, causing interpreter to parse words as undefined variables.

    • Fix: print("Welcome to Python") (Rule applied: Text strings require quotes).

  • Receipt Designer Application:

    • Program specifications:

    • Output school canteen receipt formatting lines with .

    • Align columns via \t.

    • Print quoted item name using escaped quotes \".

    • Print directory path using escaped backslashes \\.

  • Reference code: python print("=== SCHOOL CANTEEN ===") print("Item\tPrice") print("Sandwich\t5") print("\"Special\" Wrap\t8") print("Saved to: C:\\Receipts") &nbsp;&nbsp;&nbsp;&nbsp;

  • Rendered terminal display: text === SCHOOL CANTEEN === Item Price Sandwich 5 "Special" Wrap 8 Saved to: C:\Receipts &nbsp;&nbsp;&nbsp;&nbsp;

Academic Inquiries, Plenary Exchanges, and Interactive Discussions

  • Conceptual Starter and Think-Pair-Share Inquiries:

    • Discussion on Data Storage Appropriateness: If storing a student's name ("Ahmed"), age (14), and height in meters (1.62), why should they not be stored the same way?

    • Resolution: Text data requires strings for semantic manipulation. Age requires an integer because it advances in discrete whole units. Height requires a floating-point type to retain fractional precision for accurate calculations.

    • Discussion on Equality vs. Identity: Why does 5 == 5.0 evaluate to True, but type(5) == type(5.0) evaluates to False?

    • Resolution: The equality operator evaluates numerical value, where five units equals five units. The type() function evaluates the underlying data structure in memory, where an integer is a whole-number type and a float is an IEEE-754 binary floating-point representation.

    • Discussion on the Necessity of String Delimiters: Why does Python require quotes at all?

    • Resolution: Quotes disambiguate text data from programmatic identifiers. Without quotes, print(Hello) triggers a variable lookup, whereas print("Hello") denotes a string literal.

  • Period 1 Review and Exit Ticket Inquiries (Literals and Expressions):

    • Question: What data type is 8.0?

    • Response: <class 'float'> (the inclusion of a decimal point designates a float).

    • Question: What result does 9 / 3 return?

    • Response: 3.0 (true division always returns a float).

    • Question: Provide a Python expression using comparison and logical operators that evaluates to False.

    • Response: 5 > 3 and 2 > 4 (evaluates as True and False, returning False).

    • Question: Explain why executing "5" + 5 produces a runtime error.

    • Response: Python is strongly typed and refuses to implicitly coerce an integer into a string or vice versa when using the addition operator, raising a TypeError.

    • Question: Why does 6 / 2 output 3.0 instead of 3?

    • Response: The division operator / represents true division and is specified in Python to return a floating-point number in all circumstances.

    • Question: Is "True" classified as a Boolean literal? Explain.

    • Response: No, "True" is a string literal (str). The surrounding quotation marks classify it as text, neutralizing its Boolean logical meaning.

    • Question: Identify appropriate use cases for integers versus floats in real-world software.

    • Response: Integers are used for discrete, countable entities where fractions are impossible (e.g., inventory stock, user IDs, loop counters). Floats are used for continuous measurements that include fractions (e.g., currency transactions, temperature readings, GPS coordinates).

  • Period 2 Review and Exit Ticket Inquiries (Number Systems):

    • Question: Which digits are valid within the binary number system?

    • Response: Exactly two digits: 0 and 1.

    • Question: What is the decimal value of 0b110?

    • Response: 66 (4+2+04 + 2 + 0).

    • Question: Write a Python expression to display the number 2020 in hexadecimal format.

    • Response: hex(20) (which returns '0x14').

    • Question: In a single sentence, summarize how base 2 differs from base 16.

    • Response: Base 2 uses two digits (0, 1) with column values scaling by powers of 22, whereas base 16 uses sixteen alphanumeric symbols (0–9, A–F) with column values scaling by powers of 1616.

    • Question: Why do modern computers natively utilize binary?

    • Response: Physical computer hardware consists of billions of transistors that operate reliably in two discrete electrical states: on (voltage present) and off (voltage absent).

    • Question: Why do software engineers and computer scientists prefer hexadecimal over binary?

    • Response: Hexadecimal is more compact and human-readable; exactly four binary bits (a nibble) map to one hexadecimal digit (24=162^4 = 16), simplifying memory addresses and byte visualization.

    • Question: Are 0o19 or 0b102 valid syntax in Python? Explain.

    • Response: Neither is valid; both raise a SyntaxError. In octal (base 8), valid digits range only from 0 to 7, making 9 illegal. In binary (base 2), valid digits are restricted to 0 and 1, making 2 illegal.

    • Question: Is 0xFF an int or a float?

    • Response: It is an int. Number system prefixes only change how the integer literal is written; Python stores all prefixed literals as standard integers.

  • Quotation Rules and Escape Sequences Inquiries:

    • Question: Fix the code print('Don't stop').

    • Response: Change the outer quotes to double quotes: print("Don't stop"), or escape the apostrophe: print('Don\'t stop').

    • Question: Write a line of code that prints: My teacher said "Well done!".

    • Response: Wrap the string in single quotes: print('My teacher said "Well done!"').

    • Question: What does an "unterminated string literal" syntax error signify?

    • Response: A string was opened with a quotation mark that was never closed before reaching the end of the line.

    • Question: When is using an escape character like \' necessary instead of simply switching quote types?

    • Response: Escaping is necessary when the string simultaneously contains both single quotes and double quotes within its body.

    • Question: Why must Python use \\ to output a single backslash?

    • Response: Because the backslash is reserved as an escape character, the interpreter treats a single \ as the start of an escape command; escaping the backslash itself tells Python to treat it as a literal character.

    • Question: What output is generated by print("Hi\tThere")?

    • Response: Hi followed by a tab stop and There (Hi There).

    • Question: Write a single-line statement to output the directory path C:\Users\Sam.

    • Response: print("C:\\Users\\Sam") or using a raw string: print(r"C:\Users\Sam").

    • Question: In a single sentence, describe what the escape character does.

  • Response: The escape sequence inserts a line break that moves the printing cursor down to the beginning of the next line.

  • Domestic Object Classification:

    • Television price: <class 'float'> (e.g., 1299.99)

    • Sibling's name: <class 'str'> (e.g., "Mariam")

    • Ambient room temperature: <class 'float'> (e.g., 21.5)

    • Front door lock state: <class 'bool'> (e.g., True)

    • Sibling count: <class 'int'> (e.g., 3)