Python Programming 1 Exam Review

Ace your homework & exams now with Quizwiz!

Which choice best represents the output of the following code? student_name = "iteration" count = 0 for letter in student_name: if letter.lower() == "e": print(count) count += 1 a) "2" b) "3" c) "-4" d) "-5"

a) "2"

Choose the correct print output for the following code: name = "Alton" print(name[::2]) a) "Atn" b) "lo" c) "on" d) "Al"

a) "Atn"

Which statements evaluate True and without errors? (Choose all that apply.) a) "upper".islower() b) "The Title".istitle() c) "upper".isupper() d) 3.isdigit()

a) "upper".islower() b) "The Title".istitle()

Which operator has the highest precedence? a) + b) == c) and

a) +

Which string method returns an index of first character or substring matches? a) .find() b) .count() c) .isalpha() d) while

a) .find()

To move the pointer in an open file to the first character, what should you use? a) .seek(0) b) .seek(-1) c) reset(filename) d) All of the above

a) .seek(0)

To move the pointer 5 characters past the current pointer location, what should you use? a) .seek(5,1) b) .seek(5, 2) c) .seek(5, 0) d) All of the above

a) .seek(5,1)

Which function displays a date object in the form Monday, January 01, 2018? a) .strftime("%A, %B %d, %Y") b) .strftime("%A, %B %D, %Y") c) .strftime("%A, %M %d, %Y") d) .strftime("%A, %M %D, %Y")

a) .strftime("%A, %B %d, %Y")

When using Python, which mathematic operation returns a value of 2? a) 46 % 4 b) 46 / / 4 c) 46 / 4 d) 46 ** . 4

a) 46 % 4

Which of the following statements about tuples is true? a) A tuple can contain list elements. b) A tuple cannot contain another tuple. c) After you define a tuple, you can add elements to it. d) You define the elements of a tuple within square brackets.

a) A tuple can contain list elements.

In Python, what is the base class for all built-in exceptions? a) BaseException b) Error c) Exception d) IOError

a) BaseException

What is the output of the following code? 1. tip = "Do or do not. There is not try. Jedi Master Yoda" 2. tip_words = tip.split() 3. for word in tip_words: 4. print(word) a) Do or do not. There is not try. Jedi Master Yoda b) Do or do not. There is not try. Jedi Master Yoda c) Do or do not. There is not try.Jedi Master Yoda d) Do or do not.There is not try.Jedi Master Yoda

a) Do or do not. There is not try. Jedi Master Yoda

Which best describes the result of the following code? days = [12, 9, "Monday", 1] days.remove("Friday") a) Error, because "Friday" was not found and can't be removed b) Nothing happens, because the "Friday" was not found in the list c) "Friday" is added to the list d) All of the above

a) Error, because "Friday" was not found and can't be removed

Which attributes can you define for a time object? (Choose all that apply.) a) Hour b) Second c) Day d) Month e) Millisecond

a) Hour b) Second

// This means a) Integer Division b) Division c) Exponent d) Modulo

a) Integer Division

Which two statements about the pydoc module are true? (Choose two). a) It generates documentation from the docstrings in a module. b) It generates documentation for a module without importing it. c) It imports a module and then generates documentation for the module. d) It automatically suppresses module functions from running while generating documentation for the module.

a) It generates documentation from the docstrings in a module. c) It imports a module and then generates documentation for the module.

Which two statements about key:value pairs are correct? (Choose two.) a) Keys are unique b) Values are unique c) A value can be associated with multiple keys d) Keys within a dictionary must be of the same type

a) Keys are unique c) A value can be associated with multiple keys

In which two ways is a tuple like a list? (Choose two.) a) Lists and tuples are data structures that can store a sequence of elements. b) Lists and tuples are immutable data structures. c) Lists and tuples can contain int, float, list, and string elements. d) You can reorder the elements of lists and tuples.

a) Lists and tuples are data structures that can store a sequence of elements. c) Lists and tuples can contain int, float, list, and string elements.

Given that the file school_names contains the following text with 3 school names: City Elementary Maths High School Early Learner PreSchool if we run the following code: schools = open("school_names.txt", "w+") Which item is Not True? a) The file school_names will contain the original 3 school names. b) The file school_names will be erased and empty. c) We can now read to the school_names by using schools.readline(). d) schools.read() will return an empty string.

a) The file school_names will contain the original 3 school names.

When a function calls a subfunction, which variables are maintained in memory? (Choose all that apply.) a) The global variables b) The function variables c) The subfunction variables

a) The global variables c) The subfunction variables

What is the result of not setting the value of the year attribute of a date object? a) The object is invalid. b) The year defaults to the current year. c) The year defaults to 9999. d) The year defaults to 0.

a) The object is invalid.

Which two statements are true for two objects that contain the same information and are saved in different memory locations? Example: ```python x = [1,2,3,a,b] y = [1,2,3,a,b] ``` (Choose two.) a) They are equal b) They are not equal c) They are identical d) They are not identical

a) They are equal d) They are not identical

"w+" mode opens a file for write plus read, such as in the following Python code: schools = open("school_names.txt", "w+") a) True b) False

a) True

.readline() is used to read one line, as a string, from an open text file. a) True b) False

a) True

A datetime.timedelta object stores only days, seconds, and microseconds. a) True b) False

a) True

A file opened in read mode cannot be changed (we cannot write to the file). a) True b) False

a) True

Escape sequences start with a backslash (\). a) True b) False

a) True

In Python, range(0,5) is equivalent to the list [0, 1, 2, 3, 4]. a) True b) False

a) True

In Python, using the 'raise' statement allows the programmer to define and raise their own exception. a) True b) False

a) True

Python code can include a script that returns the operating system platform your code is running on with the .sys a) True b) False

a) True

The .pop() method both returns and deletes an item from a list. a) True b) False

