CSC121-H101: Python Programming exams

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

Which method or operator can be used to concatenate lists?

+

What are the values that the variable num contains through the iterations of the following for loop? for num in range(4): 1, 2, 3, 4 0, 1, 2, 3, 4 1, 2, 3, 0, 1, 2, 3

0, 1, 2, 3 21/25

t will be displayed after the following code is executed? def pass_it(x, y): z = x*y result = get_result(z) return(result) def get_result(number): z = number + 2 return(z) num1 = 3 num2 = 4 answer = pass_it(num1, num2) print(answer) 12 9 14 Nothing, this code contains a syntax error

14

What are the values that the variable num contains through the iterations of the following for loop? for num in range(2, 9, 2): 2, 3, 4, 5, 6, 7, 8, 9 2, 5, 8 2, 4, 6, 8 1, 3, 5, 7, 9

2, 4, 6, 8

at will display after the following code is executed? def main(): print("The answer is", magic(5)) def magic(num): answer = num + 2 * 10 return answer main() 70 25 100 the statement will cause a syntax error

25

What will be displayed after the following code is executed? total = 0 for count in range(4,6): total += count print(total) 4 9 4 5 6 4 5 9

4 9

hat will be the output after the following code is executed? def pass_it(x, y): z = y**x return(z) num1 = 3 num2 = 4 answer = pass_it(num1, num2) print(answer) 81 64 12 None

64

A set of statements that belong together as a group and contribute to the function definition is known as a header block return parameter

Block

What will be the output after the following code is executed and the user enters 75 and 0 at the first two prompts? def main(): try: total = int(input("Enter total cost of items? ")) num_items = int(input("Number of items ")) average = total / num_items except ZeroDivisionError: print('ERROR: cannot have 0 items') except ValueError: print('ERROR: number of items cannot be negative') main() Question 10 options: ERROR: cannot have 0 items ERROR: number of items can't be negative 0 Nothing; there is no print statement to display average.

ERROR: cannot have 0 items

What will be the output after the following code is executed and the user enters 75 and -5 at the first two prompts? def main(): try: total = int(input("Enter total cost of items? ")) num_items = int(input("Number of items ")) average = total / num_items except ZeroDivisionError: print('ERROR: cannot have 0 items') except ValueError: print('ERROR: number of items cannot be negative') main() Question 3 options: ERROR: cannot have 0 items ERROR: cannot have 0 items ERROR: number of items can't be negative ERROR: number of items can't be negative Nothing; there is no print statement to display average. The ValueError will not catch the error.

ERROR: number of items can't be negative

A local variable can be accessed from anywhere in the program. T/F

False A local variable in Python can only be accessed within the scope of the function or block where it is defined.

A look-back gives information about the line number(s) that caused an exception. Question 20 options:TrueFalse

False A look-back, as described, doesn't directly give information about the line number(s) that caused an exception. When an exception occurs in Python, the interpreter provides a traceback that includes the sequence of calls leading to the exception. This traceback includes the file names and line numbers, showing where the exception occurred. So, it's the traceback information that provides details about the line number(s) that caused an exception, not a concept referred to as "look-back" in standard Python terminology.

A CPU-controlled loop causes a statement or set of statements to repeat as long as the condition is true. TrueFalse

False Condition-Controlled Loop

Tuples are refutable sequences which means that once a tuple is created, it cannot be changed. Question 22 options:TrueFalse

False Immutable

Arguments are passed by data type to the corresponding parameter variables in a function. T/F

False In Python, arguments are passed by position, not by data type. The value of the argument is assigned to the corresponding parameter variable in the function. 24/25

Arrays, which are allowed by most other programming languages, have more capabilities than Python list structures. Question 5 options:TrueFalse

False In Python, lists are quite flexible and powerful data structures, and for many purposes, they offer similar or even more capabilities compared to arrays in other programming languages. Python lists are dynamic arrays that can hold elements of different data types, and they can be resized easily. Python lists provide a variety of built-in methods and operations for manipulation, slicing, and iteration. Additionally, Python supports various libraries, such as NumPy, which introduces arrays with additional functionalities like element-wise operations, mathematical operations, and multi-dimensional arrays. So, while Python doesn't have a built-in array type, the combination of lists and specialized libraries makes Python quite capable in terms of array-like functionalities.

