Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Exam Review 2023 May 20
- # Do those LABS
- # Ch 2-14... all Labs!
- # Ch 21-32 just ADDITIONAL LABS, but important practice!
- # Prac Tests, Ch 33 and 34
- # Use Submit Mode and get them to 100%!!! And PAY ATTENTION to the unit tests!
- # Comp 1: Basic syntax and knowledge: operators, data types, etc
- # Comp 2: Control Flow
- # Comp 3: Modules and Files
- # Watch your string input and output
- # input...
- # myInput = input().strip()
- # output/print()
- # print() is the same print(end="\n")
- # print("Something I'm printing", end=" ")
- # print()
- # print("Clean new line!") # I checked myself before I wrecked myself
- # Comp 1: Basic syntax and knowledge: operators, data types, etc
- # int
- # float
- # bool # True, False # x = 7 # if x > 5: # print(type(x>5))
- # str # ""
- # list # [ ]
- # dict # {key:value}
- # tuple # () immutable, Python sees a,b,c as (a,b,c)... return x,y --> return (x,y)
- # set # { } all unique/no duplicates, no order... no index, no slicing, no sort
- # range object # range()... range(0, 5) --> # [0, 1, 2, 3, 4]
- # operators
- # = # assignment, assigning a value
- # == # equality, asking a question, comparing... if/elif, while
- # +
- # -
- # *
- # /
- # % # modulo... gives the int remainder, "how many whole things didn't fit?"... since the last even division
- # // # floor division... is that last even division
- # <
- # >
- # <=
- # >=
- # += # x += 1 is x = x+1
- # -=
- # ** # raising to a power... pow() and math.pow()
- # !=
- # # # keywords used like operators
- # in # if x in myList:
- # not # if not x in myList:
- # and
- # or # any one True means the whole conditions is True... limit OR to 2 conditions
- # Comp 2
- # the HOW stuff... control flow structures
- # IF statements... if, if/else, if/elif, if/elif/else
- # LOOPS
- # WHILE - an IF that repeats
- # FOR - looping over a container, or a known number of times # hence... range()
- # for ___ in __someContainer__:
- # for item in myList:
- # for char in myStr:
- foodTVSubs = {
- # "": "Nancy asks if you can have a blank key", # legal!
- "canned ham": "Spam",
- "shell candies": "M&M's",
- "cereal treats": "Rice Krispies treats"
- }
- # for key in myDict: # loop var holds key
- # We can use dict keys as if they indices
- # print(foodTVSubs["canned ham"]) # retrives the value for the key
- # # We can assign a new value to a key
- # foodTVSubs["canned ham"] = "Turkey Spam"
- # print(foodTVSubs["canned ham"])
- #
- # for k in foodTVSubs:
- # v = foodTVSubs[k]
- # print(f"We have to say '{k}' instead of '{v}' on Food Network.")
- #
- # # dict items() method
- # for key, value in foodTVSubs.items():
- # print(f"We have to say '{key}' instead of '{value}' on Food Network.")
- # for n in range(0, 12):
- # for i in range(0, len(myList)): # for i, item in enumerate(myList):
- # print(myList[i])
- # 1st value tells me how many more times to call input()
- # myInput = int(input())
- # for n in range(myInput):
- # nextValue = input()
- # jerry.spiller@wgu.edu
- # FUNCTIONS
- # defining/writing vs calling
- # parameters are special variables... they don't work like "regular" variables
- # parameters vs arguments
- # return vs print()/output... vs other... do whatever the question says
- # a function has ONE, PARTICULAR job
- # def someFunction(x, y):
- # return x * y
- #
- # if __name__ == "__main__": # is this script the one that's being run from?
- # # we're solving THIS QUESTION
- # myInput = int(input())
- # myOther = int(input())
- # myNum = someFunction(myInput, myOther)
- # print(myNum)
- # See "tasks" in the last section of Ch 10, 11, 13, 14 for function writing practice
- # # CodingBat also has good function-based Python questions:
- # # https://codingbat.com/python
- # BUILT-IN FUNCTIONS
- # input()
- # print()
- # range()
- # type()
- # list()
- # int()
- # float()
- # dict()
- # tuple()
- # set()
- # enumerate()
- # round() # cousins math.ceil() and math.floor() are in math
- # open() # open file, create a file type object
- # len()
- # sum()
- # min()
- # max()
- # help()
- # dir()
- # help(list)
- # print(dir(str))
- # help(str.isspace)
- # STRINGS
- # be able to slice...
- # myStr = "abc"
- # revStr = myStr[::-1] # "cba"
- # KNOW YOUR WHITESPACE
- # " " # space bar space
- # # a lot of spaces in Unicode
- # "\n" # NEW line return
- # "\r" # carriage return
- # "\t"# tab
- # STRING METHODS
- # myStr.format() # "stuff I want to put together {}".format(var)...
- # myStr.strip() #
- # myStr.split() # returns a list of smaller strings
- # myStr.join() # " ".join(listOfStrings)
- # myStr.replace(subStr, newStr) # "remove"... myStr = myStr.replace(subStr, "")
- # myStr.find(subStr) # returns int... index where subStr starts
- # myStr.count(subStr) # return int count
- # case: myStr.lower(), myStr.upper(), myStr.title(), myStr.capitalize()
- # is/Boolean: myStr.isupper(), myStr.islower(), myStr.isspace(), myStr.isalpha(), isnumeric(), isdigit(), isalnum()
- # startswith(), endswith()
- # LIST
- # be able to use index, slices
- # LIST METHODS
- # # +
- # myList.append(item)
- # myList.insert(i, item)
- # myList.extend(anotherList)
- # # -
- # myList.pop() # pop by index... myList.pop(0)
- # myList.remove(item) # remove by value
- # myList.clear()
- # # other
- # myList.count(item)
- # myList.sort()
- # myList.reverse()
- # # also rans
- # myList.copy()
- # myList.index(item)
- # DICT
- # use the key like an index
- # myDict[key] # retrieve value for that key
- # myDict[key] = value # assign value to key
- # myDict.keys()
- # myDict.values()
- # myDict.items()
- # MODULES
- # math and csv
- # MATH MODULE
- # import math # FULL IMPORT
- # math.factorial(x)
- # math.ceil(x.yz)
- # math.floor(x.yz)
- # math.pow(x, y) # not to be confused with math.exp()
- # math.sqrt(x)
- # math.fabs(x) # abs(x)
- # math.pi
- # math.e
- # # PARTIAL IMPORT
- from math import factorial # # factorial(x) # not math.factorial()
- # from math import ceil, sqrt
- # from math import *
- # floor(x.yz) # not math.floor()
- # # ALIAS IMPORT
- # import math as m
- # m.floor(x.yz) # not math.floor()
- # FILES
- # READ MODE
- with open("test.txt", "r") as f:
- contents = f.readlines() # list a strings line by line
- # print(contents)
- # for line in contents:
- # line = line.strip()
- # print(line)
- # CSV Module
- import csv # csv.reader()
- with open("mock_data.csv", "r") as f1:
- contents = list(csv.reader(f1)) # returns list of lists
- # for tsv
- # contents = list(csv.reader(f1, delimitter="\t"))
- # print(contents) # [['id', 'first_name', 'last_name', 'email', 'gender', 'ip_address'], ['1', 'Remington', 'Shilling', 'rshilling0@wsj.com', 'Male', '1.71.141.52']... ]
- # for row in contents[0:20]:
- # print(row)
- # WRITE MODE
- # with open("output_data18.csv", "w") as f2:
- # for row in contents:
- # # only write into this new file if email is at tripadvisor.com
- # # email is at list position 3
- # if "@tripadvisor.com" in row[3]: # if row[3].endswith("@tripadvisor.com")
- # # takes a single str argument
- # f2.write(",".join(row) + "\n")
- # APPEND MODE
- # with open("append_to_this.txt", "r") as f3:
- # contents = f3.readlines()
- with open("append_to_this.txt", "a") as f3:
- f3.write("Gimli\nShelob\nBilbo\nRadagast\n") # added to file, rather than overwriting
- print(contents)
Advertisement
Advertisement