a) True

The containment operators in and not in return a True/False result. a) True b) False

a) True

The first item in a Python List is located at index 0 (zero). a) True b) False

a) True

The following code will print "act". word = "characteristics" print(word[4:7]) a) True b) False

a) True

The input() function in Python returns user input as a string. a) True b) False

a) True

True and False are Boolean keywords in Python. a) True b) False

a) True

Using comma separation, we can combine strings and numbers (int & float) in a single Python print() function without a TypeError. a) True b) False

a) True

def ignoreCase(name): answer = "" while answer.isalpha() == False: answer = input("enter last name: ") return answer.lower() == name.lower() When will the ignoreCase function exit the while loop? a) When only letters are entered at the input prompt b) When answer == name c) When answer.lower() == name.lower() d) When a digit is entered at the input prompt

a) When only letters are entered at the input prompt

You run a Python script named my_script.py directly from a terminal window. In the script environment, what is the value of the `__name__` variable? a) `__main__` b) `__my_script__` c) `my_script` d) `my_script.py`

a) `__main__`

Which information should you include in a multi-line docstring for a function? a) arguments, return values, and exceptions b) function name c) function parameters d) public methods and instance variables

a) arguments, return values, and exceptions

** This means what a) exponent b) modulo c) integer division d) PEMDAS

a) exponent

What does type(3.55) return? a) float b) int c) str d) all of the above

a) float

Which three data types can you use for dictionary keys? (Choose three.) a) float b) int c) lists d) other dictionaries e) string

a) float b) int e) string

Which expression defines an object named hiredate with a value of July 1, 2018? a) hiredate = datetime.date(year = 2018, month = 7, day = 1) b) hiredate = datetime.datetime(year = 2018, month = 7, day = 1) c) hiredate = datetime.timedate(year = 2018, month = 7, day = 1) d) hiredate = datetime.timedelta(days = 43282)

a) hiredate = datetime.date(year = 2018, month = 7, day = 1)

There are 23 students in a programming class. The teacher brings in a bag of candy with 126 pieces. Which statement would calculate the number of pieces that would be left over? a) left = 126 % 23 b) left = 126 // 23 c) left = 126 / 23 d) left = 23 % 126

a) left = 126 % 23

Which statement correctly casts the string to a list? a) letterList = list("This one") b) letterList = "This one".list() c) letterList = list."This one" d) letterList = "This one"

a) letterList = list("This one")

Which function from the math module can you use to round up the number 102.34 to 103? a) math.ceil ( ) b) math.trunc ( ) c) math.float ( ) d) math.floor ( )

a) math.ceil ( )

Which function from the math module can you use to round up the number 12.34 to 13? a) math.ceil ( ) b) math.float ( ) c) math.floor ( ) d) math.trunc ( )

a) math.ceil ( )

Which best describes the result of the following code? 1. numbers = [2, 3, 2] 2. total = 0 3. while numbers: 4. total += numbers.pop() a) numbers is an empty list and total is 7 b) numbers is [2, 3, 2] and total is 7 c) infinite loop d) All of the above

a) numbers is an empty list and total is 7

Which two functions can you use to determine whether a path leads to either a file or a directory? (Choose two.) a) os.path.isdir(path) b) os.path.isfile(path) c) os.path.exists(file_path) d) os.remove(file_path)

a) os.path.isdir(path) b) os.path.isfile(path)

Which choice will print the word "tac", given the following variable declaration? word = "cat" a) print(word[::-1]) b) print(word[::1]) c) print(word[0:1:2]) d) print(word[2:1:0])

a) print(word[::-1])

Which command should you use to generate text documentation for a Python module named py? a) pydoc program b) pydoc -h program.py c) pydoc -t program.py d) pydoc -w program

a) pydoc program

Which function returns only whole, even numbers from within the range from 1 to 1000? a) random.randrange(2, 1001, 2) b) random.randrange(1, 1001, 2) c) random.randint (1, 1000, 2) d) random.choice(1, 1000, even)

a) random.randrange(2, 1001, 2)

x = 3 y = "3" # get_diff takes an int and a str def get_diff(xint, ystr): # <function code needed here> if y.isdigit() == False: print('"y" is not an integer string') elif get_diff(x,y) == 0: print('x equal to y') else: print('x equal to y') To make this program work, printing "x equal to y", choose the best code to replace the above comment "# <function code needed here> " in the get_diff function. a) return int(ystr) - xint b) return str(ystr) - in(xint) c) return ystr - x d) return int(xint) - y

a) return int(ystr) - xint

Which is a valid way to initialize a Python list? a) scores = [11, 8, 0, 24, 31, 12, 19] b) listdef scores(11, 8, 0, 24, 31, 12, 19) c) scores.list(11, 8, 0, 24, 31, 12, 19) d) scores = {11:8:0:24:31:12:19}

a) scores = [11, 8, 0, 24, 31, 12, 19]

Which statement best describes a String in Python/Computer Science? a) sequence of characters b) series of 1's and 0's c) computer keyboard d) object existing in four dimensions

a) sequence of characters

Which of the following are valid expressions for the datetime.timedelta objects t1, t2, and t3? (Choose all that apply.) a) t1 = t2 - t3 b) t1 = 6 % t2 c) month = datetime.timedelta(1 month) d) year = datetime.timedelta(365 days)

a) t1 = t2 - t3 b) t1 = 6 % t2

Which of the following are valid expressions for the datetime.timedelta objects t1, t2, and t3? (Choose all that apply.) a) t1 = t2 - t3 b) month = datetime.timedelta(1 month) c) t1 = t3 % t2 d) year = datetime.timedelta(365 days)

a) t1 = t2 - t3 c) t1 = t3 % t2

Which choice is a valid Python code to store the length of the given string variable 'word' below in 'x'? word = "Python" a) x = len(word) b) x = word.len() c) x.length(word) d) for x in length of word

