CS 1064 STUDY GUIDE

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Choose which of the following are valid Python variable names. Note that they do not have to be good variable names, just valid.

BankAccount _27_ stor_txt

A for loop will process a file sentence-by-sentence.

False

A while loop will always execute at least once.

False

A while loop will execute once for each expression in the conditional

False

Dictionaries are useful because you can have duplicate keys

False

The body of a for loop will contain one statement for each element of the iteration list.

False

The given program correctly closes the file: def has_a_cat(filename): a_file = open(filename) return "cat" in a_file.read() a_file.close() has_a_cat("story.txt")

False

The open function consumes a String representing a path and returns a String of the file's contents

False

The print function can only print literal values

False

The print function is necessary to call a function

False

The statement count = count + 1 will cause an error because no number can be greater than itself

False

Tuples are composed of key/value pairs.

False

Variable names are important because computers understand the meaning of names and change their value accordingly

False

Variables in Python are used to solve for unknown values, like in Alegbra

False

You can nest if statements inside of other if statements, but not inside functions

False

You can store a List as one of the keys of a Dictionary

False

You should not put error messages into help seeking emails because it can clutter up the email

False

Which of the following is the best description of this line of code? from math import sqrt as square_root

Loads the sqrt function in the math module but renames it square_root

The input function does which of the following?

Writes output to the console Consumes arguments Returns a string Retrieves input from the user

Unlike Lists, Tuples are immutable, meaning Tuples cannot be changed after they are created.

True

Variables change their value over time according to the instructions in a program

True

What is the value of the variable x after this code is run? values = [-1, -2, 2, 3] x = False for value in values: x = x or value > 0 print(x)

True

You can store a Dictionary as one of the elements of a List

True

You can store a List as one of the values of a Dictionary

True

You must import the json module before you can use the load function

True

Which of the following can be involved in an expression?

Variables Mathematical operators Values Other Expressions Conditional operators

How many times does the loop body below execute? command = "" words = [] while command != "quit": command = input("Give me another word:") words.append("Said "+command) print(words)

at least once

For Loop

A control structure for performing actions on each element of a sequence

Dictionary

A data structure for mapping keys to values ex. {} {1:2}

List

A data structure for storing elements in an ordered sequence ex. [1,2,3] []

Variable

A name that can be associated with a value

Function

A reusable chunk of code with inputs and outputs

Program

A sequence of coded instructions that manipulate data inside a computer

File

A sequence of data stored in your computer's long term memory

The function sayHi below returns the string "Hi". What value will the variable x hold after the line is executed? x = sayHi() + sayHi() + sayHi()

"HiHiHi"

Mark each of the following email titles if they are GOOD titles when seeking help from a senior colleague.

"What is a TypeError and how do I get rid of it?" "How do I update a variable?"

How many values can be used at a time with each of the following operators?

+ = 2 not = 1 and = 2 != 2

What is printed after the code below is executed? def calculate_sum(values): sum = 0 for value in values: sum = sum + value return sum sum = 0 calculate_sum([1, 2, 3]) print(sum)

0

Evaluate the type of the following expressions. Assume the following code is run first: name = "Python" grade = 100.0

1+1 = Integer [name] = List "1,2,3,4".split(",") = List True or False = Boolean name[0] = String "1" + "1" = String 4/5 = Float 100-99 = Integer [0][0] = Integer 1 < 5.0 = Boolean grade - grade = Float 1+1 < 5 or 4 > 3 = Boolean {name:grade} = Dictionary

Fill in the blanks of the following code in order to print out each movie title followed by the names of its characters: movies = [ {"Name": "Iron Man", "Length": 126, "Characters": ["Tony", "Pepper", "Obidiah"]}, {"Name": "Thor", "Length": 130, "Characters": ["Thor", "Jane", "Loki"]}, {"Name": "Captain America", "Length": 126, "Characters": ["Steve", "Peggy", "Bucky"]}] for movie in movies: print(movie[ __1__ ]) for character in movie[ __2__ ]: print(character)

1. "Name 2. "Characters"

