CC3 – COMPUTER PROGRAMMING 2
Python Programming Reviewer
Week 2 Introduction | Chapter 1 (Parts 1 & 2) | Chapters 2–4
WEEK 2 – INTRODUCTION TO PYTHON PROGRAMMING
1. History of Python
• Conceived: late 1980s; implementation started in December 1989
• Creator: Guido van Rossum at the Centre for Mathematics and Computer Science (CWI),
Netherlands
• Designed as a successor to the ABC programming language
• Features included exception handling and interfacing with the Amoeba operating system
• Guido van Rossum – Principal Author of Python; holds the title "Benevolent Dictator For
Life" (BDFL)
◦ Oversees Python development and retains final say in community disputes
2. Thrust Areas of Python
2.1 Marketability
• Known for simplicity and developer friendliness
• Considered one of the fastest-growing major programming languages
• Ranked in top ten most popular languages since 2003 (TIOBE Programming Community
Index)
• As of April 2018 → 4th in TIOBE Index
• IEEE Spectrum → 1st place (2017); RedMonk → 3rd place (2018)
2.2 Academia & Scientific Tools
• Offered as introductory programming language in most U.S. CS departments
• Competes with Matlab as the most preferred language for research
• Python is a real programming language; Matlab is not
Core Scientific Packages (BSD License):
◦ SciPy – numerical integration and optimization
◦ NumPy – N-dimensional array objects, linear algebra, Fourier transform
◦ Jupyter – revolutionized the way Python programming is done
◦ SymPy, Matplotlib
2.3 Machine Learning & NLP
• Machine Learning – effective and adaptive tool; originates from Computer Science &
Statistics
• Scikit-Learn – built on NumPy, SciPy, Matplotlib; supports Classification, Regression,
Clustering, Model Selection, Dimensionality Reduction, Preprocessing
◦ Available under BSD license + commercial license
• Natural Language Processing (NLP) – used to read and understand text
• NLTK (Natural Language Toolkit) – popular NLP library; available under Apache License
V2.0
2.4 Data Analysis & Statistics
• Pandas – transformed data analysis in Python; built on top of NumPy; available under BSD
license
Pandas Data Structures:
◦ Series – holds any data type; each item is labeled by index
◦ DataFrame – tabular structure with labeled rows and columns (like Excel)
Pandas Functions:
◦ Fill missing data, reshape datasets, slicing, indexing, merging, joining
◦ Reads: CSV, Excel, SQL, HDF5
• Statsmodels – statistical analysis; supports linear/generalized linear models, time series
analysis; used under modified BSD license
2.5 Database Connectors / HTTP / ORM
• Requests HTTP Library – 'library written for humans'; simplifies [Link]
◦ HTTP verbs: POST (Create), GET (Read), PUT (Update), DELETE (Delete)
◦ Features: Thread-safety, International Domains, Cookie Persistence, Connection Timeouts
• Database Connectors – drivers that allow querying databases from code
• Popular DBs: MySQL, PostgreSQL; connector: MySQL-Python-Connector from Oracle
• ORM (Object Relational Mapping) – 'bridge' between object-oriented programs and
relational databases
2.6 Web Frameworks
• Django – full-fledged web framework; supports caching, internationalization, serialization, ORM,
auto admin interface
• Flask – microframework for small apps; install external libraries as needed
• Both available under BSD-derived licenses
2.7 Game Development & Cloud Computing
• Pygame – library for game development; accelerates game mechanics and UI development
• OpenStack – entirely written in Python; creates scalable private and public clouds
◦ Features: load balancing, reliability, vendor independence, built-in security
◦ Included in Fedora and Ubuntu
• Cloud platforms: Google App Engine, AWS, Heroku, Microsoft Azure
3. Why Python?
• Works on multiple platforms: Windows, Mac, Linux, Raspberry Pi
• Simple syntax similar to English
• Programs written in fewer lines than other languages
• Runs on an interpreter system – code executes immediately; rapid prototyping
• Can be procedural, object-oriented, or functional
4. Python Syntax vs. Other Languages
• Designed for readability; influenced by English and mathematics
• Uses new lines to complete commands (not semicolons or parentheses)
• Uses indentation/whitespace to define scope (not curly-brackets)
5. Python Interpreter
• Python is an interpreted language: source code → bytecode → executed by Python Virtual
Machine
• Unlike compiled languages (C, C++) – Python does not need to be built and linked
• Compiler: translates high-level code to machine code ahead of time
• Interpreter: translates code line-by-line while the program is running
6. Indentation
• Indentation is a fundamental syntax rule in Python, not just style
• Defines code blocks; replaces braces used in other languages
Rules of Indentation:
◦ Default: 4 spaces; minimum 1 space required
◦ Indentation not permitted on the first line of Python code
◦ A code block must have a consistent number of spaces
◦ Whitespaces preferred over tabs; do not mix tabs and whitespaces
7. Comments in Python
• Symbol: # (number sign / hash / pound sign)
• Used to include short descriptions alongside code
• Explains logic and thought process of the developer
• The Python interpreter completely ignores comments
CHAPTER 1 – PART 1: VARIABLES, DATA TYPES &
OPERATORS
1. Variables
• Variables: containers for storing data values
• No declaration keyword needed (unlike Java); created upon first assignment
• Can represent a wide variety of information
number = 5 name = "Mary"
• Variables can change type after being set (dynamic typing)
2. Data Types
• String – text data type; e.g., x = "Hello World"
• Integer (int) – whole numbers; e.g., x = 214
• Float – numbers with decimal point; e.g., x = 214.50
• Boolean – True or False; e.g., x = True
• Bytes – e.g., bytes(4)
2.1 String
• A str object is a sequence of characters
• Can use single quotes (' ') or double quotes (" ")
• Concatenation: combine two or more strings using +
first = "Hello" last = "World" print(first + " " + last)
2.2 Numeric Types
• int and float are numeric types for performing mathematical operations
• Use type() function to check the type: print(type(5236))
• Floating point numbers contain a decimal point and are represented by float type
sal = 12563.25 print(sal)
2.3 Boolean
• Boolean data type has only two values: True or False
• Most objects in Python have a characteristic of True or False
• Commonly used as filters or conditions
3. Casting / Type Casting
• Casting: converting one data type into another using constructor functions
• int() – converts to integer (removes decimals from float)
• float() – converts to float
• str() – converts to string
x = int(3.14) # x = 3 y = float(5) # y = 5.0 z = str(10) # z = '10'
4. Output and Input Functions
4.1 print() – Output
• print(): prints message to screen or standard output
• Message can be a string, number, or any object (converted to string)
4.2 input() – Input
• input(): accepts user input; always returns a string
name = input("Enter Full Name: ") email = input("Enter Email: ") print("Name: " +
name) print("Email: " + email)
5. Operators in Python
5.1 Arithmetic Operators
• + Addition, - Subtraction, * Multiplication, / Division
• // Floor Division, % Modulus (remainder), ** Exponentiation
5.2 Assignment Operators
• = Assign, += Add and assign, -= Subtract and assign
• *=, /=, %=, **=, //=
5.3 Comparison Operators
• == Equal, != Not equal, > Greater, < Less
• >= Greater or equal, <= Less or equal
5.4 Logical Operators
• and – both conditions must be True
• or – at least one condition must be True
• not – reverses the boolean result
CHAPTER 1 – PART 2: STRINGS, FORMATTING, NUMBER
FUNCTIONS & CONTROL STRUCTURES
1. Strings in Python
• String: a series of characters interpreted as text
• Examples: "The quick brown fox.", 'The fast green turtle'
• Escape sequences: \', \", \n (newline)
1.1 String Placeholder – { } format
• Uses {} as placeholders inside strings with .format() method
name = "Juan" print("Hello, {}!".format(name))
• Placeholders can be positional or named
1.2 String Placeholder – % format
• %d – placeholder for an integer
• %s – placeholder for a string
• %.2f – placeholder for a float formatted to 2 decimal places
print("Item: %s, Qty: %d, Cost: %.2f" % ("milk", 55, 335.50))
1.3 String Indexing
• Individual characters accessed using Indexing
• Positive index: left to right (0, 1, 2...)
• Negative index: right to left (-1 = last, -2 = second last, ...)
• IndexError: index out of range; TypeError: non-integer index
2. String Formatting Methods
• [Link]() – converts to UPPER CASE
• [Link]() – converts to lower case
• [Link]() – first character to uppercase
• [Link]() – first character of each word to uppercase
• split() – splits string at separator; returns a list
• replace() – returns string with specified value replaced
• len() – counts total characters in a string
• count() – returns how many times a specified value occurs
3. Number Formatting Functions
• round() – rounds to nearest whole number or decimal place
• ceil() – rounds up to nearest whole number (from math module)
• floor() – rounds down to nearest integer (from math module)
• pow(x, y) – returns x to the power of y; pow(x, y, z) → x^y mod z
• Number data types are immutable: changing value creates a new object
4. Control Structures in Python
• Allow programs to make choices and follow multiple pathways
Types of Control Structures:
• Sequential – default; statements execute in order, top to bottom
• Selection – used for decision-making; checks conditions and branches
• Iteration / Repetition – used for looping; repeatedly executes a code block
4.1 Sequential
• A set of statements executed in sequence
• If logic breaks in one line, the entire source code execution breaks
4.2 Selection / Decision Control
• Branching statements: also called decision control statements
• Forms: only if, if-else, nested if, if-elif-else
4.3 Iteration / Repetition
• Uses for loop and while loop to repeat a set of statements
CHAPTER 2 – SELECTION (Decision Control)
1. Selection Structure
• Selection: provides a choice between two alternatives
3 Components:
◦ Condition – a boolean expression to be tested
◦ Process A – statement(s) performed if condition is True
◦ Process B – statement(s) performed if condition is False
• Entry: through the condition; Exit: through Process A or B
2. Single Alternative – if
• Executes a block only if the condition is True
if condition: statement1 # Example: a = 20 if a > 50: print("This is the if
body") print("This is outside the if block")
3. Dual Alternative – if-else
• if: executed when condition is True
• else: executed when condition is False
number = 10 if number > 0: print('Positive number') else: print('Negative
number') print('This is the end of the program.')
4. Multiple True Selection – if-elif-else
• Used when there are multiple conditions to evaluate
if condition: statement1 elif condition: statement2 else: statement3
5. Nested if Statements
• Nested if: an if statement inside another if statement
• Used to test multiple conditions in a structured, layered way
6. Compound Conditions
• Have more than one conditional expression
• and: BOTH conditions must be True
• or: at LEAST ONE condition must be True
(condition-1) and (condition-2) (condition-1) or (condition-2)
7. Built-in String Methods (for Conditions)
• isupper() – returns True if all characters are uppercase
• islower() – returns True if all characters are lowercase
• isdigit() – returns True if all characters are digits
• isalpha() – returns True if all characters are alphabetic
x = "SSS" print([Link]()) # True x = "python@" print([Link]()) # False (@
is not alpha)
CHAPTER 3 – ITERATION (Loops)
1. What is Iteration?
• Iteration: the most useful and powerful control structure
• Allows repetition of instructions or statements in the loop body
• Avoids code repetition and maintenance burdens
Parts of an Iteration Structure:
◦ Loop body – the instruction(s) repeated
◦ Loop-exit condition – the condition tested before each repetition
Types:
• while loop – condition-controlled; use when number of iterations is unknown
• for loop – count-controlled; use when number of iterations is known
2. When to Use Which Loop?
• while loop: best when loop depends on a sentinel value (special indicator value)
• for loop: best for traversing and manipulating arrays/sequences
3. Common Loop Applications
Accumulator
• Accumulator: a variable that sums up or accumulates values
• Similar to a counter, but accumulates undetermined values (counter adds a fixed value)
Data Validation
• A loop can validate user entry – check if input is correct data type or within range
• Incorrect data can lead to unwanted results or terminate a program abnormally
4. The while Loop
• Executes statements as long as the condition remains True
while condition: statement1 statement2
Flowchart Logic:
• Evaluates condition → if True: execute body → re-evaluate; if False: terminate
Sentinel Value
• Sentinel value: a special value that signals the end of a process
• Not part of the actual input; allows a different number of inputs each run
# Example: -98 as sentinel value = int(input("Enter a number (-98 to quit): "))
while value != -98: # process value value = int(input("Enter a number (-98
to quit): ")) print("Goodbye!")
5. The for Loop
• for loop: iterating function; repeats a fixed number of times
• Always used with an iterable object: list, range, string, dict, set, tuple
• Iterates over members of a sequence in order
Syntax:
for iterator_variable in sequence_name: Statements
Examples:
# Iterating a list names = ["Mike", "Ana", "Jun"] for name in names: print(name)
# Using range for a in range(10, 20): print(a) # Iterating a string string =
"Hello World" for x in string: print(x)
Nested for loop:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for lst in list_of_lists: for
x in lst: print(x, end="")
else in for loop:
• else: executes when the loop finishes normally (not interrupted by break)
for x in range(6): print(x) else: print("Finally finished!")
range() with step:
# range(start, stop, step) for i in range(1, 10, 2): # 1, 3, 5, 7, 9 print(i)
6. Loop Control Statements
break
• break: forces immediate termination of a loop
• Bypasses the conditional expression and remaining code in loop body
• Program control resumes at the next statement following the loop
continue
• continue: transfers control directly to the conditional expression
• Skips remaining statements in the current iteration
• Moves control back to the top of the loop
• Can be used in both while and for loops
pass
• pass: a null operation; nothing happens when it executes
• Used as a placeholder where code will eventually go but hasn't been written yet
# Summary of loop control: # break = terminates the loop entirely # continue =
skips to next iteration # pass = does nothing; placeholder
CHAPTER 4 – EXCEPTION / ERROR HANDLING
1. What are Exceptions?
• Exceptions: events or errors that disrupt the normal flow of execution
• Prevent the program from reaching a normal end
• Usually occur during runtime
Examples:
◦ Division by zero, Invalid input, File not found
2. Kinds of Exceptions
2.1 Checked Exception
• All exceptions except Runtime Exception are checked exceptions
• Subject to the Catch or Specify Requirement
• Checked by the compiler (compile-time exceptions)
• Errors the program can deal with
• Note: Python doesn't enforce checked/unchecked as strictly as Java — uses try-except blocks
2.2 Runtime Exception
• Unchecked: not subject to Catch or Specify Requirement
• Result of programming flaws
Examples:
◦ Dividing by zero, null pointer/reference, array/list out of bounds
2.3 Errors
• Generally beyond the control of the program
• Cannot be anticipated or recovered from
• Examples: unreadable file, hardware malfunction, syntax error
• Often referred to as unchecked exceptions
3. Types of Errors in Python
• SyntaxError – misspelled keyword, missing colon, unbalanced parenthesis
• TypeError – wrong type applied to operation (e.g., adding string to integer)
• NameError – variable or function name not found in scope
• IndexError – index out of range for list/tuple
• KeyError – key not found in a dictionary
• ValueError – function called with invalid argument (e.g., converting non-numeric string to int)
• AttributeError – attribute or method not found on object
• IOError – I/O operation fails (e.g., reading/writing a file)
• ZeroDivisionError – attempt to divide by zero
• ImportError – import statement fails to find or load a module
4. Handling Exceptions – try/except/else/finally
4.1 try Block
• try: code block where Python attempts to execute potentially error-prone code
try: file = open('[Link]')
4.2 except Block
• except: executes if the try block raises an error
• Cannot use try without an except or finally clause
try: file = open('[Link]') except Exception: print('Error')
4.3 else Block
• else: executes if no errors were raised in the try block
try: print("This is the try block!") except: print("There is an Error!")
else: print("No Error Found")
4.4 finally Block
• finally: executes regardless of whether an error occurred or not
• Always runs — used for cleanup operations
try: file = open('[Link]') except Exception: print('Error') else:
print('No Error') finally: print('Finally')
Full Structure:
try: pass except ExceptionName: pass else: pass finally: pass
5. The raise Keyword
• raise: used to manually trigger an exception depending on a condition
• Stops the control flow of the program
try: a = 15 if a <= 17: raise Exception except Exception:
print("Error:") else: print("No Error") finally: print("Finally")
raise with custom message:
try: number = int(input("Enter a positive number: ")) if number < 0:
raise ValueError("Number must be positive") else: print("Number is
positive") except ValueError as e: print("Error:", e)
6. The assert Keyword
• assert: a debugging tool that tests if a condition returns True
• If condition is False: raises AssertionError and stops execution
• If condition is True: continues execution normally
• An assertion: a boolean expression that the programmer assumes will always be True
x = 20 assert x == 20 # True → continues print("True") x = 20 assert x == 17 #
False → AssertionError
assert with try-except:
num1 = int(input("Input zero: ")) try: assert num1 == 0 print("CORRECT!")
except AssertionError: print("The number is not 0")
7. Quick Reference – Exception Handling Keywords
• try – defines the block of code to test for errors
• except – defines how to handle a specific error
• else – runs if no error was raised in try
• finally – always runs; used for cleanup
• raise – manually triggers an exception
• assert – tests a condition; raises AssertionError if False
— END OF REVIEWER —