CSE final chapter 14 and 15

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

Multiple parameters Which correctly passes two integer arguments for the function call calc_val(...)? 1. (99, 44 + 5) 2. (99 + 44) 3. (99 44)

1. (99, 44 + 5)

what is the difference between parameters vs. arguments?

1. A parameter is a function input specified in a function definition. Ex: A pizza area function might have diameter as an input. 2. An argument is a value provided to a function's parameter during a function call. Ex: A pizza area function might be called as print_pizza_area(12.0) or as print_pizza_area(16.0).

Assign x to a bytes object containing three bytes with hexadecimal values 0x05, 0x15, and 0xf2. Use a bytes literal. x = ____________

b'\x05\x15\xf2' The values do not correspond to readable ASCII characters, thus the \x escape must be used to specify the values in the literal.

Assign x to a bytes object with a single byte whose hexadecimal value is 0x1a. Use a bytes literal. x = ___________

b'\x1a' The value 0x1a does not correspond to a readable ASCII character, thus the \x escape must be used to specify the value in the literal.

Some files consist of data stored as a sequence of bytes, known as ________ __________that is not encoded into human-readable text using an encoding like ASCII or UTF-8. Images, videos, and PDF files are examples of the types of files commonly stored as binary data.

binary data

Reasons for defining functions. T/F A benefit of functions is to increase redundant code.

false: A function can decrease redundant code, so that the same group of statements doesn't have to be written in multiple places.

T/F The write() method immediately writes data to a file.

false: Output is buffered, thus there may be a delay between calling the write method and data being written to the disk.

Reasons for defining functions. T/F Avoiding redundancy means to avoid calling a function from multiple places in a program.

false: Redundancy refers to writing the same code in multiple places. A programmer may want to write that code in a function, then call the function from multiple places in a program.

T/F Use of a with statement is not recommended most of the time when opening files.

false: The with statement is recommended, because closure of the file is guaranteed.

The __________ method closes the file, after which no more reads or writes to the file are allowed.

file.close()

Programs often write to a file to store data permanently. The ______ method writes a string argument to a file.

file.write() The write() method accepts a string argument only. Integers and floating-point values must first be converted using str(), as in f.write(str(5.75)).

A _________ is a named series of statements.

function

To assist with the incremental development process, programmers commonly introduce _________ _______, which are function definitions whose statements haven't been written yet. The benefit of a function stub is that the high-level behavior of the program can be captured before diving into details of each function, akin to planning the route of a road trip before starting to drive.

function stubs

Programs are typically written using _______________ ______________, meaning a small amount of code is written and tested, then a small amount more (an incremental amount) is written and tested, and so on.

incremental development

Complete the program by echoing the second line of "readme.txt" my_file = open('readme.txt') lines = my_file.readlines() print(_______) # ...

lines[1] my_file.readlines() reads the contents of readme.txt and stores each line as an element in the "lines" list.

Complete the statement to read up to 500 bytes from "readme.txt" into the contents variable. my_file = open('readme.txt') contents =___________

my_file.read(500) The optional argument to the file.read() method limits the number of bytes read.

Open "myfile.txt" as read-only in binary mode. f =_______________________

open('myfile.txt', 'rb') Reading the contents of a file opened with binary mode will not map "\n" to "\r\n" on Windows. Reading from and writing to binary files requires the use of bytes objects.

Complete the statement to open the file "readme.txt" for reading. my_file =____________

open('readme.txt')

A common programming task is to get input from a file using the built-in ________ function rather than from a user typing on a keyboard.

open()

A programmer writing a function stub should consider whether or not calling the unwritten function is a valid operation. Simply doing nothing and returning nothing may be acceptable early in the development of a larger program. One approach is to use the _________ keyword, which performs no operation except to act as a placeholder for a required statement.

pass

Call a function named print_age, passing the value 21 as an argument.

print_age(21) An argument is an expression like 21, my_age, my_age + 21, etc.

Calls with multiple parameters. Given: def print_sum(num1, num2): print(num1, '+', num2, 'is', (num1 + num2)) Write a function call using print_sum() to print the sum of x and 400 (providing the arguments in that order).

print_sum(x, 400) If x is 99, then print_sum(x, 400) will print: 99 + 400 is 499.

Return basics: Add a return statement to the function that returns the cube of the argument, i.e. (num*num*num). def cubed(num):

return num*num*num The expression num*num*num is evaluated, and then returned as the result of the function call.

A function may return one value using a ________ ________

return statement

