CompSci 1/7 Test

ENTIRE YEAR SO FAR (MOST IMPORTANT STUFF)

  • Operations (PEMDAS always applies)

    • + - add

    • - - subtract

    • // -integer division- takes away the decimal no matter what it is

      • Integer division always takes away the decimal no matter what, puts lower #

      • 5//2=2

    • - exponential 52=25

    • % - modulus=remainder operator, returns remainder, 7%5=2, 2%5=2

  • Escape characters (must be enclosed in quotes)

    • \n make a new line

    • \t make a tab space

  • String concatenation

    • str() converts any value (usually a number value) to a string

    • sep - used to create a separator between strings.

      • print(“G”,”F”,”L”,sep=“_”)

    • end - can be used the same as sep

      • print(first, end= “ ”)

      • print(last)

      • Result- Finn Ryan

      • The sep parameter controls how items are separated within single print() statement, end parameter determines what is printed at the end of statement.

  • If you convert any number to boolean it will always be true unless 0

    • print(bool(0)) → returns FALSE

  • Use int() to convert to integer

  • Math functions and random functions

    • You must first import math and import random

    • math.sqrt()-for a square root

    • math.pow()- raise a number to the power of another number

      • print(math.pow(2,3)) → 8

    • math.floor()- rounds a number down

      • print(math.floor(3.14)) → 3

    • math.ceil()- rounds a number up

    • round(for rounding a number)

    • round(a,b)- where a is the number b is the decimal places

      • print(round(3.14159, 3)) → 3.142

    • math.abs()- for absolute values integers

      • math.fabs() for floating absolute value unit

        • print(math.fabs(-3.14)) → 3.14

    • Random- generates random numbers

      • print(random.randint(1,10)) a random # 1-10

    • random.uniform - for decimal/float random numbers (2 decimal places)

      • print(random.uniform(1,10)) → random float from 1-10

    • random/choice- selects randomly from a list

      • print(random.choice(names))- a random name off the list

  • Relational operators

    • > greater than

    • < less than

    • >= greater than or equal to

    • <= less than or equal to

    • == equal to

    • != not equal to

  • Logical operators- used to combine 2 or more boolean expressions

    • And

    • Or 

    • Not 


T and T = T

T or T = T

Not = opposite

T and F = F

T or F = T

not(True) = False

F and T = F

F or T = T

not(false) = True

F and F = F