The addToIt method is commonly used to add items to a list. Question 17 options:TrueFalse

False In Python, the common method for adding items to a list is the append() method. For example: my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] If addToIt is a custom method that someone has defined, its usage would depend on the specific implementation within that code. However, it's not a standard or widely recognized method in the Python language for adding items to a list.

Each element in a tuple has an influx that specifies its position in the tuple. Question 13 options:TrueFalse

False In Python, the position of an element in a tuple (or any iterable) is determined by its index, not by an "influx." The index is an integer that represents the position of the element in the tuple, and it starts from 0 for the first element. For example: my_tuple = (10, 20, 30) # Index 0 corresponds to the first element print(my_tuple[0]) # Output: 10 # Index 1 corresponds to the second element print(my_tuple[1]) # Output: 20 # Index 2 corresponds to the third element print(my_tuple[2]) # Output: 30 So, elements in a tuple are accessed by their index, not by an "influx."

In Python, there is nothing that can be done if the program tries to access a file to read that does not exist. Question 8 options:TrueFalse

False In Python, you can handle the case where a program tries to access a file that does not exist. If you attempt to open a file that doesn't exist in 'r' (read) mode, Python will raise a FileNotFoundError exception. You can use a try-except block to catch this exception and handle it gracefully in your code. This allows you to provide feedback to the user or take alternative actions when a file is not found.

It is not possible to create a while loop that determines when the end of a file has been reached. Question 19 options:TrueFalse

False It is indeed possible to create a while loop that determines when the end of a file has been reached in Python. The read method on a file object returns an empty string when the end of the file is reached. You can use this behavior to construct a while loop that continues reading lines from a file until reaching the end. Here's a simple example: with open('example.txt', 'r') as file: line = file.readline() while line: # Process the line print(line.strip()) line = file.readline() In this example, the loop continues as long as line is not an empty string, which happens when the end of the file is reached.

A trotting total is a sum of numbers that accumulates with each iteration of the loop. TrueFalse

False Running Total

The min() function returns the item that has the lowest value in the sequence. Question 8 options:TrueFalse

False The min() function in Python returns the smallest of the input values or items in a sequence (e.g., a list, tuple, or string), but it doesn't return the item itself. Instead, it returns the minimum value. Here's an example: my_list = [3, 1, 4, 1, 5, 9, 2] # Using min() to find the minimum value in the list minimum_value = min(my_list) print(minimum_value) This will output: 1 In this case, min() returns the smallest value in the list, which is 1. If you want to find the item itself (not just its value), you would need to use additional methods or techniques.

To get the total number of iterations in a nested loop, add the number of iterations in the inner loop to the number in the outer loop. TrueFalse

False To get the total number of iterations in a nested loop, you multiply the number of iterations in the inner loop by the number of iterations in the outer loop.

The backup method reverses the order of the items in a list. Question 21 options:TrueFalse

False To reverse the order of items in a list, you can use the reverse() method: my_list = [1, 2, 3, 4, 5] my_list.reverse() print(my_list) This would output: [5, 4, 3, 2, 1] So, while there is no "backup" method for reversing a list, you can achieve this with the reverse() method. If "backup" is a custom method defined in your code or part of a specific library, its behavior would depend on its implementation.

When a piece of data is read from a file, it is copied from the file into the program. Question 13 options:TrueFalse

False When a piece of data is written to a file, Data is copied from a variable in RAM to a file. According to the fundamentals of basic programming skills and File Access Methods (FAM), it is clearly stated that whenever a program wishes to read information or data that is stored in a file, then all of that data present in the file first needs to be brought into the main memory (also known as RAM) in order for it to be read properly by the currently executing program. And this process is achieved by bringing that piece of information present in the file and copying it into some temporary local variables that get created within the RAM of your system (and not in the program itself as mentioned in the given statement)