The file "myfile.csv" contains the following contents: Airline,Destination,Departure time,Plane Southwest,Phoenix,615,B747 Alitalia,Milan,1545,B757 British Airways,London,1230,A380 Complete the statement such that the program prints the destination of each flight in myfile.csv. import csv with open('myfile.csv', 'r') as myfile: csv_reader = csv.reader(myfile) for row in csv_reader: print(_____________)

row[1] Iterating over the reader object yields each row of the file as a list of the fields. The destination field is in position 1 of the list.

A variable or function object is only visible to part of a program, known as the object's ________. When a variable is created inside a function, the variable's scope is limited to inside that function.

scope

T/F A function definition with no parameters must still have the parentheses, as in: def print_something():. The call to such a function must include parentheses, and they must be empty, as in: print_something()

true

T/F A function may have multiple parameters, which are separated by commas. Argument values are assigned to parameters by position: First argument to the first parameter, second to the second, etc.

true

T/F A return statement may appear at any point in a function, not just as the last statement. A function may also contain multiple return statements in different locations.

true

T/F The function call jumps execution to the function's statements.

true

T/F When writing to a file, the mode of the file must be explicitly set in the open() function call. A _mode_ indicates how a file is opened, e.g., whether or not writing to the file is allowed,

true

Incremental development and function stubs. T/F Incremental development may involve more frequent testing, but ultimately leads to faster development of a program.

true Frequent testing leads to catching errors earlier, before multiple errors begin to interact with one another in strange ways.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 1. y = square_root(49.0)

true/valid

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 6. square_root(9.0)

true/valid The expression evaluates to 3.0. Nothing is done with that value. The statement is legal, but not useful.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 4. y = square_root(square_root(16.0))

true/valid The inner square_root(16.0) evaluates to 4.0. Then, the outer square_root(4.0) evaluates to 2, which is assigned to y.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 9. print_val(9.0)

true/valid This is the normal usage of a function with no return value.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 3. y = 1.0 + square_root(144.0)

true/valid square_root(144.0) evaluates to 12.0. Then 1.0 + 12.0 is 13.0, which is assigned to y.

T/F The statement f.write(10.0) always produces an error.

true: The write() method requires a string argument. The programmer should write f.write(str(10.0))instead.

T/F The flush() method (and perhaps os.fsync() as well) forces the output buffer to write to disk.

true: Data in the output buffer may not be written to disk until a newline character is encountered or if the buffer is filled.

A _______ statement can be used to open a file, execute a block of statements, and automatically close the file when complete.

with

Open "data.txt" as read-only in binary mode. f = open('data.txt', ___________)

'rb' Reading the contents of a file opened with binary mode will not map "\n" to "\r\n" on Windows.

multiple parameters Given a function definition: def calc_val(a, b, c): and given variables i, j, and k, which are valid arguments in the call calc_val(...)? 1. (i, j) 2. (k, i + j, 99) 3. (i + j + k)

(k, i + j, 99) There are three integer arguments, so k's value will be assigned to a, i + j to b, and 99 to c.

A bytes object is used to represent a sequence of single byte values, such as binary data read from a file. Bytes objects are immutable, just like strings, meaning the value of a bytes object cannot change once created. A byte object can be created using the bytes() built-in function:

-bytes('A text string', 'ascii') - creates a sequence of --bytes by encoding the string using ASCII. -bytes(100) - creates a sequence of 100 bytes whose values are all 0. -bytes([12, 15, 20]) - creates a sequence of 3 bytes with values from the list.

Calls with multiple parameters. Given: def print_sum(num1, num2): print(num1, '+', num2, 'is', (num1 + num2)) What will be printed for the following function call? print_sum(1, 2)

1 + 2 is 3 When print_sum(1, 2) is called, 1 is assigned to the function's first parameter num1, and 2 to num2.

Python comes with a number of built-in functions, such as input(), int(), len(), etc. what keyword is used to create new functions?

The def function

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 7. y = print_val(9.0)

The expression always evaluates to None, which is legal to assign to y but not very useful.

Return basics: Add a return statement to the function that returns the result of adding num1 and num2. def sum(num1, num2): return num1 + num2

The expression num1 + num2 is evaluated, and then returned as the result of the function call.

T/F A function can only return one item, not two or more (though a list with multiple elements could be returned). A function with no return statement, or a return statement with no following expression, returns the value None. None is a special keyword that indicates no value.

True

T/F A function evaluates to its returned value. Thus, a function call often appears within an expression. Ex: 5 + compute_square(4) would become 5 + 16, or 21. A function that returns None cannot be used as such within an expression.

True

T/F When using a with statement to open a file, the file is automatically closed when the statements in the block finish executing.