F or F = F

  • Algorithm- a set of steps/instructions to solve a problem or accomplish a task

  • String methods- these are placed after your string like: print(“JOHN”.lower())

    • lower()- converts a string to lowercase

    • upper()- converts a string to uppercase

    • title()- converts first letter of every word to uppercase

    • capitalize()- converts only first letter of string to uppercase

    • lstrip()- removes any white space before a string

    • lstrip(characters)- removes specific characters from the left of a string

      • print(“Matthew”.lstrip(“aM”)) → matthew

      • Before you can remove middle letter you must remove everything before it, case sensitive

    • rstrip()- removes blank space from right, rstrip(characters)- removes characters from right

      • print(“Matthew”.rstrip(“ew”)) → Matth

    • strip()- removes spaces on both right and left side

    • strip(characters) - removes extra characters on both sides

  • More boolean stuff

    • islower()- True if all letters are lowercase

    • isupper()- True if all letters uppercase

    • isalpha()- True if string only contains letters

    • isdigit()- True if string only contains digits

    • isalnum()- True if string contains only letters and/or digits

    • isspace()- returns True if string contains only white space (eg. “ “, \n, \t)

    • startswith()- True if string starts w specified value

    • endswith()- True if string ends w specified value

    • isidentifier()- return true only if string is a valid identifier or variable

      • Identifier rules for variables names

        • Can’t start w number

        • Can’t have a space

        • Can’t be a key word (True, False)

        • No special characters #$!?

  • Finding index numbers

    • find()- gives index position of character/substring searched starting from 0. If there is an error it returns in -1

    • index()- returns the index position of the value searched starting from 0. If not found, ERROR is produced

    • rfind()- returns the position of last occurrence of value being searched, if not found, returns -1

      • print(“Mi casa, su casa”, rfind(“casa”)) → 12 NOT 3

    • replace(old, new)- replaces old substring w/ the new substring

    • center()- returns a centered string within specified member of spaces

      • print(“Welcome to This Game”.center(20)) →  Welcome to This Game 

    • count()- returns number of times specific character occurs in string

    • swapcase() - Returns string where lowercase becomes uppercase and vise versa

  • Index positions

    • len()- gives you the number of characters in a string

    • Index positions- use [ ] to indicate index

      • city=“Boston” print(city[0])- B    print(city[-1])- n print(city[6])- error

    • Slicing- selecting a range of characters (substring) in a string

      • print(“hello”[1:3]) → el print(“hello”[3:1]) → blank, you cannot slice backwards

    • REMEMBER: [start🔚step]

    • [:end] - this starts at 0 and goes all the way to the number. You input when u want to stop

      • print(“hello”[:4]) → hell

    • [start:]- this starts from the start index to the end of the string

      • print(“hello”[2:]) → llo

    • [:] this just gives the whole string

    • in - used to find if a character/substring is in a string

      • if ‘seven’ in text:

        • print(“The substring seven was found”)

    • Not in - negates in

      • if ‘seven’ not in text:

        • print(“The substring seven was not found”)

  • While loops- they use repetition

    • Syntax of a while loop:

      • Set initial value

      • While condition:

        • Commands

        • Commands

      • Update initial value

    • Example while loop

      • i=0

      • While i<10:

        • print(i)

      • i +=1

  • Infinite loop- loop that does not stop

  • For loops- loops controlled by a counter

    • There is a predetermined # of times it will loop

    • range(x)- function that generates numbers from 0 to x-1

    • For n in range(5):

      • print(“n”)

    • sum=0

    • For n in range(10,21)

      • Sum +=n

    • print(“Add”,n,”=”,sum)

  • Functions- group of commands with a name that performs specific task

    • Always start a function with “def” it means define

    • Void function- it doesn’t return anything it just prints the result

      • Def add23(num)

        • print(num+23)

    • Returning function- it returns the result to the original calling command

      • Easy way to tell if it is returning function is if it says return in it somewhere

  • Python lists- group of related items stored in a variable

    • Ways to make list

      • Declare a list empty then fill it up w stuff- use empty brackets [ ]

        • Nums[ ]

        • append() is used to add items to the list

        • nums.append(11)- adds 11 to the list

      • To access a specific value in the list, use the index position, nums[0] → prints 11

      • Second way is to declare list and assign items at same time

        • nums2=[11,14,12,13]

  • List slicing and methods

    • List-name[start:end] slice from start to end index (end included)

    • If you have just end index, no start, it assumes you start @ 0

    • If you have just a start index it assumes you’re going from that position to end

    • List-name[-index] starts counting from right to left

    • Using insert(index, item) you insert an item into your list at that location

      • If you give a index position too big computer adds item to end of list

    • entend(list) adds a new list to the end of existing list

      • scores.extend([10,20,30])

    • remove(item)- removes first occurrence of the item off the list

    • pop(optional index)- pops/removes an item from the specific index position, if you don’t specify index, it auto-removes the last item of the list

    • reverse()- reverses the order of the list (permanent change)

    • sort()- sorts the list in ascending order lowest to highest #

    • copy()- copies the item from one list to another list

  • 2D arrays- An array with multiple arrays inside it, can be displayed as a table

    • To print individual items in the array, listName[inner-array#][index in array]

    • The first inner array is the first row, second inner array is second row.

    • if you use len() for a 2D array it is number of rows

      • Use len(names[index#]) if you’re tryna find how many items are in a certain row

  • Methods to make a 2D array

    • Declare arrays and assign values later

      •  arrayName = [[], [], []]  → 3 arrays in an array

      • lockers1 =  [[0] * 3 for n in range(2)]   # A 2d array with 3 inner arrays

        • To fill these arrays

        • lockers1[0].append(12)

        • lockers1[1].append(16) etc.

    • Declare and assign values at same time

      • lockers4  = [[3, 2, 5], [4, 1, 7]]

      • print 2 from lockers4

        • print(lockers4[0][1])

    • Using a nested for loop can let you print everything in the entire array:

      • for array in prices:

      •   for price in array:

      •     print(price)

  • Parallel lists- 2 or more lists w/ 1-1 corresponding relationship between items

    • numbers = ["1", "2", "3", "4"]

    • números = ["uno", "dos", "tres", "cuatro"]

    • n = input("Enter 1, 2, 3, or 4: ")

    • print(n, "is", numeros[numbers.index(n)])

  • F-strings- Used to create formatted strings that include variables. They use { } squiggly brackets

    • syntax for format specifiers

    • {variable:[flag][width][precision]data-type}

    • Width sets how much space a value takes up.

    • Justification decides whether the value sticks to the left (<), right (>), or center (^).

    • Precision controls how many decimal places to show.

  • Data types for the f string

    • d - for integer data type (will add commas to a #)

    • f - for float data type

  • Using the f string:

    • print(f"x is {x}, y is {y}")  is simpler than print("x is " + str(x) + ", y is " + str(y))

    • n = 1000

    • print(f"{n}") # 1000

    • print(f"{n:,d}") # 1,000

    • print(f"{n:,.2f}") # 1,000.00

    • print(f"{n:10d}") #     1000 within 10 spaces, right justified by default

    • print(f"{n:<10d}") #     1000 within 10 spaces, left justified