Assume that the following code is run: values = [1,2,3] word = "Python" Predict the output of each of the following operations: print(values[ 0 ]) print(values[ -1 ]) print(values[ 2 ]) And then also for these: print(word[ :2 ]) print(word[ -2: ]) print(word[ 3:4 ])

1. 1 2. 3 3. 3 4. Py 5. on 6. h

How many branches do each of these code snippets have? if conditional: print(4) print(4) if conditional: print(1) else: print(3) if conditional1: if conditional2: print(4) print(3) print(2)

1. 2 2. 2 3. 3

The function double below returns the number multiplied by 2. What value will the variable "x" hold after the line is executed? x = double(4) + double(2)

12

How many elements are in the following list? movies = [{"Name": "Iron Man", "Released": 2008}, {"Name": "Thor", "Released": 2011}, {"Name": "Captain America", "Released": 2011}]

3

What will be printed after this code is run? points = {"Virginia Tech": 5} points["Virginia Tech"] = 3 print(points["Virginia Tech"])

3

Evaluate whether each of the following expressions are True, False, or cause an error. Apply the rules of Truthiness when they are not boolean expressions. Assume the following code is run first: quote = "I like turtles"

3<5 = True False = False 10 == 10.0 = True "" in quote = True "quote" in quote = False 10 == "10" = False not False = True 5 < 4 or 3 == 3 = True [1,2,3] <5 = Error 5 in [1,3,5] = True True or (True and False) = True not True and False = False "1" + "1" == "2" = False "False" == "False" = True "turtle" in quote = True " " in quote = True "Alaska" < "Delaware" = True [] = False

After the second iteration of the loop, what is the value of sum? sum = 0 values = [4, 2, 6] for value in values: sum = sum + value

6

If an if statement is nested inside another if statement, how many spaces will the body of the inner if statement have?

8

Type

A categorization of values of similar kinds that determines what you can do with the values ex. Boolean Float Integer Dictionary String List

Module

A collection of functions, classes, and variables available to be imported

If Statement

A control structure for branching the execution of a program

String

A type that represents textual data ex. "2.0" "Python" '' "True"

What is the type of the iteration variable in this code? groceries = [{"Name": "Apple", "Cost": 1.99, "Calories": 20}, {"Name": "Cookie", "Cost": 4.99, "Calories": 300}, {"Name": "Steak", "Cost": 6.99, "Calories": 100}] for grocery in groceries: print(grocery)

Dictionary

Every function created with the def keyword must have AT LEAST one parameter

False

Expressions are always evaluated from left to right

False

Humans discovered programming languages in the 1940s and have been decoding them ever since.

False

Once a function returns a variable, that variable is available outside of the function

False

Printing is the same thing as returning

False

String are composed of only letters and symbols

False

Description: The method find returns the numerical index of the first appearance of substring in a_string. Remember, counting starts at 0. If the substring is not in the string, then -1 is returned. Syntax: a_string.find(substring) Parameters: - substring (str): The string to find in a_string. Returns: int Examples: > "Harry Potter".find('r') 2 > "Capitalization is Important".find('I') 18 > "Harry Potter".find('g') -1 > "".find('e') -1 > "You can check for more than one character!".find("can") 4

How many parameters does the find method take? 1 What type of value does the find method return? integer What is the result of calling the following: "Hello". find ("l") 2

Is the print call before, inside, or after the for loop? for name in names: print(name)

Inside

Which of the following are possible subtypes for a list?

Integer List Boolean Dictionary String

Which of the following types are sequences?

List String Tuple File Dictionary

What is the value of tax after this program executes? if False: tax = 5 print(tax)

No value, because an error occurs since the value has not been defined

When the following code is executed, what will be the value of the variable named greeting? def make_greeting(name): print("Hello", name) greeting = make_greeting("Mr. Anderson")

None

Given the file named scores.txt with the following contents: 44, 23, 37 And the following python code: score_file = open("scores.txt") score_data = score_file.read() What will be the type of score_data?

String

Literal Value

Specific instances of data written directly in source code

How do you write each of the following as string literal values? A tab character: A new line: A double quote: A single quote:

Tab = "\t" New Line = "\n" Double Quote = "\"" Single Quote = "'"

Histogram

The distribution of a list of numbers

Scatter Plot

The relationship between two lists of numbers

Line Plot

The trend in a list of numbers

Keys can be added to a dictionary after the dictionary has been created

True

Like an if statement and a function call, the for Loop might cause the execution to not follow the sequential order of lines.

True

List comprehensions cannot express everything that a for loop can.

True

Normally, statements are executed from top to bottom

True

The Iteration Variable will take on each value of the List Variable, one at at time

True

Given this dictionary... animal = {"Name": "Pumpkin", "Age": 2, "Small?": True}

What is the type of the value associated with the key "Name" = String What is the type of the key "Name"? = String What is the type of the key "Small?" = String What is the type of the value associated with the key "Age" = Integer

Read the following code, and then fill in the blanks below. 1| def f(x): 2| x = x + 1 3| return x 4| y = f(0) 5| print(y)

What line is executed first? 1 What line is executed second? 4 After line 3 is executed, what will be the next line executed? 5

Read the error message below, then fill in the blanks at the bottom. Traceback (most recent call last): File "my_code.py", line 49, in <module> 21 + "NameError" TypeError: unsupported operand type(s) for +: 'int' and 'str'

What line of code did the error occur on? 49 What type of error occurred? TypeError

The print function does which of the following?

Writes output to the console Consumes arguments

Which of the following demonstrates proper syntax for accessing a dictionary's value?

a_dictionary["Key"]

What does the pass do?

absolutely nothing

How would you call a function named close_file? Assume it takes no arguments.

close_file()

Given the following dictionary, convert = { 5: 10, 10: 5 } What is the value of the following expressions?

convert[5] = 10 convert[5+5] = 5 convert[5]+5 = 15

Given the following code, dict = {"Key": "Value", 7: 8, True: "Hello"} key = 7 Which of the following are valid expressions?

dict[key] dict["Key"] dict[True] dict[7]

Built-in functions

ex. print input

Keyword

ex. while for in def import return

Values

ex. 5 "" [] True {1:2}

Tuple

ex. (1,2,3)

Float

ex. -1.4 2.3454

Integer

ex. 5 -100000257

None

ex. None

Boolean

ex. True False

Which of the following have a body?

for loop while loop if statement Function definition

Label each of the following as a function call, method call, or not a call.

function.call() = Method print() = Function file.(close) = Not a call method() = Function "function".method() = Method (input) = Not a call

Which of the following two snippets of code are equal?

import json file = open("scores.txt") json.load(file) from json import load file = open("scores.txt") load(file)

Which of the following expressions creates two new variables?

month, year = (11,17)

Given the following code: movies = [ {"Name": "Iron Man", "Length": 126, "Characters": ["Tony", "Pepper", "Obidiah"]}, {"Name": "Thor", "Length": 130, "Characters": ["Thor", "Jane", "Loki"]}, {"Name": "Captain America", "Length": 126, "Characters": ["Steve", "Peggy", "Bucky"]}] What is the value of the following expressions?

movies[0]["Name"] = Iron Man movies[0]["Name"] = Captain America movies[1][1] = Raises an Error movies[127]["Name"] = Raises an Error movies[2]["Characters"][0] = "Steve" movies[2]["Characters"]["Steve"] = Raises an Error movies[1]["Characters"][2] = Loki movies[2]["Steve"] = Raises an Error movies[-1]["Length"] = 126

Label each of the following as either a "Read", a "Write", or a "Read and Write" for the variable price.

price = 0 = Write print(price) = Read adjusted = price*tax = Read price = price*.9 = Read and Write

Given the program below, name = input("What is your name?") def fix_capitalization(name): return name.title().strip() def print_message(name): print("Hello", name, "how are you?") Which of the following lines of code will have the data flow correctly through both functions in order to print the message with the fixed capitalization?

print_message(fix_capitalization(name)) name = fix_capitalization(name) print_message(name)


Kaugnay na mga set ng pag-aaral

NURS 321: Leadership Module 2.03

View Set