When a program needs to save data for later use, it writes the data in a temporary memory location. Question 1 options:TrueFalse

False When a program needs to save data for later use, it typically writes the data to a more persistent storage location, such as a file or a database, rather than a temporary memory location. Temporary memory locations are often used for short-term storage during program execution, but they are not suitable for saving data permanently. when a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time.

When data is written to a file, it is described as an input file. Question 2 options:TrueFalse

False When data is written to a file, it is more accurately described as an output file. An input file is usually considered the source from which a program reads data. In contrast, an output file is where the program writes or saves data. So, if you are writing data to a file, it's often referred to as writing to an output file. Output file is used to describe a file that data is written to

When data is written to a file, it is described as a retrieved file. Question 4 options:TrueFalse

False When data is written to a file, it is typically described as an output file or written file. On the other hand, a retrieved file usually refers to a file that has been read or loaded into a program. The terminology can vary, but writing data to a file is commonly associated with terms like output or writing, not retrieval.

The plot_it package is a library you can use in Python to create two-dimensional charts and graphs. Question 11 options:TrueFalse

False matplotlib package is a library for creating two-dimensional charts and graphs. Not apart of the standard python library, so you have to install it separately, after installing python.contains a module named pyplot that is imported.import matplotlib.pyplot

An organizational chart is a visual representation of the relationships between functions. T/F

False?

Which of the following functions returns the largest integer that is less than or equal to its argument? floor ceil lesser greater

Floor

A __________ variable is accessible to all the functions in a program file. keyword local global string

Global

It is recommended that programmers avoid using __________ variables in a program whenever possible. local global string keyword

Global

__________ is the process of inspecting data that has been input into a program in order to ensure that the data is valid before it is used in a computation. Input validation Correcting data Data validation Correcting input

Input validation

hat does the following program do? import turtle def main(): turtle.hideturtle() square(100,0,50,'blue') def square(x, y, width, color): turtle.penup() turtle.goto(x, y) turtle.fillcolor(color) turtle.pendown() turtle.begin_fill() for count in range(4): turtle.forward(width) turtle.left(90) turtle.end_fill() main() It draws a blue square at coordinates (100, 0), 50 pixels wide, starting at the top right corner. It draws a blue square at coordinates (0, 50), 100 pixels wide, starting at the top

It draws a blue square at coordinates (100, 0), 50 pixels wide, starting at the top right corner.

A __________ variable is created inside a function. global constant named constant local

Local

The Python standard library's __________ module contains numerous functions that can be used in mathematical calculations. math string random number

Math

What will be the output after the following code is executed? def pass_it(x, y): z = x , ", " , y num1 = 4 num2 = 8 answer = pass_it(num1, num2) print(answer) 4, 8 8, 4 48 None

None

What is an advantage of using a tuple rather than a list? Question 12 options: Tuples are not limited in size. Tuples can include any data as an element. Processing a tuple is faster than processing a list. There is never an advantage to using a tuple.

Processing a tuple is faster than processing a list.

In a value-returning function, the value of the expression that follows the keyword __________ will be sent back to the part of the program that called the function. def result sent return

Return

Python comes with __________ functions that have already been prewritten for the programmer. standard library custom key

Standard

The __________ design technique can be used to break down an algorithm into functions. subtask block top-down simplification

Top-down

A input validation loop is sometimes called an error trap or an error handler. TrueFalse

True

A sentinel is a special value that marks the end of a sequence of items. Question 11 options:TrueFalse

True

A value-returning function is like a simple function except that when it finishes it returns a value back to the part of the program that called it. T/F

True

Functions can be called from statements in the body of a loop and loops can be called from within the body of a function. True/False

True

In a flowchart, both the decision structure and the repetition structure use the diamond symbol to represent the condition that is tested.

True

In a flowchart, both the decision structure and the repetition structure use the triangle symbol to represent the condition that is tested. TrueFalse

True

In a nested loop, the outer loop goes through all of its iterations for each iteration of the inner loop. TrueFalse

True

In order to draw an octagon with turtle graphics, you would need a loop that iterates eight times. Question 9 options:TrueFalse

True

One reason to store graphics functions in a module is so that you can import the module into any program that needs to use those functions. T/F

True

Python allows you to pass multiple arguments to a function. T/F

True

Python function names follow the same rules as those for naming variables.

True

Reducing duplication of code is one of the advantages of using a loop structure. TrueFalse

True

The 'P' in the acronym IPO refers to processing. T/F

True

The append method is commonly used to add items to a list. Question 7 options:TrueFalse

True

The integrity of a program's output is only as good as the integrity of its input. For this reason, the program should discard input that is invalid and prompt the user to enter valid data. Question 10 options:TrueFalse

True

The sort method rearranges the elements of a list so they are in ascending or descending order. Question 9 options:TrueFalse

True

The tuple function can be used to convert a list to a tuple. Question 1 options:TrueFalse

True

The while loop is known as a pre-test loop because it tests the condition before performing an iteration. TrueFalse

True

To assign a value to a global variable in a function, the global variable must be first declared in the function. T/F

True

Tuples are immutable sequences which means that once a tuple is created, it cannot be changed. Question 6 options:TrueFalse

True

A binary file contains data that has not been converted to text. Question 25 options:TrueFalse

True A binary file contains data in a format that has not been converted to text. Binary files store information in a more compact form, using the raw binary representation of data. This is in contrast to text files, where data is typically stored in a human-readable form using characters and encoding schemes. Binary files can store any type of data, including images, audio, video, and executable programs, in their raw binary format. 20/25

A filename extension is a short sequence of characters that appear at the end of a filename, preceded by a period. Question 18 options:TrueFalse

True A filename extension is indeed a short sequence of characters that appears at the end of a filename, usually preceded by a period. The extension often indicates the type or format of the file and is used by the operating system and applications to determine how to handle or open the file. Examples of filename extensions include .txt for text files, .jpg for JPEG image files, and .py for Python script files.

The acronym GIGI refers to the fact that the computer cannot tell the difference between good data and bad data.

True Garbage In, Garbage Out

If the last line in a file is not terminated with \n, the readline method will return the line without \s. Question 16 options:TrueFalse

True If the last line in a file is not terminated with a newline character (\n), the readline method in Python will return the line without the newline character. This behavior means that the newline character is not automatically added to the last line if it's missing. Programmers need to be aware of this when reading lines from a file, especially if they rely on newline characters to distinguish between lines.

A try block includes one or more statements that can potentially raise an exception. Question 17 options:TrueFalse

True In Python, a try block includes one or more statements that may potentially raise an exception. These statements are placed within the try block, and if an exception occurs during their execution, it can be caught and handled by one or more except blocks associated with the specific exception types. The purpose of a try block is to identify and handle exceptions that might occur during the execution of the enclosed statements.

The index -1 identifies the last element in a list. Question 19 options:TrueFalse

True In Python, the index -1 is used to access the last element in a list. Similarly, -2 would represent the second-to-last element, and so on. Here's an example: my_list = [1, 2, 3, 4, 5] last_element = my_list[-1] print(last_element) # Output: 5 second_to_last = my_list[-2] print(second_to_last) # Output: 4 So, the statement "The index -1 identifies the last element in a list" is true.

In order to create graphs using the matplotlib package, you need to import the pyplot module. Question 20 options:TrueFalse

True In order to create graphs using the matplotlib package in Python, you typically need to import the pyplot module. The pyplot module provides a convenient interface for creating a variety of plots, such as line plots, bar plots, scatter plots, and more. Here's a simple example: import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a line plot plt.plot(x, y) # Show the plot plt.show() Make sure to install matplotlib using: pip install matplotlib So, the statement "In order to create graphs using the matplotlib package, you need to import the pyplot module" is true.

It is possible to create a while loop that determines when the end of a file has been reached. Question 11 options:TrueFalse

True It is possible to create a while loop that determines when the end of a file has been reached. In Python, when you read from a file, the read method returns an empty string when the end of the file is reached. You can use this behavior to create a while loop that continues reading from the file until the end is reached. Here's a simple example: with open('example.txt', 'r') as file: line = file.readline() while line: # Process the line print(line.strip()) line = file.readline() In this example, the loop continues as long as line is not an empty string, which happens when the end of the file is reached.

Lists are dynamic data structures such that items may be added to them or removed from them. Question 15 options:TrueFalse

True Lists in Python are dynamic data structures, which means that you can add or remove items from them after they have been created. This dynamic nature makes lists versatile and suitable for various tasks. For example, you can use the append() method to add an item to the end of a list: my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] You can also use the remove() method to remove a specific item: my_list = [1, 2, 3, 4] my_list.remove(2) print(my_list) # Output: [1, 3, 4] So, the statement "Lists are dynamic data structures such that items may be added to them or removed from them" is true.

Programmers usually refer to the process of saving data in a file as writing data to the file. Question 9 options:TrueFalse

True Programmers typically refer to the process of saving data in a file as writing data to the file. Writing data to a file involves storing information in a persistent storage medium, such as a disk, so that it can be retrieved and used later. The term "writing" is commonly used in programming to describe the action of storing or saving data.

Python allows the programmer to work with text and number files. Question 15 options:TrueFalse

True Python provides functionality to work with both text and binary files. You can open, read, and write text files using built-in functions like open, read, write, and more. Additionally, Python supports working with binary files using similar functions, with the option to specify the mode as 'b' (binary). This flexibility allows programmers to handle a variety of file types, including text and binary files.

The ValueError exception is raised when a search item is not in the list being searched. Question 18 options:TrueFalse

True The ValueError exception is not raised when a search item is not found in a list. Instead, if you attempt to find an element using methods like index() or remove() and the item is not present, a ValueError will be raised. For example: my_list = [1, 2, 3] try: index = my_list.index(4) except ValueError as e: print(f"ValueError: {e}") In this case, attempting to find the index of 4 in my_list would raise a ValueError because 4 is not in the list. If you want to check if an item is in a list without raising an error, you can use the in keyword: my_list = [1, 2, 3] search_item = 4 if search_item in my_list: print(f"{search_item} is in the list.") else: print(f"{search_item} is not in the list.") This way, you can handle the case where the item is not found without using exception handling.

The ZeroDivisionError exception is raised when the program attempts to perform the calculation x/y if y = 0. Question 5 options:TrueFalse

True The ZeroDivisionError exception is raised when a program attempts to perform the division operation (x/y) and the divisor (y) is zero. If you attempt to divide any number by zero in Python, it will result in a ZeroDivisionError.

The built-in function len returns the length of a sequence. Question 24 options:TrueFalse

True The built-in function len() in Python is used to return the length of a sequence, such as a string, list, tuple, or any other iterable. For example: my_list = [1, 2, 3, 4, 5] length_of_list = len(my_list) print(length_of_list) # Output: 5 In this case, len(my_list) returns the length of the list my_list, which is 5. So, the statement "The built-in function len returns the length of a sequence" is true.

To calculate the average of the numeric values in a list, the first step is to get the total of values in the list. Question 25 options:TrueFalse

True To calculate the average of numeric values in a list, the first step is indeed to get the total (sum) of the values in the list. The average is then obtained by dividing the total by the number of elements in the list. Here's a simple example in Python: my_list = [1, 2, 3, 4, 5] # Calculate the total total = sum(my_list) # Calculate the average average = total / len(my_list) print(average) In this example, the sum() function is used to get the total of values in the list, and then the average is calculated by dividing the total by the number of elements in the list. So, the statement "To calculate the average of the numeric values in a list, the first step is to get the total of values in the list" is true. 23/25

When a program needs to save data for later use, it writes the data in a file. Question 14 options:TrueFalse

True When a program needs to save data for later use, one common approach is to write the data to a file. Writing data to a file allows the program to store information in a persistent storage medium, such as a disk, so that it can be retrieved and used later, even after the program has terminated. This is a common practice for tasks like data persistence and configuration settings.

When data is written to a file, it is described as an output file. Question 7 options:TrueFalse