a) x = len(word)

Which choice best represents the output of the following code? student_name = "iteration" new_word = "" for letter in student_name[:3]: new_word += letter print(new_word) a) "ration" b) "ite" c) "iter" d) "ation"

b) "ite"

You perform the following Boolean comparison operation: (x >= 10) not (x < 20) and (x % 2 == 0) For which two numbers is the comparison operation True? (Choose two.) a) 10 b) 20 c) 25 d) 50

b) 20 d) 50

Choose the best representation of the output expected for the following code. 1. cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"] 2. for city in cities: 3. if city.startswith("P"): 4. print(city) 5. elif city.startswith("D"): 6. print(city) a) São PauloDubai b) Dubai c) São Paulo d) None of the above

b) Dubai

"Hello, world!" is a specialized program used specifically for Python. a) True b) False

b) False

A global variable is available from any Python module. a) True b) False

b) False

A new list is initialized, made of 2 lists, when the .extend() list method is used. a) True b) False

b) False

An infinite loop is a loop that runs until the value returned by the loop condition is False. a) True b) False

b) False

In Python string comparisons, lower case "a" is less than upper case "A". a) True b) False

b) False

In Python, strings can contain only letters a-z and A-Z. a) True b) False

b) False

In Python, we can use the "+" operator to add numbers, but not to add strings. a) True b) False

b) False

In the following for loop code, the variable name is "student" because it can only be called "student" and cannot be replaced with another valid variable name such as "pupil". 1. students = ["Alton", "Hiroto", "Skye", "Tobias"] 2. for student in students: 3. print("Hello", student) a) True b) False

b) False

The .append() method adds an item to the beginning of a list. a) True b) False

b) False

The .count() string method returns the number of times a for/in loop iterates. a) True b) False

b) False

The .insert() method overwrites (replaces) the list item at the selected index. a) True b) False

b) False

To read each line of a file as an item in a list, use .listread(). a) True b) False

b) False

When handling exceptions, Python code can include an else clause or a finally clause, but not both. a) True b) False

b) False

You can use the remove function to delete a specific file directory. a) True b) False

b) False

Which statement about local variables is true? a) A local variable can be read from the global scope. b) You can use the same variable name in multiple functions. c) A local variable in one function can be read from another function. d) A function can update a global variable in a local scope by using the same name for a local variable and assigning a new value.

b) You can use the same variable name in multiple functions.

Choose the item that best completes the following sentence: "A Python list..." a) uses index 1 for the first item in the list. b) can contain both strings and numbers together as list items. c) can contain either all strings or all numbers as list items, but not both together. d) cannot contain other Python lists

b) can contain both strings and numbers together as list items.

Which best describes a valid Python use of the following days List? a) days.append(1, "Wednesday") b) days.insert(1, "Wednesday") c) print(days[6]) d) All of the above

b) days.insert(1, "Wednesday")

Which of the following statements would return the current date and time? a) dt = today() b) dt = datetime.today() c) dt = date.today() d) dt = datetime.today

b) dt = datetime.today()

Which is not a start to a string iteration loop, given the following string variable assignment? word = "health" a) for letter in word: b) for word in letter: c) for ltr in word[1:]: d) for part in "health":

b) for word in letter:

Which code should you use to import a function named time from a Python module named datetime? a) import time b) from datetime import time c) import time fm datetime d) import time from datetime

b) from datetime import time

Which code should you use to import a function named abc from a Python module named xyz? a) import abc b) from xyz import abc c) import abc from xyz d) import mod xyz fn abc

b) from xyz import abc

Which process does Python use to optimize dictionary search capabilities? a) containment b) hashing c) iteration d) looping

b) hashing

Which expression defines an object named hiredate with a value of Jan 15, 2019? a) hiredate = datetime.datetime(year = 2019, month = 1, day = 15) b) hiredate = datetime.date(year = 2019, month = 1, day = 15) c) hiredate = datetime.timedate(year = 2019, month = 1, day = 15) d) hiredate = datetime.timedelta(days = 43282)

b) hiredate = datetime.date(year = 2019, month = 1, day = 15)

Which Boolean operator has the highest precedence? a) or b) is not c) do or do not

b) is not

Which Boolean operator has the highest precedence? a) and b) not c) or

b) not

Which code overwrites (replaces) the "0" with a "5" in the following numbers list? numbers = [1, 1, 0] a) numbers[3] = 5 b) numbers[2] = 5 c) numbers.append(5) d) numbers.insert(2,5)

b) numbers[2] = 5

Which function can you use to test whether an absolute or relative path to a folder is valid? a) os.path.commonpath(paths) b) os.path.exists(path) c) os.path.normpath(path) d) os.path.realpath(path)

b) os.path.exists(path)

Which of the following statements would display the current working directory? a) print('Working directory: ', os.printcwd()) b) print('Working directory: ', os.getcwd()) c) print('Working directory: ', getcwd()) d) print('Working directory: ', os.getdir())

b) print('Working directory: ', os.getcwd())

Given the following code, which choice is best to represent the first line in the text file books.txt in Title format, where every word is capitalized? books = open('books.txt', 'r') a) print(books[0].upper()) b) print(books.readline().title()) c) print(books.readline().upper()) d) All of the above

b) print(books.readline().title())

Given the following starting code: test1 = open('test1.txt', 'r') We can read 10 string characters from a file into memory by using which Python code? a) ten_char = test1.read(11) b) ten_char = test1.read(10) c) ten_char = test1[0:11] d) All of the above

b) ten_char = test1.read(10)

Complete the sentence to be true for code running in a Python environment. A local scope is created... a) when a function is created b) when a function is called c) when a function returns to its caller d) when a function is destroyed

b) when a function is called

Given x = 9, which line of code will evaluate False? a) x==9 b) x<3 c) 3<x d) x=3

