Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Exam Review 2023 Jan 21
- # LABS
- # Ch 2-14... all Labs!
- # Ch 21-34 just ADDITIONAL LABS, but important practice!
- # Use Submit Mode!!!
- # Watch your string input and output
- # 1
- # myVar = input().strip()
- # 2
- # print() # print(end="\n")
- # # if you ever override end...
- # print("some stuff", end=" ") # set it back to a clean new line
- # print() # wrap up with it!
- # print("Clean new line!")
- # Comp 1: Basic syntax and knowledge: operators, data types, etc
- # Comp 2: Control Flow
- # Comp 3: Modules and Files
- # Comp 1: Basic syntax and knowledge: operators, data types, etc
- # Common Data Types
- # int
- # float
- # str # ""
- # list # []
- # dict # {k:v}
- # tuple # () immutable, Python sees any x,y,z as (x,y,z)... return x,y -> return (x,y)
- # set # {} all unique / no duplication, no order (no index, no slice, no sort...)
- # range() # --> sequenced container of a series of number
- # operators
- # = # assignment
- # == # equality... asking, comparing... condition
- # +
- # -
- # *
- # /
- # % # modulo... int remainder... "how many whole things left over?"
- # // # floor division... x//y -> math.floor(x/y)
- # >
- # <
- # >=
- # <=
- # += # increment
- # -= # decrement
- # != # not equal... asking/comparing
- # ** # raise to a power... pow() or math.pow()
- # # keywords used like operators
- # in # if _someValue_ in _someContainer_
- # not # if not _someValue_ in _someContainer_
- # and
- # or # any one True means whole condition 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 item in _container_:
- # for item in myList:
- # for key in myDict:
- # for num in range(0, 5): # [0, 1, 2, 3, 4]
- # for i in range(0, len(myList)):
- # FUNCTIONS
- # defining/writing vs calling
- # parameters are special "variables"... they don't work like regular variables
- # parameters vs arguments
- # a function has ONE particular job
- # return vs print()... vs write a file... whatever the question says
- # method are functions that belong to a particular class/type
- # def someFunction(x, y):
- # return x + y
- #
- # if __name__ == "__main__": # are we running from this very script I'm writing?
- # myInput = int(input())
- # myOther = int(input())
- # num = someFunction(myInput, myOther)
- # print(num)
- # 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
- # print()
- # input()
- # range()
- # list()
- # int()
- # float()
- # set()
- # tuple()
- # dict()
- # str()
- # len()
- # min()
- # max()
- # sum()
- # pow()
- # abs()
- # bool()
- # round() # buts its cousins math.ceil() and math.floor() are in the math module
- # chr()
- # ord()
- # open() # for IO/files --> .read(), .readlines(), .write()
- # sorted() # returns sorted list... compare list.sort() does not return anything
- # reversed() # same as above
- # enumerate()
- # type() # type objects have a .__name__ property
- # help() #help(str)
- # dir()
- # print(dir(str))
- # help(str.isspace)
- # STRINGS
- # be able to slice like it's 2nd nature: myString[start:stop:step]
- # myStr = "abcde"
- # revStr = myStr[::-1]
- # print(revStr)
- # KNOW YOUR WHITESPACE
- # " "... and many Unicode spaces
- # "\n"
- # "\r"
- # "\t"
- # STRING METHODS
- # "stuff I want to put together {}".format(var) # or similar f strings
- # myStr.strip()
- # myStr.split() # returns a list of smaller strings
- # ",".join(listOfStrings)
- # myStr.replace(oldStr, newStr) # remove... myStr = myStr(oldStr, "")
- # myStr.find(subStr) # return the index where substring starts, or -1... myStr.index(subStr) would error instead
- # myStr.count(subStr)
- # case: myStr.lower(), myStr.upper(), myStr.title(), myStr.capitalize()
- # is/Boolean: isupper(), islower(), isspace(), isdigit()... return Boolean on whether the whole str is that
- # LISTS
- # again be able to slice
- myList = [1, 2, 3, 1, 2]
- # LIST METHODS
- # +
- # myList.append(item)
- # myStr.insert(i, item)
- # myStr.extend(anotherList)
- # # -
- # myList.pop() # myList.pop(i)
- # myList.remove(item) # ... pop() by index, remove by value
- # # other
- # myList.count(item)
- # myList.sort()
- # myList.reverse()
- # myList.index(item)
- # myList.copy()
- # myList.clear()
- # DICT
- # use the key like an index
- # myDict[key] # retrieve the value for that key
- # myDict[key] = value # assign a (new) value to that key
- # myDict.keys()
- # myDict.values()
- # myDict.items()
- # MODULES
- # math and csv
- # MATH MODULES
- # import math # <-- that's a 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() # compare to abs()
- # math.e
- # math.pi
- #
- # # PARTIAL IMPORT
- # from math import factorial
- # # don't say math.factorial()... we didn't import math
- # factorial()
- # ALIAS IMPORT
- # import math as m
- # import math as m
- # m.floor() # etc
- # FILES!!!
- # READ MODE
- with open("test.txt", "r") as f:
- contents = f.readlines() # returns a list of strings line by line
- print(contents) # it looks like:
- # [
- # 'Hello.\n', # note new line returns on each line
- # 'This\n',
- # 'is\n' ...
- # etc ...
- # ]
- # for line in contents:
- # line = line.strip()
- # print(line)
- # CSV MODULE
- import csv
- with open("mock_data.csv", "r") as f1:
- contents = list(csv.reader(f1)) # creates a list of lists, with each comma-separated value being a string in the inner lists
- # if tsv... csv.reader(f1, delimiter="\t")
- # print(contents) # it looks like:
- # [
- # ['id', 'first_name', 'last_name', 'email', 'gender', 'ip_address'],
- # ['1', 'Remington', 'Shilling', 'rshilling0@wsj.com', 'Male', '1.71.141.52'],
- # ['2', 'Milty', 'Chittey', 'mchittey1@china.com.cn', 'Male', '85.14.30.8'],
- # ['3', 'Enoch', 'Keady', 'ekeady2@hud.gov', 'Male', '216.15.244.138'],
- # ['4', 'Baldwin', 'McCaskill', 'bmccaskill3@icio.us', 'Male', '151.51.0.216'],
- # ['5', 'Carling', 'Baude', 'cbaude4@liveinternet.ru', 'Male', '91.198.36.54']...
- # etc ...
- # ]
- # WRITE MODE
- # writes over file (if it already exists) destructively
- with open("output_data10.csv", "w") as f2:
- for line in contents:
- # look for emails ending in .gov to write out
- # email = line[3]
- # if email[-4:]
- if line[3][-4:] == ".gov": # or line[3].endswith(".gov"):
- # write() method takes one single str argument
- f2.write(",".join(line)+"\n")
- # APPEND MODE
- # writes onto the end of a file, non-destructively
- # with open("append_to_this.txt", "r") as f3:
- # contents = f3.readlines()
- # print(contents)
- # [
- # "Frodo\n",
- # "Sam\n",
- # "Merry\n" # btw, always worth seeing if this last line has a new line return or not
- # ]
- with open("append_to_this.txt", "a") as f3:
- f3.write("Pippin\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement