Algorithms and programming was a highlight of the course and a larger part of the five big ideas of AP CSP. Because of this, I learned that loops and conditionals are some of the most important code segments in a programming language, as they allow for selection and interation. Some examples in Python are as follows:


Variables and Boolean Statements

Variables work without declaration in Python. Assigning a value creates the variable.

x = 4 creates the variable x with a value of 4.

If needed, commands like int() can help with assigning the variable type. This would declare the variable an integer and return an error if otherwise.


Booleans are true or false statements. They are used in loops to determine whether the loop should run.

10>9 returns True and would pass an if statement.

True and (false or True) also returns true.

False and (True or false) returns false.


Loops

While loops repeat the code until a certain condition is met. It is especially useful for counters or other progressively increasing programs that need to meet a condition.

In the following example, the condition needed to be met is x = 4, but the starting condition is x = 1. It will print every step until it reaches 4.

x = 1
while x < 4:
  print(x)
  x += 1

Output: 1 2 3


For loops repeat over a sequence depending on the selected value. It is especially useful for forming new strings or involving lists. This loop is quite important in my Create Performance Task, as the algorithm used would’ve had to have been much more complex without this loop.

In the following example, the loop runs for every character in the variable, text. It will proceed to the next character after executing the print command.

text = "Hello World!"
for char in text:
  print(char) 

Output: H e l l o ⠀ W o r l d !

If/Else Statements

If/Else statements run if a certain condition is or isn’t met. They are a critical aspect of a programming language, as they allow for a great range of selection.

The following example is a snippet from my performance task, which is determining if the shift amount input by a user exceeds the number of strings in the reference list. If it exceeds, the list is used as if the index was reset to zero.

if letter.index(char) + shift_am > 25: 
    tshift = ((letter.index(char) + shift_am) - 26)
else:
    tshift = (letter.index(char) + shift_am)

If letter.index(char) = 23, and shift_am = 6, the first command would execute as the statement would be true.