b) x<3

When using the format() method, which placeholder outputs the variable x as a three-digit integer with two digits before and one digit after the decimal point (for example, 12.3)? a) {x:3.2f} b) {x:3.1f} c) {x:4.2f} d) {x:2.1f}

b) {x:3.1f}

When using printf-style string formatting, which conversion flag outputs a signed integer decimal? a) %x b) %c c) %d d) %s

c) %d

In an os function, which syntax can you use to move up one folder in the current directory structure? a) \\ b) \ c) . . d) /

c) . .

Which answer best describes what .strip() does in the following code sample? poem_line = poem1.readline().strip() a) .strip() removes leading and trailing parenthesis b) .strip() removes all whitespace in a string, including the '\n' formatting character c) .strip() removes leading and trailing whitespace, including the '\n' formatting character d) All of the above

c) .strip() removes leading and trailing whitespace, including the '\n' formatting character

Choose the best representation of the output expected for the following code. 1. numbers = "" 2. for x in range(0,5,2): 3. numbers += str(x) 4. print(numbers) a) 0 b) 5 c) 024 d) 24

c) 024

When using Python, which mathematic operation returns a value of 2? a) 42 / 4 b) 42 / / 4 c) 42 % 4 d) 42 ** . 4

c) 42 % 4

When using Python, what is the result of the mathematic operation 1 ** (2 * 3) / 4 + 5? a) 0.11 b) 0.67 c) 5.25 d) 6.50

c) 5.25

You are comparing two numerical values in the following operation: In [1]: 9 ___ 9 Out[1]: True Which operator correctly completes the operation? a) => b) =! c) >=

c) >=

Which statement about the datetime.datetime data type is true? a) All variables are optional. b) All variables are required. c) All date variables are required. d) All time variables are required.

c) All date variables are required.

You are performing the following operation: In [1]: 10 == 20 Out[1]: _____ What is the result of the operation? a) 0 b) 10 c) False d) True

c) False

Which attributes can you define for a time object? (Choose all that apply.) a) Month b) Day c) Hour d) Second e) Millisecond

c) Hour d) Second

Which two statements about a positional argument are true? (Choose two.) a) it can be whatever it wants to be in 2020 b) the argument can be commented out c) It is a required argument d) It is an optional argument e) It is always the first argument f) Its position depends on the command

c) It is a required argument f) Its position depends on the command

Given the code below, which statement would modify the date to Feb. 14, 2019? 1. from datetime import date 2. # assign a date 3. SomeDate = date(year = 2015, day = 28, month = 2) a) SomeDate.year = 2019 SomeDate.day = 14 b) SomeDate = SomeDate.replace(2019, 14) c) SomeDate = SomeDate.replace(year = 2019, day = 14) d) SomeDate.replace(year = 2019, day = 14)

c) SomeDate = SomeDate.replace(year = 2019, day = 14)

Which string defines a heterogeneous tuple? a) T = ("switch",) b) T = tuple(L) c) T = ("Tobias", 23, 25.3, []) d) T = (10, -4, 59, 58, 23, 50)

c) T = ("Tobias", 23, 25.3, [])

Choose the item that best completes the sentence: "A Python list..." a) cannot be changed after initialization. b) can add items of the same type only. c) can add items to the end of the list using the .append() method. d) always appends to index 0 (zero).

c) can add items to the end of the list using the .append() method.

Which code is the best use of Python that deletes the "5" in the following numbers list? numbers = [7, 1, 5, 8, 0] a) numbers[3] = "" b) numbers[2].delete() c) del numbers[2] d) numbers.remove(2)

c) del numbers[2]

Which code is the best use of Python to iterate through the list "numbers"? numbers = [7, 1, 5, 8, 0] a) for range[5] in numbers: b) for int in list: c) for number in numbers: d) all of the above

c) for number in numbers:

Which is the best choice to complete the following sentence? Opening a file in Python using read mode ('r')... a) reads the file as a string 10 characters at a time. b) creates a new file c) makes file contents available for Python to read from the file. d) erases all of the contents of the file being opened.

c) makes file contents available for Python to read from the file.

You run a Python script named my_script.py by importing it as a module into a script named second_script.py. In the script environment, what is the value of the `__name__` variable? a) __main__ b) __my_script__ c) my_script d) my_script.py

c) my_script

What type of loop should you use to iterate over the elements of a simple table (two-dimensional list)? a) compound b) for c) nested d) while

c) nested

Which function can you use to list the contents of the current working directory? a) os.chdir() b) os.getcwd() c) os.listdir() d) os.rmdir()

c) os.listdir()

Which function can you use to list the contents of the current working directory? a) os.rmdir() b) os.chdir() c) os.listdir() d) os.getcwd()

c) os.listdir()

Which function can you use to test whether an absolute or relative path to a folder is valid? a) os.path.commonpath(paths) b) os.path.normpath(path) c) os.path.exists(path) d) os.path.realpath(path)

c) os.path.exists(path)

Which two os module functions can you use to delete a specific file? (Choose two.) a) os.delete b) os.path.re c) os.remove d) os.unlink

c) os.remove d) os.unlink

Which type of statement should you use as a placeholder for future function code? a) break b) continue c) pass d) place

c) pass

Which Python code results in output of a sorted scores list with changing the original scores list below to be in a sort order? scores = [ 0, 5, 2, 11, 1, 9, 7] a) print(scores.reverse()) b) print(sorted(scores)) c) print(scores.sort()) d) All of the above

c) print(scores.sort())

Which Python code results in output of a sorted scores list without changing the original scores list below? scores = [ 0, 5, 2, 11, 1, 9, 7] a) print(scores) b) print(scores.sort()) c) print(sorted(scores)) d) All of the above

c) print(sorted(scores))