True When data is written to a file, it is commonly described as writing to an output file. The term "output" is often used in the context of data leaving the program and being stored in a file, making it an appropriate description for the action of writing data to a file.

Which list will be referenced by the variable number after the following code is executed? number = range(0, 9, 2) Question 4 options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 3, 5, 7, 9] [2, 4, 6, 8] [0, 2, 4, 6, 8]

[0, 2, 4, 6, 8]

What will be the value of the variable list after the following code executes? list = [1, 2] list = list * 3 Question 10 options: [1, 2] * 3 [3, 6] [1, 2, 1, 2, 1, 2] [1, 2], [1, 2], [1, 2]

[1, 2, 1, 2, 1, 2]

What will be the value of the variable list2 after the following code executes? list1 = [1, 2, 3] list2 = [] for element in list1: list2.append(element) list1 = [4, 5, 6] Question 16 options: [1, 2, 3] [4, 5, 6] [1, 2, 3, 4, 5, 6] Nothing; this code is invalid

[1, 2, 3]

A(n) __________ is any piece of data that is passed into a function when the function is called. global variable argument local variable parameter

argument

What type of loop structure repeats the code based on the value of Boolean expression? conditioned-controlled loop number-controlled loop count-controlled loop Boolean-controlled loop

conditioned-controlled loop

What type of loop structure repeats the code a specific number of times? condition-controlled loop number-controlled loop count-controlled loop Boolean-controlled loop

count-controlled loop For Loop

Which of the following would you use if an element is to be removed from a specific index? Question 23 options: del statement remove method index method slice method

del statement Here's an example: my_list = [1, 2, 3, 4, 5] # Remove the element at index 2 del my_list[2] print(my_list) This will output: [1, 2, 4, 5] The del statement is used to delete an element or a slice from a list.

A single piece of data within a record is called a Question 24 options: variable delimiter field data bit

field

In order to create a graph in Python, you need to include

import matplotlib.pyplot

Which of the following is the correct way to open a file named users.txt in 'r' mode? Question 6 options: infile = open('r', users.txt) infile = read('users.txt', 'r') infile = open('users.txt', 'r') infile = readlines('users.txt', r)

infile = open('users.txt', 'r')

In Python, a comma-separated sequence of data items that are enclosed in a set of brackets is called sequence variable value list

list

Which of the following will assign a random integer in the range of 1 through 50 to the variable number? random(1, 50) = number number = random.randint(1, 50) randint(1, 50) = number number = random(range(1, 50))

number = random.randint(1, 50)

Which of the following is the correct way to open a file named users.txt to write to it? Question 12 options: outfile = open('w', users.txt) outfile = write('users.txt', 'w') outfile = open('users.txt', 'w') outfile = open('users.txt')

outfile = open('users.txt', 'w')

The first operation is called the __________ and its purpose is to get the first input value that will be tested by the validation loop. priming read first input loop set read loop validation

priming read

When a file has been opened using the 'r' mode specifier, which method will return the file's contents as a string? Question 22 options: write input get read

read

Which method will return an empty string when it has attempted to read beyond the end of a file? Question 23 options: read getline input readline

readline

A(n) __________ structure is a structure that causes a statement or a set of statements to execute repeatedly. sequence decision module repetition

repetition

Which method could be used to convert a numeric value to a string? Question 21 options: str value num chr

str

In Python, the variable in the for clause is referred to as the __________ because it is the goal of an assignment at the beginning of each loop iteration. target variable loop variable for variable count variable

target variable

Which method can be used to convert a list to a tuple? Question 14 options: append tuple insert list

tuple

When will the following loop terminate? while keep_on_going != 999: when keep_on_going refers to a value less than 999 when keep_on_going refers to a value greater than 999 when keep_on_going refers to a value equal to 999 when keep_on_going refers to a value not equal to 999

when keep_on_going refers to a value equal to 999


Kaugnay na mga set ng pag-aaral

Demographic and Social Structure

View Set

Chapter 9: New Product Development

View Set

Chapter 11 wound healing, sutures, needles and stapling devices

View Set