CS 115: Data Types, Operators, and Errors

CS 115: Introduction to CS with Python - Data Types, Operators, and Errors

Computer Architecture Fundamentals

  • Von Neumann Architecture: Briefly mentioned as a foundational concept in computer science (Page 2).

  • Computer Architecture: General topic of how computer systems are designed and function (Page 3).

Data Types

  • Variables: Defined as locations in memory where values can be stored.

    • Integers: Represent whole numbers (e.g., 55, 10-10).

    • String: A sequence of characters (e.g., "Hello", "Python").

    • Double, float: Represent floating-point numbers (numbers with decimal points, e.g., 3.143.14, 2.52.5).

  • Variable Naming Rules: Specific guidelines for creating valid variable names in Python.

    • Can consist of letters, digits, and underscores (e.g., my_var, age2).

    • Must start with a letter or an underscore (e.g., _counter, name).

    • Cannot have spaces in the name (e.g., my variable is invalid).

    • Cannot be a Python keyword (reserved words like in, for, else, class, if, while, etc.).

  • Invalid Variable Name Examples:

    • 1varible: Invalid because it starts with a number.

    • my-variable: Invalid because a hyphen ($-$) is not allowed.

    • my variable: Invalid because it contains a space.

Variable Assignment

  • Syntax: Variable = some expression

  • Requirements:

    • Left-Hand Side (LHS): Must be a single variable (e.g., name, x, z).

    • Right-Hand Side (RHS): Can be a value, another variable, or an expression.

  • Evaluation Process: The RHS is evaluated first, and its resulting value is then assigned to the variable on the LHS.

  • Examples:

    • name = "Kevin" (assigns a string value)

    • x = 21 (assigns an integer value)

    • y = 6 (assigns an integer value)

    • z = x (assigns the value of variable x to z)

    • x = 3 + 4 * 5 - 6 * 2 + 1 (assigns the result of an expression)

    • z = x + 5 (assigns the result of an expression)

    • z = x + y (assigns the result of an expression involving two variables)

  • Invalid Assignment Examples:

    • a + b = 10: Invalid because the LHS is an expression, not a single variable.

    • x + 1 = 30: Invalid for the same reason—LHS is an expression.

Compound Assignment Statements

  • Purpose: These are shorthand operators for performing an arithmetic operation and then assigning the result back to the original variable.

  • Operators:

    • x += n is equivalent to x = x + n (addition assignment)

    • x -= n is equivalent to x = x - n (subtraction assignment)

    • x *= n is equivalent to x = x * n (multiplication assignment)

    • x /= n is equivalent to x = x / n (division assignment)

    • x %= n is equivalent to x = x % n (modulus assignment)

    • x //= n is equivalent to x = x // n (integer division assignment)