Which function returns only whole, even numbers from within the range from 1 to 100? a) random.choice(1, 100, even) b) random.randint (1, 100, 2) c) random.randrange(2, 101, 2) d) random.uniform(1, 100)

c) random.randrange(2, 101, 2)

What is the best choice to complete the following sentence? Using .readlines() to read an open file results in... a) reading one line at a time. b) reading the entire file as a string. c) reading each line in the file as an item in a list. d) All of the above

c) reading each line in the file as an item in a list.

Which Python code results in reversing the order of the scores list? scores = [ 0, 5, 2, 11, 1, 9, 7] a) scores{-1} b) reverse(scores) c) scores.reverse() d) All of the above

c) scores.reverse()

When using .readlines(), it is common to remove the last character of each string in the generated list, because... a) .readlines() adds a character that cannot be processed. b) the last character is always duplicated when using .readlines(). c) the last character is typically a whitespace newline character, "\n". d) All of the above

c) the last character is typically a whitespace newline character, "\n".

Which of the following statements would get the total number of seconds given the following code? 1. from datetime import timedelta 2. td = timedelta(days = 3, hours = 2) a) totSec = td.total_seconds b) totSec = td.totalseconds() c) totSec = td.total_seconds() d) totSec = total_seconds()

c) totSec = td.total_seconds()

Which choice will return -1, given the following variable assignment below? word = "Python" a) word.find("P") b) word.find("y") c) word.find("Z") d) word.find("n")

c) word.find("Z")

When using the str.format() method, which flag places a - (negative sign) in front of negative numbers? a) - b) ^ c) + d) "

d) "

Which is an example of a valid one-line docstring? a) # Return the path of the current working directory b) // Return the path of the current working directory // c) docstring("Return the path of the current working directory.") d) """Return the path of the current working directory."""

d) """Return the path of the current working directory."""

Given that the file school_names contains the following text: *City*Elementary* *Maths*High*School* *Early*Learner*PreSchool* Which answer best describes the output of the following code? 1. schools = open("school_names.txt", "r") 2. name = schools.readline().strip('*\n') 3. while name: 4. if name.startswith("M"): 5. print(name) 6. else: 7. pass 8. name = schools.readline().strip('*\n') a) "Maths High School" b) "*Maths*High*School*" c) "MathsHighSchool" d) "Maths*High*School"

d) "Maths*High*School"

When using printf-style string formatting, which conversion flag outputs a single character? a) %s b) %x c) %d d) %c

d) %c

In an os function, which syntax can you use to move up one folder in the current directory structure? a) / b) \ c) \\ d) . .

d) . .

Which function displays a date object in the form Monday, January 01, 2018? a) .strftime("%A, %B %D, %Y") b) .strftime("%A, %M %d, %Y") c) .strftime("%A, %M %D, %Y") d) .strftime("%A, %B %d, %Y")

d) .strftime("%A, %B %d, %Y")

Choose the best representation of the output expected for the following code. 1. numbers = "" 2. for x in range(7): 3. numbers += str(x) 4. print(numbers) a) 0 b) 7 c) 1234567 d) 0123456

d) 0123456

Choose the best representation of the output expected for the following code. 1. numbers = "" 2. for x in range(2,8,2): 3. numbers += str(x) 4. print(numbers) a) 2 b) 8 c) 2468 d) 246

d) 246

When using Python, what is the result of the mathematic operation 1 ** (2 * 2) / 4 + 5? a) 0.11 b) 0.67 c) 6.50 d) 5.25

d) 5.25

Which element should come first in a multi-line docstring for a function? a) A blank line b) The function arguments c) The function parameters d) A summary line that describes the function as a command

d) A summary line that describes the function as a command

Which statement about the datetime.datetime data type is true? a) All variables are optional. b) All variables are required. c) All time variables are required. d) All date variables are required.

d) All date variables are required.

Which best describes the valid Python use of the following days List? a) days.append("Wednesday") b) days.append(14) c) print(days[-1]) d) All of the above

d) All of the above

name = "Tobias" print(name == "Alton") What is the output from running the above code? a) "Tobias = Alton" b) "Alton" c) True d) False

d) False

What is the result of not setting the value of the year attribute of a date object? a) The year defaults to 0. b) The year defaults to the current year. c) The year defaults to 9999. d) The object is invalid.

d) The object is invalid.

Which process can you use to assign the values of a tuple to multiple variables? a) Convert the tuple into a list b) Create a homogeneous tuple c) Slice the tuple d) Unpack the tuple

d) Unpack the tuple

Which element stores Python script command-line arguments and options? a) arg b) argc c) argparse d) argv

d) argv

Which clause should you use for code that you want to execute regardless of whether an exception is raised? a) else b) elseif c) except d) finally

d) finally

Which code places another "2" integer to the end of the following list? numbers = [1, 1, 2] a) numbers + 2 b) numbers.add(2) c) numbers += 2 d) numbers.append(2)

d) numbers.append(2)

Which function can you use to delete an empty folder? a) os.chdir() b) os.getcwd() c) os.listdir() d) os.rmdir()

d) os.rmdir()

There are 23 students in a programming class. The teacher brings in a bag of candy with 126 pieces. Which statement would calculate the number of pieces each student could receive? a) pieces = 126 % 23 b) pieces = 126 / 23 c) pieces = 23 // 126 d) pieces = 126 // 23

d) pieces = 126 // 23

Which is valid Python code that will print "Green", given the following code? colors = ["Red", "Blue", "Green", "Yellow"] a) print(colors[0]) b) print(colors[4]) c) print(colors[3]) d) print(colors[2])

d) print(colors[2])

Which command should you use to generate HTML documentation for a Python module named py? a) pydoc program b) pydoc -h program.py c) pydoc -t program.py d) pydoc -w program

d) pydoc -w program

After we open a file (first_test) using: test1 = open('test1.txt', 'r') we can read the file into memory with which Python code? a) for test_data in test1: b) test_data.open.read(test1) c) test_data = open(test1) d) test_data = test1.read()

d) test_data = test1.read()

The .close method conserves system memory because... a) file .close() compresses files by 50%. b) file .close() closes any unused files created by Python. c) file .close() permanently deletes all text data in the target file. d) the file .close() method removes the reference created from file open() function.

d) the file .close() method removes the reference created from file open() function.

Choose the item that best completes the following sentence: "After using an insert on a Python list..." a) one of the index values gets overwritten. b) an error occurs if the inserted object is not of the same type of the other list items. c) the length of the list remains the same. d) the length of the list increases by 1.

d) the length of the list increases by 1.

What type of loop should you use to repeat a code process as long as a condition resolves as `True`? a) compound b) for c) nested d) while

d) while

Which statement ensures that a file will be closed even when an exception is raised? a) else: file.close() b) file = open(file_path, mode) c) file.close() d) with open(file_path, mode) as file:

d) with open(file_path, mode) as file:

In what format does a dictionary store information? a) (key, value) b) [key:value] c) {key, value} d) {key:value}

d) {key:value}

hot_plate = True if hot_plate: print("Be careful, hot plate!") else: print("The plate is ready.") What is the output from running the above code? a) "Be careful, hot plate!" b) "The plate is ready." c) "True" d) NameError

a) "Be careful, hot plate!"

x = 0 while True: if x < 10: print('run forever') x += 1 else: break What is the output from running the above code most like? a) "run forever" (10 times) b) "run forever" (9 times) c) "run forever" d) No Output

a) "run forever" (10 times)

Which is a valid Python code comment? a) # use comments to describe the function of code. b) comments make code easier to update. c) [comment] comments can provide use instructions for other developers. d) (comment) warnings can be placed in comments.

a) # use comments to describe the function of code.

What is the value of x after the following code is run? x = 2 y = 1 x += y + 1 a) 4 b) 3 c) 1 d) 2

a) 4

print("It's time to code") What is the output of the above code? a) It's time to code b) It"s time to code c) Its time to code d) an error

a) It's time to code

Which is not a way to run a code cell in a Jupyter Notebook? a) Shift + R b) Ctrl + Enter c) Shift + Enter d) Menu: Cell...> Run Cells

a) Shift + R

assignment = 25 if assignment = 25: print('use "=" to assign values') else: pass What is the output of the above code? a) SyntaxError b) "use "=" to assign values" c) True d) No Output

a) SyntaxError

For the code: x = 3 + 9 * 2 the value of x is 21 when applying order of operations. a) True b) False

a) True

Function names cannot begin with a number as the first character. a) True b) False

a) True

Jupyter Notebooks have code cells and markdown cells. a) True b) False

a) True

Like else, the elif can execute only when the previous if conditional evaluates False (shown in the below code sample). if response == 3: return "Correct" elif response <= 0: return "Correct" else: return "Incorrect" a) True b) False

a) True

The double equal sign (==) is used to compare values. a) True b) False

a) True

name = "SKYE HOMSI" print("y" in name.lower()) What is the output from the above code? a) True b) False c) "skye homsi" d) 3

a) True

while 3 < 5: is a forever loop just like while True: is. a) True b) False

a) True

answer = input("enter your answer: ") print(10 + answer) If user input is 38, what is the output of the above code? a) TypeError b) 1038 c) 10answer d) 48

a) TypeError

count = 1 while count >= 1: print("loop") count +=1 What is the output from running the above code most like? a) forever loop b) "loop" c) "loop" (2 times) d) no output

a) forever loop

1. 2. score = add_score(190) 3. 4. print(name, "your score is", score) 5. At which line above should the following add_score() function definition be inserted so the program runs without error? def add_score(current): return current + 10 a) line 1 b) line 3 c) line 5 d) any of the above

a) line 1

\\\\ What is the best choice of code to create the output shown above? a) print("\\\\\\\\") b) print("'\''\''\''\''\'") c) print("\\\\") d) print(\\\\)

a) print("\\\\\\\\")

if x < 0: print("-") else: if y >= 0: print("+/+") else: print("+/-") Which values for x and y result in the output "+/-"? (Choose the best answer.) a) x = 0 and y = -1 b) x = 1 and y = 0 c) x = -1 and y = 1 d) x = 0 and y = 0

a) x = 0 and y = -1

if x < 0: print("-") else: if y >= 0: print("+/+") else: print("+/-") The nested conditional code is sure to be run if ___. (Choose the best answer.) a) x = 1 b) y = 1 c) y = -1 d) x = -1

a) x = 1

id = 3556 if id > 2999: print(id, "is a new student") else: print(id, "is an existing student") What is the output of the above line of code? a) "id, is a new student" b) "3556 is a new student" c) "id, is an existing student" d) "3556 is an existing student"

b) "3556 is a new student"

vehicle_type = "Truck" if vehicle_type.upper().startswith("P"): print(vehicle_type, 'starts with "P"') else: print(vehicle_type, 'does not start with "P"') What is the output from running the above code? a) "Truck starts with "P"" b) "Truck does not start with "P"" c) "True" d) "False"

b) "Truck does not start with "P""

Which print output is the result of the following code? word = "windows" print(word[-1]) a) "w" b) "s" c) "i" d) "" (empty string)

b) "s"

def add_numbers(num_1, num_2 = 10): return num_1 + num_2 Choose the correct output of calling the function above using the following code: print(add_numbers(100)) a) 100 b) 110 c) 200 d) An Error

b) 110

calculation = 5 + 15 / 5 + 3 * 2 - 1 print(calculation) What is the best estimate for the output of the above code? a) 13 b) 13.0 c) 9 d) 9.0

b) 13.0

