CQS 311 MIDTERM SHEEt

.pdf

School

Binghamton University *

*We aren’t endorsed by this school

Course

311

Subject

Computer Science

Date

Oct 30, 2023

Type

pdf

Pages

2

Uploaded by SuperHumanIronYak19

Variables, Expressions, and Statements: - Variables are named places in memory where data is stored. - Variable names must start with a letter or underscore and can consist of letters, numbers, and underscores. - Variables are case-sensitive. - Assignment statements are used to assign a value to a variable (e.g., x=5"). - Expressions are combinations of values, variables, and operators that evaluate to a single value. - Constants are fixed values like numbers, letters, and strings that don't change. - String constants are enclosed in single (") or double (") - Reserved words cannot be used as variable names. - Operators are symbols used to perform operations (e.g., "+ for addition). Numeric Constants: - Integers are whole numbers (e.g., 14, -2). - Floating-point numbers have decimal parts (e.g., -2.5, 98.6). - Numeric operations include addition (+), subtraction (-), multiplication (*), division (/), exponentiation (**), and remainder (%). Order of Evaluation: - Operator precedence determines the order of execution in complex expressions. - Use parentheses to explicitly specify the order. - Exponentiation has the highest precedence, followed by multiplication, division, addition, and subtraction. Types in Python: - Variables and constants have types. - Python knows the difference between integers and strings. - Type affects how operators behave (e.g., "+ means addition for numbers and concatenation for strings). - Type conversions can be done using “int()’, "float()’, “str()’ func User Input: - "input()” function reads data from the user as a string. - Use type conversion functions to convert input to numbers if needed. Comparison Operators: - Comparison operators (e.g., <, <=, == produce Boolean results. - Boolean expressions evaluate to "True’ or "False’ # True or True = True # False or True/ True or False = True # False or False = False . - Comparison operators look at variables but do not change them. Indentation: - Indentation is crucial in Python. - Increase indentation after an "if” or “for’ statement. - Maintain indentation to define the block's scope. - Reduce indentation to end the block. Two-Way and Multiway Decisions: - "1f° statements allow two-way decisions based on conditions. - Multiway decisions can be achieved using “elif” (else if). The “try’/ except” Structure: - Used to handle exceptions and errors. - Surround potentially problematic code with “try’ and handle errors in the “except’ block. Loops and Iteration: - Loops are used for repeated steps. - An 1infinite loop runs indefinitely. \’ \:>::\’ \:>\’ \!::\) - Use "break” to exit a loop prematurely. - Use "continue’ to skip the current iteration and start the next one. Definite and Indefinite Loops: - Definite loops run a fixed number of times. - Indefinite loops continue until a condition becomes "False'. Functions: - Functions are reusable blocks of code that take arguments and return results. - They are defined using "def . - Function calls use the function name, parentheses, and arguments. - Functions can return values using ‘return’. - Parameters are variables in the function definition. - Arguments are values passed to a function. - Void functions do not return values. - Use built-in functions and create custom functions. Strings: -> IMMUTABLE - Strings are sequences of characters - with *” or - Concatenation with "+’ joins strings. - Use 'len()" to get the length of a string. - Indexing allows access to individual characters. - Slicing extracts continuous sections of a string. - Common string functions include "find()", "replace()’, and "strip()". Lists: -> MUTABLE - Lists are ordered collections that can hold various data types. - Lists contents can change- elements separated by commas - Use ‘'len()’ to find the number of elements 1n a list. - Combine lists with "+ -uses Brackets [ ] - "append()’ adds elements to a list - adds it to the end - Lists can be sorted using “sort()". Dictionaries: -~ MUTABLE - Dictionaries are collections of key-value pairs- are unordered - Keys are used to access values. key : value - uses brackets {} - word : meaning- (key1 : valuel, key2 : value2, keyn : valuen) - Use "get()" to retrieve values safely - cant index -keys- print(sorted(variablename)) -values - print(sorted(variablename.values()) -pairs - print(sorted(variablename.items()) - keys should be unique values can be duplicated - Iterate through keys or key-value pairs using “for' loops -keys can be strings or numbers, values can be any type. -cannot be indexed by number - it gives an error Tuples: -~ IMMUTABLE - Tuples are ordered and immutable sequences- uses parentheses () - Tuples are efficient and are often used for temporary variables. - Lists can be sorted using the “sorted()" function. [X%4) LISTS variable.sort() #sorts from lowest to highest variable.sort(reverse = True) #sorts from highest to lowest print(len(variable)) # of items in list print(max(variable)) #largest print(min(variable)) # smallest print(sum(variablet)) print(sum(variablet)/ len(variable)) #average() = total/count # Define the list x =['a’, 'b", 'c’, 'd’, 'e'] # Select the 0th element in the list x[0] # 'a' # Select the last element in the list x[-1] # '€’ # Select 1st (inclusive) to 3rd (exclusive) x[1:3] # ['b', 'C']
# Select the 2nd to the end x[2: 1 #['c', 'd', ‘e # Select 0th to 3rd (exclusive) x[ :3] # ['a, 'b', 'c] CHANGING VALUE IN DICTIONARY print(phone_dict["John"]) phone_dict["John"] = "212-2121" Select the left side then use brackets and type in what u want to change for item in phone_dict: print(phone_dict[item]) #dictionaryvariable[key] = value LOOPS FILTERING numbers = [1,2,3,4,5,6,7,8,9,10] #find the square of all even numbers # filter all even numbers # find the squares for value in numbers: # filter all even numbers if value % 2 == 0: print(value, value ** 2) # filter all odd numbers if value % 2 1= 0: print(value, value ** 2) STRINGS -slicing- # stringvariable[start index : end index] # start index - inclusive # end index - exclusive -methods- print(dir(variable)) -find -> print(variable.find(* ‘) # exact match - it gives index of the first char of the match, # no match - it gives -1 -upper case and lower case- print(variable.upper()) print(variable.lower()) -replace - : x =5 if x < 10: print('smaller') if x > 20: print('bigger"') smaller : x =5 for i in range(5): print(1i) 0 1 2 3 4 : x =4 if x > 5: print(‘'bigger') else: print('smaller') print(nstr) Hello Jane HellX BXb friends = [ 'Joseph’, for friend in friends : print('Happy New Year:', print('Done!") Happy New Year: Happy New Year: Happy New Year: Done! Joseph Glenn Sally lotto = [2, 14, lotto[2] = 28 print(lotto) [2, 14, 28, 41, 63) x=11, 2, "joe', 99] print(len(x)) 4 while True: line = input('> ') if line == 'done' : break print(line) print('Done!’) 'Glenn’, 26, 41, 63] t; [ERIy e x = 20 if x < 103 print(‘'small’) elif x < 15: print('medium') else: print('large’) large astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print('First', istr) astr = '123' try: istr = int(astr) except: istr = -1 print('Second', istr) First -1 Second 123 smaller greet = 'Hello Bob' : - [i' 2, 3] nstr = greet.replace('Bob', 'Jane’) c ; : ; i' 6] print(nstr) print(c) nstr = greet.replace('o','X") t = [9, 41, 12, 3, print(t[1:3]) ‘sally'] 141, 12] friend) stuff = list() word = 'banana' count = 0 for letter in word : def addtwo(a, b): added = a + b return added if letter == 'a' : count = count + 1 print(count) X = addtwo(3, 5) print(x) 3 8 a = 'Hello' fruit = 'banana’ b = a + 'There’ letter = fruit[l] print(b) print(letter) c=a+ ' ' + 'There' print(c) i A w = fruit[x - 1] HelloThere print(w) Hello There a n greet = 'Hello Bob' zap = greet.lower() print(zap) fruit = 'banana’ print (greet.upper()) index = 0 print('Hi There'.lower()) while index < len(fruit): letter = fruit[index] print(index, letter) hello bob index = index + 1 HELLO BOB hi there 0 b la 2n 3 a 4 n 5 a 74, 15) stuff.append('book") stuff.append(99) print(stuff) [ 'book', 99] friends = [ friends.sort() print(friends) ['Glenn’, 'Joseph’, ‘Joseph’, 'Glenn', 'Sally' ] ‘sally') i |lx = (9, 8, 7] : purse = dict() purse[ 'money’ ] 2 purse[ 'candy’'] purse[ 'tissues’ print (purse) print(purse[ 'candy']) 1 3 -0 79 { 'money"’ : 3 12, 'candy': 3, ‘chuck’ : 1 , 'tissues': 'fred' x[2] = 6 print(x) [9, 8, 6] 75} : 42, 'jan': 100} for aaa,bbb in jjj.items() : print(aaa, bbb) chuck 1 fred 42 jan 100 print(variable.replace(" ", "))- doesn't actually change # strip(), Istrip(), rstrip() - remove whitespaces print(variable.strip()) # remove all whitespace on left and right print(variable.Istrip()) # remove all white space on left side print(variable.rstrip()) # remove all white space on right side Aaf +hinal). print('Hello') print('Fun’) thing() print('zip') thing() Hello Fun Zin click to expand output; double click to hide output Fun def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print('I sleep all night and I work all day.' print_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. def greet(): return "Hello" print(greet(), "Glenn") print(greet(), "Sally") Hello Glenn Hello Sally astr = 'Bob' try: print('Hello') istr = int(astr) print('There') except: istr = -1 print('Done’', istr) Hello Done -1
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help

Browse Popular Homework Q&A

Q: recent survey found that 60% of all adults wear sunglasses for driving. In a random sample of 10…
Q: Assume that intelligence follows a normal distribution and that on a standard test for intelligence…
Q: Explain the relationship between tests of the acquisition and payment cycle and tests of inventory.…
Q: Find the maximum for this list of numbers 43 14 54 10 38 63 86 92 25 68 20 50 18 48 59
Q: 6. Use properties of logarithms to condense the logarithmic expression below. write the expression…
Q: 2.) A group of students in a mathematics class were asked whether they participated in the past 3…
Q: Analyze the effect of the Baby Boomers retirement on the supply and demand for financial capital:…
Q: Janelle was able to describe her friend's personality quickly and accurately. When describing her…
Q: Display the current day of the week, hour, minutes, and seconds of the current date setting on the…
Q: describe each of the 10 generally accepted auditing standards and indicate how the action(s) of…
Q: Question 19 81 View Policies Current Attempt in Progress Use heats of formation data bellow to…
Q: QUESTION 10 1:1/1 Rung 1 36 C5:1/DN Rung 2E Rung 3 Rung 4 C5:1/DN 1:1/2 36 -CTU- COUNT-UP COUNTER…
Q: Create a view that lists the name and phone number of the contact person at each publisher. Don’t…
Q: M, a solid cylinder (M=2.27 kg, R=0.131 m) pivots on a thin, fixed, frictionless bearing. A string…
Q: What is the fundamental distinction between a node and a host?
Q: Consider the triangle shown in the figure. y (cm) 11 10 8 7 6 5 4 3 2 1 0 012 3 4 5 6 7 89 10 11 x…
Q: Test the hypothesis that the proportion of Elementary School Districts being Anderson has increased…
Q: The compoind CuNO3 is named: a) Copper (I) Nitrate b) Copper (II) Nitrate c) Copper (II) Nitrite…
Q: At a large publishing company, the mean age of proofreaders is 36.2 years and the standard deviation…
Q: For the problem related to Fundamental.4, a sketch of the considered system showing and naming (or…
Q: In a sample of 120 adults, 114 had children. Construct a 99% confidence interval for the true…
Q: price increases by 9% due to inflation and is then reduced by 10% · a sale. Express the final price…