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., , ).
String: A sequence of characters (e.g., "Hello", "Python").
Double, float: Represent floating-point numbers (numbers with decimal points, e.g., , ).
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 variableis 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 expressionRequirements:
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 variablextoz)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 += nis equivalent tox = x + n(addition assignment)x -= nis equivalent tox = x - n(subtraction assignment)x *= nis equivalent tox = x * n(multiplication assignment)x /= nis equivalent tox = x / n(division assignment)x %= nis equivalent tox = x % n(modulus assignment)x //= nis equivalent tox = x // n(integer division assignment)
Mathematical Operations
Basic Operators:
Addition (
+):15 + 3 = 18Subtraction (
-):15 - 3 = 12Multiplication (
*):15 * 3 = 45Division (
/):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()
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 int)1.5 * 1.5 = 2.25(float * float float)3 * 3.2 = 9.6(int * float float) - The integer3is temporarily converted to3.0before multiplication.3.2 / 2 = 1.6(float / int float) - The integer2is temporarily converted to2.0before 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):
Parentheses (
()): Operations inside parentheses are evaluated first.Exponentiation (
**)Multiplication (
*), Division (/), Floor Division (//), Modulus (%): These have equal precedence and are evaluated from left to right.Addition (
+), Subtraction (-): These have equal precedence and are evaluated from left to right.Comparison Operators (
==,!=,<,<=,>,>=)Logical Operations (
not,and,or)
Precedence Example: Consider the expression
5 + 2 * 3 ** 2Step 1: Exponentiation (
**) is performed first:3 ** 2 = 9Remaining expression:
5 + 2 * 9
Step 2: Multiplication (
*) is performed next:2 * 9 = 18Remaining expression:
5 + 18
Step 3: Addition (
+) is performed last:5 + 18 = 23Final result:
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 * heightRequirements:
Use variables to store
baseandheight.The program should print the
base,height, and calculatedarea.
Improvement Suggestion: Enhance the program to prompt the user for the
baseandheightvalues 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 closedKey: 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:
Actual Output:
56.666666666666664Reason: The formula incorrectly divides by instead of . 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).