num_1 = "" num_temp = "" num_final = "" while True: num_1 = input("Enter an integer: ") if num_1.isdigit(): num_final = num_temp + num_1 num_temp = num_final else: print(num_final) break What is the output from running the above code using the following input at the Enter an integer: prompt? 1st input: 3 2nd input: 4 3rd input: five 4th input: 6 a) 34five b) 34 c) 34five6 d) 7

b) 34

How do you know if you have written your code correctly and there are no errors? a) Print your code b) Debug your code c) View your code d) Reset your code

b) Debug your code

Function calls should be placed at the beginning of a code page, and functions should be placed later and toward the end of the code. a) True b) False

b) False

In the for loop below, the variable "word" is an arbitrary variable name. Any valid variable name can be used since its value is assigned only within this loop. for letter in word: print(letter) a) True b) False

b) False

Nested Conditional code always runs all sub-conditions that are indented under if statements. a) True b) False

b) False

Python Function return values must be stored in variables. a) True b) False

b) False

Python cannot display quotes in strings using print(). a) True b) False

b) False

The code print("I am", 17, "years old") will output: I am17years old a) True b) False

b) False

The first character in a string is at index 1. a) True b) False

b) False

The string method .swapcase() converts from string to integer. a) True b) False

b) False

The type() function is used to change from one data type to another. a) True b) False

b) False

while True: will loop forever but can be interrupted using the Python keyword "end" inside the loop. a) True b) False

b) False

Which is an example of Python string addition that will run without error? a) new_string = Hello + World! b) Falsenew_string = "Hello " + "World!" c) new_string = "Hello ' + "World!' d) all of the above

b) Falsenew_string = "Hello " + "World!"

Which version of Python does this course cover? a) Python 2 b) Python 3 c) Python 4 d) Python 5

b) Python 3

What is the output of the following code? print("She said, \"Who's there?\"") a) She said, \Who's there?\ b) She said, "Who's there?" c) 'She said, "Who's there?"' d) "She said, Who's there?"

b) She said, "Who's there?"

"Hello".isalpha() What is the output of the above code? a) Hello b) True c) False d) Error

b) True

What is the output of the following code? name = 123 if name.startswith("a"): print("welcome") else: print("please wait") a) please wait b) an error message c) none of the above d) welcome

b) an error message

What are the advantages of creating and using functions in code? (Choose all that apply.) a) faster running code b) code reuse c) easier testing d) Boolean string testing

b) code reuse c) easier testing

A function with 2 integer parameters could start with which definition? a) funct add_numbers(num_1, num_2): b) def add_numbers(num_1, num_2): c) def 2_numbers(num_1, num_2): d) FUNCTION add_numbers(x, y):

b) def add_numbers(num_1, num_2):

1. greet(name) 2. name = input("enter your name: ") 3. greet(name) 4. def greet(person): 5. print("Hi,", person) 6. greet(name) Which line or lines need to be removed from the above code so the program prints a greeting without error? a) lines 1 and 2 b) lines 1 and 3 c) line 1 only d) line 3 only

b) lines 1 and 3

Given the code below and entering "Colette" for user_name input: python total_cost = 22.95 user_name = input("Enter your name: ") Choose the print statement that will output: Colette - the total is $ 22.95 for today's purchase a) print(Colette, "- the total is $", total_cost, "for today's purchase") b) print(user_name, "- the total is $", total_cost, "for today's purchase") c) print(Colette, '- the total is $', total_cost, 'for todays purchase') d) print("user_name", "- the total is $", "total_cost", "for today's purchase")

b) print(user_name, "- the total is $", total_cost, "for today's purchase")

Which choice will print the first half of the word "Consequences", given the following variable declaration? word = "Consequences" a) print(word[6:]) b) print(word[:6]) c) print(word[1:7]) d) print(word[7:1])

b) print(word[:6])

name = "skye homsi" name_1 = name.title() name_2 = name_1.swapcase() print(name_2) What is the output from the above code? a) "Skye Homsi" b) "SKYE HOMSI" c) "skye homsi" d) "sKYE hOMSI"

d) "sKYE hOMSI"

name = "Jin Xu" if type(name) == type("Hello"): print(name, "is a string entry") else: print(name, "is not a string entry") What is the output from running the above line of code? a) "Hello Jin Xu" b) "Jin Xu is a not string entry" c) "Jin Xu is a string entry" d) "string"

c) "Jin Xu is a string entry"

x = 0 while x < 5: x += 1 print('loop') What is the output from running the above code most like? a) "loop" b) "loop" (4 times) c) "loop" (5 times) d) forever loop

c) "loop" (5 times)

def low_case(words_in): return words_in.lower() Choose the correct output of calling the function above using the following code: words_lower = low_case("Return THIS lower") print(words_lower) a) "Return THIS lower" b) No Output c) "return this lower" d) An Error

c) "return this lower"

Which contains only integers? (ignore the commas) a) Q, W, E, R, T, Y, a, s, d, f b) -2, -1, -0.5, 0, 0.5, 1, 2 c) 1, 2, 0, -3, 2, -5 d) 3, 2, 1, *, +, =, -

c) 1, 2, 0, -3, 2, -5

x = 3 y = 4 calculation = x*y print(calculation) What is the best estimate for the output of the above code? a) 12.0 b) 9.0 c) 12 d) 9

c) 12

def add_num(num_1 = 10): print(num_1 + num_1) Choose the correct output of calling the above function using the following code: add_num() a) 0 b) 10 c) 20 d) An Error

c) 20

def add_num(num_1 = 10): return num_1 + num_1 Choose the correct output of calling the function above using the following code: print(add_num(100)) a) 20 b) 100 c) 200 d) an error

c) 200

1. name = input("enter your name") 2. print(name, "your score is", score) 3. score = 199 Order the above numbered code lines into the proper sequence. a) 1,2,3 b) 2,3,1 c) 3,1,2 d) 3,2,1