True: The context manager for files performs a teardown operation when the statements complete, closing the file automatically.

Incremental development and function stubs. T/F The main advantage of function stubs is that they ultimately lead to faster-running programs.

false Function stubs mainly help a programmer capture correct high-level behavior before getting distracted by low-level details. Function stubs may lead to better organized programs, and may shorten development time too.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 8. y = 1 + print_val(9.0)

false/invalid print_val() returns None, which cannot be added to 1.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 5. y = square_root()

false/invalid square_root requires one argument.

Given the following function, determine which statements are valid. def square_root(x): return math.sqrt(x) def print_val(x): print(x) 2. square_root(49.0) = z

false/invalid: The left side of an assignment statement must be a variable, not an expression.

Reasons for defining functions. T/F A key reason for creating functions is to help the program run faster.

false: Actually, functions may cause slightly slower execution. But functions have other, far more important advantages, like improved readability.

Reasons for defining functions. T/F If a function's internal statements are revised, all function calls will have to be modified too.

false: Usually not. One of the advantages of a function is that the detailed implementation of the function is not relevant to the caller.

Incremental development and function stubs. T/F A pass statement should be used in a function stub when the programmer wants the stub to stop program execution when called.

false: pass or print statements allow a program to continue. The statement raise NotImplementedError causes the program to halt.

________ is the area of code where a name is visible.

Scope

The most common methods to read text from a file are ____1____and _______2________. The file.read() method returns the file contents as a string. The file.readlines() method returns a list of strings, where the first element is the contents of the first line, the second element is the contents of the second line, and so on

1. file.read() 2. file.readlines()

1-A _________ _________consists of the new function's name and a block of statements. Ex: def print_pizza_area():. An indented block of statements follows the definition. 2-A _________ _____ is an invocation of the function's name, causing the function's statements to execute.

1.function definition 2.function call

Multiple parameters: Which correctly defines two parameters x and y for a function definition: def calc_val(...):? 1. (x; y) 2. (x y) 3. (x, y)

3. (x, y)

Assume a function def print_num(user_num): simply prints the value of user_num without any space or newline. What will the following code output? print_num(43) print_num(21)

4321 The first call prints 43. The second call prints 21 immediately after, so the entire output is 4321.

multiple parameters Given a function definition: def calc_val(a, b, c):, what value is assigned to b during this function call: calc_val(42, 55, 77)?

55: Given a function definition: def calc_val(a, b, c):, what value is assigned to b during this function call: calc_val(42, 55, 77)?

Is the following a valid function definition beginning? Type yes or no. def my_fct(userNum + 5):

No. A parameter is like a variable definition. It cannot be an expression.

a programmer may want a program to stop executing if an unfinished function is called: for example, A program that requires user input should not execute if the user-defined function that gets input is not completed. In such cases, a _________________Error can be generated with the statement 'raise NotImplementedError.'

NotImplementedError

Text data is commonly organized in a spreadsheet format using columns and rows. A ___________________________ file is a simple text-based file format that uses commas to separate data items, called fields. Below is an example of a typical csv file that contains information about student scores:

comma separated values (csv)

The Python standard library __________ ____________ can be used to help read and write files in the csv format. To read a file using the csv module, a program must first create a reader object, passing a file object created via open. The reader object is an iterable - iterating over the reader using a for loop returns each row of the csv file as a list of strings, where each item in the list is a field from the row.

csv module

The file "myfile.csv" contains the following contents: Airline,Destination,Departure time,Plane Southwest,Phoenix,615,B747 Alitalia,Milan,1545,B757 British Airways,London,1230,A380 Complete the statement to create a csv module reader object to read myfile.csv. import csv with open('myfile.csv', 'r') as myfile: csv_reader = _______________

csv.reader(myfile) The reader object can be used to iterate over rows of the csv file.

Complete the function definition to have a parameter named user_age.

def print_age(user_age) A parameter is specified by just giving the name.


Kaugnay na mga set ng pag-aaral

Programming Fundamentals I Chapter 1

View Set

Pre-Calculus Linear and Quadratic Functions and Modeling

View Set

Child Growth and Development Chapter 9 Study Guide

View Set

Business Management Final Exam Study Guide

View Set

MIS Chapter 2, MIS Chapter 4, MIS Chapter 6, MIS Chapter 8

View Set

ESL Supplemental Practice Test 2

View Set

Chapter 12 and 13 - Benefit Process and Options

View Set

Professional Responsibility-SULC- Exam 4

View Set

Microbiology Chapter 5, Microbiology Chapter 6/7

View Set