Computing 1 cheatsheet

docx

School

Harvard University *

*We aren’t endorsed by this school

Course

E1

Subject

Computer Science

Date

Dec 6, 2023

Type

docx

Pages

21

Uploaded by ProfessorExploration7987

Report
Strings: - Use " " or ' ' to define strings. - `type()` determines variable data type. - Use semicolons `;` to end statements. - Import `math` for math operations. - * and / for multiplication and division. - ** for exponentiation. - Use * to repeat a string. - Ensure matching quotes. - Functions: name() and (). - # for line comments. - """ for block comments. Boolean Basically if is true or false variable4=True; A string type CANNOT be converted to float type Only int to float (vice versa), And string to int (in some cases) variable=”5”; print(int(variable)); when you change the type of the value, a new variable is created, even if the name is the same. variable=5; variable=7; print(variable); - Use "in" to check if a value is in the list (e.g., "John" in names). - "+" concatenates lists. - "*" repeats a list a given number of times. - ":" is the slice operator (e.g., a[1:3] gets elements 1 and 2). List Mutability: - Lists are objects, and when you assign one list to another, both point to the same memory space. - If created as a list, list elements can be changed. - Use "del" to delete elements specified by an index or a range, which changes the list length. String to List Conversion: - The "list()" function turns a string into a list. - The "split()" method breaks a string into a list based on a specified delimiter. Updating Dictionary: - To change a value for an existing key: `temperature["Indianapolis"] = 90;`. - To add a new key-value pair: `temperature.update({"Detroit": 90});`. Clearing and Deleting: - To clear all key-value pairs: `d.clear();`. - To delete the entire dictionary: `del d;`. Useful when you no longer need the dictionary to release memory space. Retrieving Values: - Retrieve a value using the key: `print(keypad2[2]);`. Note that the key is not an array index; it's the dictionary key. Both single quotes and double quotes can be used to enclose a string. (True) The output of the line print('The sign says "Don't enter! ".'); is no output due to a misplaced quote. A single-line comment is started with the # symbol. Variable Types: - String: variable1 = "bob"; - Integer: variable2 = 5; - Float: variable3 = 6.32; - Boolean: variable4 = True; Type Conversions: - String to int: int(variable) - Int to float (vice versa) - String to int (in some cases) Programming Cheat Sheet Assignment Operators: - =, +=, -= assign values to variables. - Read = as "gets," not equal. (e.g., a = b means A gets B) - Right side of = is evaluated first; the result is assigned to the left side. Naming Conventions: - Use Camel Notation (e.g., commonMan). Escape Character: - Use \ as an escape character (e.g., \" allows quotes in strings). Reserved Keywords (Python): - Keywords cannot be used as identifiers, function, or variable names. - Keywords define the language's syntax. - All Python keywords are lowercase, except True and False. Variables: - Have a name, type, and are case- sensitive. - Variable values can be changed during program execution. File Header: - Include file name, purpose of the file, and author's name. - Serves as documentation and provides context about the code. Lists: - Lists are sequences of values, which can be of the same or different types. - Commonly referred to as "arrays," although syntax may vary in different languages. - Elements in a list are called items. - Use indices (0-based) to access list values. List Manipulation: - Lists are mutable; you can change their values using indices. - Use a loop to populate a list. - To increase list size, use the `append()` method with an initial value (e.g., salary = []; salary.append(0)). Looping with Lists: - Use the `len()` function to find the length of a list (e.g., len(names)). - Consider using a for loop to iterate through a list dynamically The output of the statement x = "2"; y = "3"; z = x + y; print(z); is indeed "23" because the values are treated as strings and concatenated. newValue = 5; newvalue = newValue + 10; print(newValue) Loops (Iteration): A loop repeats a block of statements multiple times. - Define a loop by choosing a structure, start condition, number of repetitions, and statements to repeat. - Use "while" loops with a condition. The loop continues as long as the condition is true. - Ensure a mechanism to make the condition false to avoid infinite loops. - Use "break" to exit the loop prematurely and "continue" to skip the rest of the current iteration. Example: Sum even numbers in the 1-100 sequence. String Operations: A string is a sequence of alphanumeric characters. - Access characters using [] and an index (0-based). - Example: firstLetter = fruit[0] gets the first character. - Built-in functions help with string operations, like finding string length. - Use slicing to extract substrings, omitting the first or second index. - Strings are immutable; they can't be changed once created. String Operations: To change a string, create a new one; strings are immutable. - To convert a string to uppercase, use a built-in method (e.g., fruit.upper()). This doesn't change the original string. - Strings are case-sensitive; consider changing the case for consistent operations (e.g., converting to lowercase). - Example: fruit.upper() to change to uppercase. - Use .join() to connect list values into a string. - .join() method takes a list as an argument and returns a concatenated string. List Methods: - sort() changes the order of elements in the list and returns None. - Example: my_list.sort() for in-place sorting. - pop() removes an element at a given index, defaulting to the last element if no index is provided. - remove() specifies the value to be removed or removes the last element if no index is provided. Remember to create new strings or lists when changes are needed. Use these methods to manipulate strings and lists efficiently. Pass-by-Value: - When an argument is passed into a function, its value is stored in a new local variable. - Changes to the new local variable won't affect the original argument value. Pass-by-Reference: - When an argument is passed into a function, a local reference is created that points to the original memory space. - If pass-by-reference, changing the local reference variable will affect the original argument, as they point to the same memory space. Dictionaries: - Dictionaries are similar to lists but use keys to identify values. - Key-value pairs are used (a key maps to a value). - Creating dictionaries: 1. Use the `dict()` function and add data (e.g., skills["John"] = "Python"). 2. Use `{}` and add key-value pairs inside (e.g., temperature = {"Indianapolis": 80, "Chicago": 84}). 3. Use the `dict()` function and add data as inputs. - Keys must be of text or numeric type, values can be any type. - Avoid using integers as keys to prevent confusion with array indices. - Dictionaries can be created as nested structures. - Use loops to add keys and values dynamically.
A block comment is started with triple double quotes ("""). In line a = "18";, a string variable is created. In the line a = True;, a Boolean variable is created. In the line b = a + 3;, an integer variable is created because it is the result of adding an integer (3) to a Boolean value. In the line a = 1.7;, a float variable is created. An int type can always be converted to a float type by adding .0. A string type can be converted to an int type when possible by using the int() function. A float type can always be converted to an int type, which truncates the digits after the decimal point. A string type cannot always be converted to a float or int. It depends on the content of the string. In the line c = a + b;, c is assigned the result of adding a and b. The "=" sign is an assignment operator. The statement "You must first define a function before you call it." is true. True statements about the "return" value of a function include: The returned value from a function can be used outside the function. A function doesn't have to return a value A function can take 0 or multiple inputs. "newValue" by itself does not indicate a function. Function calls typically include parentheses, like newValue(2). x = 2; y = 3; print(x); "x" is an argument. def add(x, y): return x + y; a = 2; b = 3; print(add(a, b)); "x" and "y" are parameters. def add(x, y): return x * y; x = add(2, 3); print(x); is 6. x = 2; def KiloToMile(a): r = a * 1.6; return r; print(KiloToMile(x)); "r" and "a" are local variables, while "x" is a global variable x = 2; y = 3; def KiloToMile(x): r = x * 1.6; return r; "x" and "y" are global variables, and "r" is a local variable. x = 10; def KiloToMile(): y = 1.6; return x * y; "x" is a global variable. x = 10; def KiloToMile():x = 11; y = 1.6; return x * y; the "x" in line 1 is a global variable, and the "x" inside the function is a local variable. is 5 due to case-sensitivity. The escape character is represented by \. name = "Nightingale"; print("The venue's name is \"" + name + "\"!"); is "The venue's name is "Nightingale"!" because it uses the escape character to include double quotes within the string. You're right. The output would result in an error because you need to convert value to a string, like str(value) before concatenating it with a string. True statements about Python "keywords" include: There are a number of keywords in Python. "for" is a keyword. Keywords are part of the Python infrastructure. True statements about variables include: A variable has a name A variable has a type. A variable's value can be changed. Variable names are case-sensitive. The output of the statement a = 2**3; print(a); is indeed 8, as the ** operator represents exponentiation. You are correct. The output of the statement a = "b"; print(a*4); is "bbbb" because it repeats the string 4 times What must be included in a file header: Purpose of the file.Author name.File name. Professional coding style includes: Commenting the purpose of each code block. Having a file header at the beginning of each file. Commenting the purpose of each variable created. No need to add a line break after each line, but it's common to use line breaks for readability between code blocks. x = 22; y = 0; print("x times y is " x + y); is a syntax error. You need to use str(x + y) to concatenate the values. x = 22; y = 0; print ("x divided by y is " + str(x/y)); is a runtime error because division by zero is not allowed. x = 22; y = 0; print ("x divided by y is " + str(x*y)); is a logic error. The output is incorrect because it multiplies instead of dividing. The statement "We should limit the use of local variables" is false. Local variables are essential for organizing code within functions.The statement "Whenever a function call is completed, the memory space of all its local variables are freed and ready to be reused" is true for local variables. Global variables persist throughout the program's execution. Function Basics: - A function is a named sequence of statements that performs a specific task. - When defining a function, specify its name, input parameters, and the sequence of statements it should execute. - You call a function by name, providing different inputs as arguments. - Functions can return values, and these returned values can be used in your program. Type Conversion: - The `int()` function converts a floating-point number to an integer by truncating the fraction part. Function Errors: - Trying to convert a non-numeric string to a float will result in an error (e.g., `float('a')`). - Converting numeric strings works (e.g., `float('6')`). Modules: - Functions of similar purpose can be grouped into modules. - You must import a module before using its functions. User-Defined Functions: - Function definition consists of a header (starts with `def`) and a body. - The header includes the function name and input parameters, followed by a colon. - The body contains the statements to execute. - Define the function before calling it. Function Parameters: - Parameters specify what the function accepts as inputs. - When calling the function, actual values passed are called "arguments." Example: def square(parameter): return x ** 2 result = square(4) # Call the function with an argument and get the result. Variable Scopes: - Local Scope: Variables defined and accessible inside a function are local variables. - Global Scope: Variables defined and accessible inside and outside functions are global variables. Example 1: Global and Local Variables ```python # Global variable x, defined outside of a function x = 0 # Local variables a and b, defined inside the function square() def square(a): Global x b = a * a return b To run the statement print(math.sqrt(a)); successfully, the "math" module must be imported, and "a" must be a numeric value. True statements about a variable that can only be accessed inside a function (local variable) include: The variable is created inside the function. It is called a local variable. It cannot have the same name as a variable outside the function. True statements about a global variable include: It is created outside of a function. Its value can be changed inside a function. It can be used inside a function. It can use the same name as a local variable. Limiting the use of global variables is generally recommended, as excessive use can lead to confusion and consume memory.
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
Function a named sequence of statements that performs you define a function you specify the name, input parameters and the sequence of statements you can “call” the function by name give different inputs as arguments If a function produces a value the value can be passed out of the function, i.e. this function "returns" a value. int() floating-point type to integer type by chopping of the fraction part. #This will result in an error. d = float('a') But doing float(6), float(‘6’) works not for string letters Functions of similar nature or purpose can be grouped into a module. Must import the module before using that function. User can define functions. Function definition : specify what the function is like and what it should do Function call : run the function Must first define the function before calling it. First line is called "header", starting with def, then function name and input parameters, ending with a ":".
Rest lines are called "body", indended by convention with 4 spaces, ending with a blank line. This function defines one "parameter". When it is called, it will take only one input. def square(x): When the function is called, the actual value passed into the function is called an "argument". This function defines two parameters. def power(x, y): print(x**y); power(2,3); # Two arguments are passed to the function. "fruitful functions" Functions returning values A function can be called inside another function. Variable Scopes variable scopes The scope of a variable is where the variable can be used (accessible) Local scope : the variable is defined and accessible inside a function; it is called a local variable. Global scope : the variable is defined and accessible both inside and outside a function; it is called a global variable. global variable x, defined outside of a function x = 0; local variable a and b, defined inside the function square() def square(a): b = a*a; return b;
variables belong to different scopes can have the same name. They are different variables. def square(x): local variable x is created y = x*x; local variable y is created; local variable x is used(accessed) return y; local variable y is accessed Avoid using global variables , as 1) it may be accidentally changed inside other functions, 2) local variables will be destroyed as soon as a function call is complete thus result in better code efficiency. If values need to be used inside a function, consider passing values into the function. #Only use global variables when it is absolutely necessary, considerations include size of the code package, variable size, how many times a variable needs to be accessed, available memory space etc. Why functions? Package statements that performs one task - code organization. A function can be defined once and called multiple times - code reusability. If code need to be updated, only need to update once inside the function definition. Better team work - one member creates the function for others to use; others only need to know the function header and the return type quiz1 Both single quotes and double quotes can be used to enclose a string. true What is the output of this line: print('The sign says "Don't enter! ".'); No output: misplaced quote Which starts a single line comment? # Which starts a block comment? “”
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
What type of variable is created in the following line? a = "18"; String because it is in quotes What type of variable is created in the following line? a = True; Boolean (true or false) What type of variable is b? a = 2; b = a + 3; Int because numbers What type of variable is a? a = 1.7; Float (decimals) An int type can always be converted to a float type TRUE Add .0 A string type can be converted to an int type when possible TRUE Convert “5” to int A float type can always be converted to an int type TRUE It gets rid of digits after . A string type can always be converted to a float type IS WRONG Cant convert a name to float c = a + b; c gets a plus b What type of operator is the "=" sign? Assignment operator (focus on vocab) What is the output of the following statement? x = "2"; y = "3"; z = x + y; print(z); 23 because they are strings, not int Look at question first and see what you think what is output What is the output of the following statement? newValue = 5; newvalue = newValue + 10; print(newValue) 5 because it asking for newValue, not newvalue. (case sensitive) Which of the following is an escape character? \ What is the output of the following statement?3 name = "Nightingale"; print("The venue's name is \" " + name + " \" !"); The venue's name is "Nightingale"! The \” puts “ inside the main string. So double quotes in string What is the output of the following statement? value = 10; value = 20;
print("The value is " + value); ERROR You have to convert it to string so str(value) What is true about Python "keywords"? There are a number of keywords in Python. True "for" is a keyword . True Keywords are part of the Python infrustructure. True You can create a variable whose name is the same as a keyword. False It will mess up python (look at keywords examples) What is true about variables? Choose all that apply. A variable has a name. True A variable has a type. True A variable's value can be changed. True Variable names are case-insensitive. Variableone and variableone are different variables What is the output of the following statement? a = 2**3; print(a); 8 (** is an exponent)(review math stuff)(put it on cheat sheet) What is the output of the following statement? a = "b"; print(a*4); bbbb It repeats 4 times because you cannot multiply a string What must be included in a file header? Choose all that apply. purpose of the file True required author name True required file name True Required links and references False No Which of the following is considered as professional coding style? Choose all that apply. You should comment the purpose of each code block. true You should have a file header at the beginning of each file. true You should comment the purpose of each variable created. True You should add a line break after each line. No. line break after CODE BLOCK What type of error does the following statement have? x = 22; y = 0; print("x times y is " x + y); Syntax error (review errors) Wheres +str(x+y) What type of error does the following statement have? x = 22; y = 0; print ("x divided by y is " + str(x/y)); Run time error (review errors) U cant divide 22/0 What type of error does the following statement have?
x = 22; y = 0; print ("x divided by y is " + str(x*y)); Logic error because Output is wrong It is saying x divided by y, but code is multiplyiying Logic errors: always run but output is wrong You must first define a function before you call it. True A function definition starts with the keyword "define". False It is def CHECK 28. What is true about the "return" value of a function. Choose all that apply. The returned value from a function can be used outside the function. true A function can return multiple values. False (reviewO A function doesn't have to return a value. True A function can take 0 input. True A function can take multiple inputs . True Which of the following indicates newValue is a function? newValue(2) No brackets or anything Which is called an argument in the following statements? x = 2; y = 3; print(x); x in line 3 (review arguments, (passsing values into function) Which is called a parameter in the follwing statements? Choose all that apply. def add(x,y): return x + y; a = 2; b = 3; print(add(a, b)); y and x are parameters What is the output of the following code block? def add(x,y): return x*y; x = add(2,3); print(x); 6 because add is function. A bad function name Logic error What must be true for this statement to run successfully? Choose all that apply. print(math.sqrt(a)); The "math" module must be imported. "a" must be a numeric value. "a" must have a value. Yes A cannot be a string type because you cannot square a string What is true about a variable that can be accessed only inside a function?
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
Choose all that apply. The variable is created inside the function. true It is called a local variable . true It cannot have the same name as a variable outside the function. It can (REVIEW LOCAL AND GLOBAL) It can be changed to a global variable. Never talked about it 2 different variables What is true about a global variable? Choose all that apply. It is created outside of a function. true Its value can be changed inside a function. true It can be used inside a function. true It cannot use the same name as a local variable. False it can be same name We should limit the use of global variables. TRUE It becomes confusing When you have to Takes memory space and it can changed be inside a function We should limit the use of local variables. FALSE We love local Whenever a function call is completed, the memory space of all its local variables are freed and ready to be reused. TRUE (review) If it is global, then it will be false Which is a local variable in the following code block? Choose all that apply. x = 2; def KiloToMile(a): r = a * 1.6; return r ; print(KiloToMile(x)); r and a x is a global variable it is outside of function Which one is a global variable in the following code block? x = 2; y = 3; def KiloToMile(x): r = x * 1.6; return r; X is global variable Y is global variable But x inside function is local. 2 different variables R is local Which one is a global variable in the following code block? x = 10; def KiloToMile(): y = 1.6; return x*y; X is outside Which one is a global variable in the following code block? x = 10; def KiloToMile(): x = 11;
y = 1.6; return x*y; X in line 1. It is outside. Other x is different variable, its local What is the output of the following code block? x = 9; def KiloToMile(): global x; x = 10; y = 1.6; return x*y; KiloToMile(); print(x); 10 U made x inside function a global because global x; So it now it will print x=10 Does this line create a variable of boolean type? x = "True"; No because “” is a string Does this line create a variable of boolean type? x = False; Yes, (true and false is boolean) Which of the following creates a boolean type variable? x = True Which of the following means "not equal to"? != Which of the following is an "assignment operator"? = (review assignment operators) Quiz2 What is the value of c in the following code block? a = 2; b = 3; c = a == b; FALSE What is the output in the following code block? a = 2; b = 3; print(a <= b); TRUE What is the value of d in the following code block? a = 2; b = 3; c = 3; d = a == b and b == c; FALSE
What is the value of e in the following code block? a = 2; b = 3; c = 3; d = 4; e = a < b or b == c and c > d; TRUE Read from left to right True or true and false Does short circuit evaluation happen in the following code block? a = 2; b = 3; c = 4; if (a < b or b > c): check here print(a+b+c); YES Short circuit evaluation means Does short circuit evaluation happen in the following code block? a = 2; b = 3; c = 4; if (a > b or b > c): print(a+b+c); NO Does it finish performing task? An "if" structure must be paired with an "else" structure. FALSE It is possible that an "if" block never runs. TRUE It is possible that an "else" block never runs TRUE It is possible that both "if" block and "else" block get to run. FALSE Which of the following can get input from a user keyboard entry? input("What is your name?")
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
What is the type of variable a in the following code block? a = input("Please enter a value"); string What is the result of the following code block? a = 0; while (a <= 6): print(a); a = a + 1; 0, 1, 2, 3, 4, 5, 6 Dont look at answers. What is the result of the following code block? a = 0; while (a < 6): print(a); a = a + 1; 0, 1, 2, 3, 4, 5 What is the result of the following code block? a = 0; while (a <= 6): a = a + 1; print(a); 1, 2, 3, 4, 5, 6, 7 It first adds 1 first and keeps adding. It reaches 6 and adds 1 and prints that 7. It goes to while loop so it wont add past 7 What is the result of the following code block? a = 0; while (a <= 6): print(a); Infinite loop It will just print 0 because a is always less than 6. What is the result of the following code block? a = 0; while (a >= 6): print(a); No output 0 is small forever than 6 so it wont print out anything What is the result of the following code block? a = 0;
while True: a = a + 1; if (a == 1): print(a); Infinite loop It will only print 1 but it will be stuck in the loop because u just keep adding and running. What is the result of the following code block? a = 0; while True: a = a + 1; if (a == 1): print(a); Break; 1 It gets out of the while loop because of break after it has one. What is the result of the following code block? a = 0; while True: a = a + 1; if (a == 2): print(a); continue; continuing the while loop we are still finishing it if (a == 5): print(a); break; print(a); 1, 2, 3, 4, 5 It will add 1 and then print because of the print statement all the way in the bottom. When it is 2, it continues to print the rest. At 5, it will break and stop the program. What is the length of the variable a? a = "Computing I"; 11 Just count everything including space What is the value of variable b? a = "Computing I"; b = a[1]; o What is the otuput of the following code block? a = "Computing I"; index = 0;
while (index < len(a)): letter = a[index]; print(letter); index = index + 2; Cmuig I Index is smaller than 11. It assigns C to letter and prints it. Then it adds 2 to index. So 0 to 2. Then it assigns M to letter and and prints it out and adds it and goes to 4. It goes on until index is 11 so it will stop. What is the ouput of the following code block? a = "Computing I"; for i in a: print(i); Computing I Concept What is the ouput of the following code block? a = "Computing I"; print(a[0:4]); Comp It will stop at position 3. Which of the following creates a list of integer values? x = [1,2,3,4,5] [] is list What is the output of the following lines? x = ["Math", "English", "Art"]; print("The majors are: {}, {}".format(x[1], x[2])); The majors are: English, Art What is the output of the following lines? x = ["Math", "English", "Art"]; print("The majors are: {1}, {0}".format(x[0], x[1])); The majors are: English, Math What are the values in list x after the following block finishes running? x = []; i = 0; while (i < 5): x.append(i);
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
i = i + 1; 0, 1, 2, 3, 4 What are the values in list x after the following block finishes running? x = []; i = 0; while (i < 5): x[i] = i; i = i + 1; Code will not run. It never appends anything to list theres nothing in the list. What are the values in list x after the following block finishes running? x = [1,2,3,4,5]; i = 0; while (i < len(x)): x[i] = i; i = i + 1; 0, 1, 2, 3, 4 So it put 0 in the x list and adds 1 until it reaches to 5 What is the output of the following code block? a = [1,2,3]; b = a; a[2] = 0; print(b[2]); 0 Since a equals b, it will print whatever its in a. You also changed it to 0 What is the output of the following code block? x = ['a','b','c']; x.pop(0); print(x); B,c What is the result of the following code block? Choose all that apply. x = "a,b,c"; y = x.split(","); y is a list with 3 elements. The value of x is not changed. The value of x is changed to "abc". It only splits, the value never changed The value of y is the same as x. Y splits it, x is the original
A list can contain values of different types. True What is the output of the following code block? a = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]; print(a[1]); 5, 6, 7, 8 It will print the row position 1 What is the output of the following code block? a = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]; print(a[1][0]); 5 It prints the row postion 1 and looks into that it prints out positon 0 Which method is used when passing an array into a function? Pass by reference When "passing by value" method is used, a new local variable is created inside the function whose value is the same as the argument. True When "passing by reference" method is used, both parameter variable and argument variable point to the same memory location. True What is the output of the following code block? a = [1,2,3,4]; b = 0; def changeValue(x, y): x = y[0]; y[0] = 10; changeValue(b,a); print(a); 10,2,3,4 You are using y as a list and change y positon 0 to 10. You call function which you are basically doing b=x, a=y. b=a[0] a[0]=10; Which correctly defines a dictionary structure? Choose all that apply. x = dict() x = dict(a = 1, b = 2, c = 3) x = {"a":1, "b": 2, "c": 3}
The key of a dictionary can be of integer type. True The key of a dictionary must be of string type. False The value of a dictionary cannot be of float type False The keys in a dictionary must be unique. True The values in a dictionary must be unique. False You can use index to retrieve a value in a dictionary. FALSE What is the output of the following code block? x = 1; y = 2; d = {'a':x, 'b':x, 'c':x,'d':y,'e':y,'f':y}; print(d['f']); 2 2 is value given to the key ‘f’ What is the output of the following code block? x = 1; y = 2; d = {x:y, x:y, x:y}; print(d[y]);
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
No output due to error. There is no original key WEEK4(Logical Operators and Conditional Executions) floor division operator // divides two numbers and rounds down to an integer ○ hour=135//60; ○ print(hour); It prints 2(60 goes into 135, maximum 2 times) modulus operator % divides two numbers and returns the remainder ○ bob=150%70; ○ print(bob); It will print out 10 because it goes into 150, 2 times. 150-140 is 10. boolean expression is an expression that evaluates to either True or False x = True; #case sensitive y = False; == is a relational operator, means "equal to" logical operators: and, or "and" operator: both expressions must be evaluated to True for the compound expression to be evauated to True "or" operator: at least one expression must be evaluated to True for the compound expression to be evaluated to True if both "and" and "or" are used in the compound expression, "and" takes precedence "and", "or" operators perform short-circuit evaluations - if the result can be determined without evaluating further, the
evaluation process will stop Short-circuit evaluations improves code performance and prevent run time errors #conditional execution: use if/else structure to determine the flow of execution of a block of codes "if" is followed by a condition or compound condition, if the condition is evaluated to True, the if block runs otherwise, the "else" block runs an "if" structure doesn't have to be followed by an "else" structure Pay attention to the indentations. the above can be simplified using the "elif" keyword. It is called a "chained conditional expression". TYPES OF ERRORS; Syntax errors are similar to grammar or spelling errors in a Language Missing symbols (such as comma, bracket, colon), misspelling a keyword, having incorrect indentation len("data") = 4 print(1 2) Logic Errors your code does not run as you expected Using incorrect variable names, code that is not reflecting the algorithm logic properly, making mistakes on boolean operators def add_one(x): return x + 1 A function that is intended to calculate the area of a circle, but instead calculates the perimeter of the circle. A function that is intended to sort a list of numbers, but instead sorts the list of strings. A function that is intended to print the contents of a file, but instead prints the contents of a different file.
Runtime Errors errors that occur when the code is running trying to access a variable that does not exist, trying to divide a number by zero, trying to use an undefined function print(x)
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