c) 3,1,2

What will be displayed by the following code? count = 0 while count < 5: print("Hello", end = " ") count += 1 a) Hello Hello Hello Hello b) Hello, Hello, Hello, Hello, Hello, Hello c) Hello Hello Hello Hello Hello d) Hello Hello Hello Hello Hello Hello

c) Hello Hello Hello Hello Hello

PriNt("Hello World!") will not output the message "Hello World!". What will it result in? a) TypeError b) SyntaxError c) NameError d) all of the above

c) NameError

What does the Python code: score = 3 + "45" result in? a) 48 b) 345 c) TypeError d) type()

c) TypeError

Choose the correct statement. a) Variables only represent strings in Python. b) The same variable in Python can be represented in either upper or lower case. c) Variables in Python can be initialized using the equals sign (=). d) New variables always start out as zero.

c) Variables in Python can be initialized using the equals sign (=).

answer = input("enter your answer: ") print("You entered " + answer) If user input is 38, what is the output of the above code? a) TypeError b) Syntax Error c) You entered 38 d) You entered enter your answer

c) You entered 38

Which is an example of the proper use of the Python input() function? a) answer = input(enter your answer: ) b) answer = INPUT(enter your answer: ) c) answer = input("enter your answer: ") d) answer = INPUT("enter your answer: ")

c) answer = input("enter your answer: ")

Which is a properly formatted Python print() function example? a) print("Welcome the", 3, New students!) b) print("Welcome the", 3 + New students!) c) print("Welcome the", 3, "New students!") d) print("Welcome the", 3 + " New students!")

c) print("Welcome the", 3, "New students!")

Which statement sets the variable s to a value of "Chapter1"? a) s = input("Chapter" + str(1)) b) s = "Chapter" + 1 c) s = "Chapter" + str(1) d) print("Chapter", "1")

c) s = "Chapter" + str(1)

year = "2001" if year.isdigit(): print(year, "is all digits") else: pass What is the output from running the above code? a) "True" b) "False" c) No Output d) "2001 is all digits"

d) "2001 is all digits"

day = "monday" if day.capitalize() == "Monday": print("Start the week!") else: pass What is the output from running the above code? a) True b) False c) No Output d) "Start the week!"

d) "Start the week!"

size_num = "8 9 10" size = "8" # user input if size.isdigit() == False: print("Invalid: size should only use digits") elif int(size) < 8: print("size is too low") elif size in size_num: print("size is recorded") else: print("size is too high") What is the output from running the above code? a) "Invalid: size should only use digits" b) "size is too high" c) "size is too low" d) "size is recorded"

d) "size is recorded"

time = 3 while True: print('time is', time) if time == 3: time = 4 else: break What is the output from running the above code most like? a) "time is 3" b) "time is 4" c) no output d) "time is 3" & "time is 4"

d) "time is 3" & "time is 4"

What is the order of precedence (from first to last) of the math operators? a) *, +, -, / b) *, +, /, - c) +, -, /, * d) *, /, +, -

d) *, /, +, -

Which code formats the string "Green" to "GREEN"? a) .isupper() b) .capitalize() c) .istitle() d) .upper()

d) .upper()

x = 3 y = 3 calculation = x/y print(calculation) What is the best estimate for the output of the above code? a) 9 b) 9.0 c) "1" d) 1.0

d) 1.0

length = "33" length.isalnum() What is the output of the above code? a) "33" b) Error c) False d) True

d) True

answer = input("enter your answer: ") print(10 + answer) If user input is 38, what is the output of the above code? a) 48 b) 1038 c) 10answer d) TypeError

d) TypeError

Choose the correct statement. a) A variable name in Python cannot contain numbers. b) A variable value in Python cannot be updated. c) Variables are updated in Python using the keyword "new". d) Variable values in Python can change type, from integer to string

d) Variable values in Python can change type, from integer to string

def ignore_case(name): answer = "" while answer.isalpha() == False: answer = input("enter last name: ") return answer.lower() == name.lower() When will the ignore_case function exit the while loop? a) When answer == name b) When answer.lower() == name.lower() c) When a digit is entered at the input prompt d) When only letters are entered at the input prompt

d) When only letters are entered at the input prompt

What does type(1024) return? a) all of the below b) str c) float d) int

d) int

num_1 = 3 num_2 = "8" What is the minimum code to mathematically add num_1 to num_2? a) num_1 + str(num_2) b) int(num_1) + str(num_2) c) int(num_1) + int(num_2) d) num_1 + int(num_2)

d) num_1 + int(num_2)

Hello World! What is the best choice of code to create the output shown above? a) print("Hello\tWorld!") b) print("Hello\pWorld!") c) print("Hello World!") d) print("Hello\nWorld!")

d) print("Hello\nWorld!")

Choose the statement that will print the letter "d", given the variable declaration word = "windows" a) print(word[-2]) b) print(word[-1]) c) print(word[2]) d) print(word[3])

d) print(word[3])

def show_name(): print("Tobias Ledford") Which code calls the function in the above code? a) show_name.run() b) open(show_name) c) run show_name d) show_name()

d) show_name()

What does type("Hello World!") return? a) all of the below b) int c) float d) str

d) str

For the code x >= y which x and y values evaluate True? a) x = 3, y = 4 b) x = "Z", y = "a" c) x = 0, y = 1 d) x = "a", y = "A"

d) x = "a", y = "A"


Related study sets

History 170: InQuizitive chapters 1-4 (Unit 1)

View Set

Fortinet NSE 4 6.2 infastructure

View Set

Chapter 5 Homeowners Policy P&C Test

View Set

Physics and Human Affairs Test 2

View Set

Oral portion question and answer italian

View Set

CHAPTER 7: Quality and Innovation in Product and Process Design (TF)

View Set