Vocab

The three important vocab words for AP CSP are sequencing, selection, and iteration.

Sequencing: The order in which an algorithm runs.

Selection: Algorithms figure out whether to execute a boolean statement (if statement)

Iteration: Loop (ex: for, while)

See here for a coding example demonstrating sequencing, selection, and iteration.

3.3 Expressions

Expressions are values that can be combined to be interpreted into a new value.

The usual mathematical symbols apply, the main difference is that the symbol for exponents is **, not ^.

The coding example here demonstrates how to use the ** (exponent).

3.4 Strings

Psuedocode: Using common language to write out code. Good for planning purposes and helps other people understand what you intend to do with the code.

Index: Represents the position of an array.

Length: How long something is. For example, the length of a string is the number of characters it has.

Python

Length: len(value you want to find length of)

Substring syntax in Python: string[start index:end index - 1]

In this code, the substring takes an individual character from the binary string and calculates its values based on the base two power place it is in.

This can show specific characters in a string, which are the individual letters/numbers.

Below is an example of traversing through a string.

message = "StRiNG"

for i in range(0, len(message)):
    print(message[i])
S
t
R
i
N
G

You can also change a string to uppercase or lowercase with the upper() and lower functions.

msg = "dEfaUlt stRinG"

print(msg)
print(msg.upper() + " now uppercase".upper())
print(msg.lower() + " now lowercase".lower())
dEfaUlt stRinG
DEFAULT STRING NOW UPPERCASE
default string now lowercase

Coding example

The code below converts a decimal number into binary. This demonstrates sequencing, selection, and iteration.

  • Sequencing: First, the binary numbers are appended to the binary list. Next, each binary number is subtracted from the inputted decimal number provided that the input number > the binary number. If that is the case, a "1" will be added to the binary string; otherwise, a "0" will be added.
  • Selection: The if statement determines if a "1" or a "0" is added to the binary string.
  • Iteration: Two for loops are present; the first adds binary numbers to the list and the second adds a 1 or a 0 to the binary string.

Furthermore, this code segment demonstrates concatenating strings. As you can see in the example below, the output string is either appended to 1 or 0 depending on if the power of 2 fits in the number.

def convert(num):
    numOfBinary = 8
    binary = []; 
    output = ""
    
    for i in range(numOfBinary): 
        binary.append((2**(numOfBinary - 1 - i)))
    
    for i in range(len(binary)):
        if num - binary[i] >= 0:
            num -= binary[i]
            output += "1"
        else: 
            output += "0"
        
    print(output)
        
convert(25)
00011001