Compsci exam notes Flashcards
Variables
A variable is a named storage location in a computer program.
Different types of variables are used to store different data types.
To define a variable, you need to specify its name and initial value.
Assignment Statement
Use the assignment statement ‘=’ to place a new value into a variable.
Assignment Statement Example
cansPerPack = 6
Note: ‘=’ is not used for comparison; it copies the value on the right into the variable on the left.
Variable Types
There are three types of data in Python: integers (int), floating-point numbers (float), and strings.
Variable Types Examples
cansPerPack = 6 # int, canVolume = 12.0 # float
Updating a Variable
If an existing variable is assigned a new value, that value replaces the previous contents.
Updated Variable Example
cansPerPack = 6 and then cansPerPack = 8
Computed update: cansPerPack = cansPerPack + 2
Variable Naming
Variable names should describe the purpose of the variable.
Follow rules: start with a letter or underscore, continue with letters, digits, or underscore.
Use ‘camelCase’ notation, avoid reserved words.
Constants
In Python, a constant is a variable whose value should not change after the initial assignment.
Constants are conventionally named in ALL_CAPS.
Arithmetic Operations
Python supports basic arithmetic operations: addition ‘+’, subtraction ‘-‘, multiplication ‘*’, division ‘/’.
Precedence follows PEMDAS (Parenthesis, Exponent, Multiply/Divide, Add/Subtract).
Mixing numeric types results in a floating-point value.
Arithmetic Operations (Contd.)
Use ‘**’ for exponentiation.
Floor division (//) discards the fractional part.
Remainder calculation uses the ‘%’ operator.
Arithmetic Operations (Contd.) Example
Convert pennies to dollars and cents
pennies = 1729
dollars = pennies // 100 # Calculates the number of dollars
cents = pennies % 100 # Calculates the number of pennies
print(“I have”, dollars, “and”, cents, “cents”)
Math Module
Python’s standard library includes the math module for advanced mathematical functions.
Import functions using from math import sqrt.
Strings
Strings are sequences of characters in Python.
Use single or double quotes to define string literals.
String length is obtained using len().
String Operations
Concatenate strings using ‘+’. Example: firstName + lastName
Repetition using ‘*’. Example: “-“ * 50
Convert numbers to strings using str().
String Methods
strings have built-in methods like upper(), lower(), etc.
String Methods Example
Example: name.upper() converts all characters to uppercase.
Input and Output
Use input() to read from the console.
Format output using % format specifiers.
Commenting Code
Use comments for explanation and documentation.
Two common styles include starting each line with # or using “”” “”” for multiline comments.
The if Statement
Allows a program to execute different actions based on data.
Keywords: if and else.
The if Statement example
floor = int(input(“Enter floor number: “))
if floor > 13:
actualFloor = floor - 1
else:
actualFloor = floor
print(“The elevator will travel to the actual floor %d” % actualFloor)
Relational Operators
Used in if statements for comparisons.
Floating Point Considerations
Floating-point numbers may have precision issues.
Relational Operators Examples
if floor > 13:
if floor >= 13:
if floor < 13:
if floor <= 13:
if floor == 13:
if floor != 13:
Floating Point Considerations Examples
EPSILON = 1E-14
r = math.sqrt(2.0)
if abs(r * r - 2.0) < EPSILON:
print(“sqrt(2.0) squared is approximately 2.0”)
String Comparison
Strings compared lexicographically.
String Comparison Examples
if name1 == name2:
print(“The strings are identical”)
if name1 != name2:
print(“The strings are not identical”)
Nested Branches
Using nested if statements for multiple conditions.
Nested Branches Examples
if maritalStatus == “s”:
if income <= RATE1_SINGLE_LIMIT:
tax1 = RATE1 * income
else:
tax1 = RATE1 * RATE1_SINGLE_LIMIT
tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT)
else:
# Handle married case similarly
Multiple Alternatives
Using if, elif, and else for multiple conditions
Input Validation Example
floor = int(input(“Enter floor number: “))
if floor == 13:
print(“Error: There is no thirteenth floor.”)
elif floor <= 0 or floor > 20:
print(“Error: The floor must be between 1 and 20.”)
else:
Multiple Alternatives Example
if richter >= 8.0:
print(“Most structures fall”)
elif richter >= 7.0:
print(“Many buildings destroyed”)
elif richter >= 6.0:
print(“Many buildings damaged, some collapse”)
else:
print(“No destruction of buildings”)
Input Validation
Ensuring valid user input
The while Loop
A while loop is a control structure that repeats a set of instructions as long as a specific condition is true.
The while Loop Example
balance = 10.0
target = 100.0
year = 0
rate = 0.025
while balance < target:
year += 1
interest = balance * rate / 100
balance += interest
Sentinel Values
Sentinel values are special characters or numbers used to indicate the end of a data set.
Sentinel Values Example
salary = 0.0
while salary >= 0:
salary = float(input())
if salary >= 0.0:
total += salary
count += 1
The for Loop
The for loop is used to iterate over the contents of a container or as a count-controlled loop.
Common Loop Algorithms Examples
uppercase = 0
for char in my_string:
if char.isupper():
uppercase += 1
The for Loop Example
state_name = “Virginia”
for letter in state_name:
print(letter)
Nested Loops Example
for i in range(4):
for j in range(i + 1):
print(“*”, end=” “)
print()
Nested Loops
Nested loops are loops inside other loops. Useful for complex iterations, like processing cells in a table.
Processing Strings Example
vowels = 0
for char in word:
if char.lower() in “aeiou”:
vowels += 1
Random Numbers & Simulation Example
from random import randint
for i in range(10):
d1 = randint(1, 6)
d2 = randint(1, 6)
print(f”Dice 1 is: {d1} and Dice 2 is {d2}”)
Functions as Black Boxes
Functions Overview
Definition: A function is a named sequence of instructions.
Functions as Black Boxes Example
def square(number):
return number ** 2
Function Call
Calling a function executes its instructions.
Function Call Example
result = square(5) # Calls the square function with 5 as an argument
Implementing & Testing Functions
A function consists of a header (name and parameters) and a body (instructions).
Implementing & Testing Functions Example
def greet(name):
return f”Hello, {name}!”
Testing a Function
To test a function, call it with specific inputs and check the output.
Testing a Function Example
greeting = greet(“Alice”)
Parameter Passing
Parameters are inputs passed to a function.
Parameter Passing Example
def add(a, b):
return a + b
Sentinel Values
Sentinel values are special inputs to indicate the end of data.
Sentinel Values Example
total = 0
while salary >= 0:
salary = float(input())
if salary >= 0:
total += salary
Functions with & without Return Values
Return Statement
Definition: The return statement ends a function and sends a value back
Functions with & without Return Values Example
def cube_volume(side_length):
return side_length ** 3
No Return Value
Functions are not required to return a value.
No Return Value Example
def greet(name):
print(f”Hello, {name}!”)
Variable Scope
Scope of Variables
The scope of a variable is where it’s visible.
Stepwise Refinement
Break Down Problems
Stepwise refinement is breaking down a problem into smaller tasks.
Stepwise Refinement
Break Down Problems
Example
Breaking down a check-writing program into functions like digitName, tensName, etc.
Variable Scope
Scope of Variables Example
def main():
total = 0 # local to main
for i in range(10):
square = i ** 2 # local to the loop
Global Variables
Global variables are visible to all functions.
Global Variables Example
balance = 1000
def withdraw(amount):
global balance
balance -= amount
Basic Properties of Lists
Lists store a sequence of elements.
Accessed using the subscript operator ([]).
Lists can hold values of any type.
Basic Properties of Lists Example
Creating a list
values = [32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65]
Accessing a list element
print(values[5]) # Output: 80