Mathematical Operations

  • Basic Operators:

    • Addition (+): 15 + 3 = 18

    • Subtraction (-): 15 - 3 = 12

    • Multiplication (*): 15 * 3 = 45

    • Division (/): 15 / 3 = 5 (Note: In Python 3, division always results in a float).

  • Other Operators:

    • Integer Division (//): Returns the floor of the quotient (the largest whole number less than or equal to the quotient).

      • Example: 5 // 3 = 1

    • Modulus (%): Returns the remainder of the division.

      • Example: 5 % 3 = 2

    • Exponentiation (**): Raises the first operand to the power of the second operand.

      • Example: 5 ** 3 = 125 (53=5imes5imes5=1255^3 = 5 imes 5 imes 5 = 125)

Mathematical Operations: Type Conversions

  • Implicit Type Conversion: Occurs automatically during an operation without explicit instruction from the programmer.

  • Mechanism: The Python interpreter automatically chooses the appropriate data type for the result based on the operands involved.

  • Examples:

    • 3 * 4 = 12 (int * int <br>ightarrow<br>ightarrow int)

    • 1.5 * 1.5 = 2.25 (float * float <br>ightarrow<br>ightarrow float)

    • 3 * 3.2 = 9.6 (int * float <br>ightarrow<br>ightarrow float) - The integer 3 is temporarily converted to 3.0 before multiplication.

    • 3.2 / 2 = 1.6 (float / int <br>ightarrow<br>ightarrow float) - The integer 2 is temporarily converted to 2.0 before division.

Operator Precedence

  • Definition: Rules that dictate the order in which operations are performed in an expression, similar to mathematical order of operations.

  • Precedence Order (from highest to lowest):

    1. Parentheses (()): Operations inside parentheses are evaluated first.

    2. Exponentiation (**)

    3. Multiplication (*), Division (/), Floor Division (//), Modulus (%): These have equal precedence and are evaluated from left to right.

    4. Addition (+), Subtraction (-): These have equal precedence and are evaluated from left to right.

    5. Comparison Operators (==, !=, <, <=, >, >=)

    6. Logical Operations (not, and, or)

  • Precedence Example: Consider the expression 5 + 2 * 3 ** 2

    • Step 1: Exponentiation (**) is performed first: 3 ** 2 = 9

      • Remaining expression: 5 + 2 * 9

    • Step 2: Multiplication (*) is performed next: 2 * 9 = 18

      • Remaining expression: 5 + 18

    • Step 3: Addition (+) is performed last: 5 + 18 = 23

      • Final result: 2323

  • Recommendation: Use parentheses (()) to explicitly define the order of operations and make code clearer, even if not strictly necessary according to precedence rules.

Activity 5: Python Operations (Area of a Triangle)

  • Task: Write a Python program to compute the area of a triangle.

  • Formula: Area = 0.5 * base * height

  • Requirements:

    • Use variables to store base and height.

    • The program should print the base, height, and calculated area.

  • Improvement Suggestion: Enhance the program to prompt the user for the base and height values before performing the computation.

  • Submission: Submit code and screenshots of execution on Piazza, with improvements as a reply to the original comment.

Errors in Python

  • General Information: In Python (and programming in general), errors are categorized into three main types.

  • Perspective on Errors: Errors are not failures; instead, their types provide crucial clues to help diagnose and fix issues in the code.

1. Syntax Errors
  • Definition: Occurs when the code violates the grammatical rules of the Python language.

  • Impact: The Python interpreter cannot understand or run the program at all.

  • Example: print("Hello" (missing closing parenthesis)

    • Error Message: File "/Users/CS115/temp.py", line 1 print("Hello" ^ SyntaxError: '(' was never closed

    • Key: Read the error message carefully; it often provides hints about what went wrong (e.g., SyntaxError: '(' was never closed).

2. Runtime Errors
  • Definition: Occurs when the program's syntax is correct, but it attempts an impossible or invalid operation during execution.

  • Impact: The program terminates abruptly (crashes).

  • Examples:

    • Dividing by zero (e.g., 10 / 0).

    • Attempting to perform arithmetic between incompatible data types, like multiplying two string literals (e.g., "abc" * "xyz").

  • Example: Division by zero

    • Code: a = 10, b = 0, c = a / b, print(a), print(b)

    • Error Message: File "/Users/CS115/temp.py", line 4, in <module> c = a / b ZeroDivisionError: division by zero

3. Logic Errors
  • Definition: Occurs when the code runs without crashing, but it produces an incorrect or unexpected result.

  • Detection Difficulty: These are the hardest type of errors to detect because no error message is displayed by the interpreter.

  • Example: Calculating an average with an incorrect formula.

    • Code: student1 = 80, student2 = 90, average = (student1 + student2) / 3, print(average)

    • Expected Output for correct average: (80+90)/2=170/2=85.0(80 + 90) / 2 = 170 / 2 = 85.0

    • Actual Output: 56.666666666666664

    • Reason: The formula incorrectly divides by 33 instead of 22. The correct formula for the average of two numbers is average = (student1 + student2) / 2.

Activity 6: Python Errors

  • Task: Identify the type of error (Syntax, Runtime, or Logical) for given Python code snippets and indicate the line number and the specific error (if any).