Python Final Exam

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

object

A "thing" to which a variable can refer. This could be a screen window, or one of the turtles you have created.

str

A Python data type that holds a string of characters

int

A Python data type that holds positive and negative whole numbers.

side effect

A change in the state of a program made by calling a function that is not a result of reading the return value from the function. Side effects can only be produced by modifiers.

Q-1: What is the value of the following expression: 16 - 4 * 7 // 3 + 1 A. 29 B. 8 C. 29.0 D. 9

B. 8

dict-3-10: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print(23 in mydict) A. True B. False

B. False

list-5-3: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(57 in alist) A. True B. False

B. False

strings-8-7: Evaluate the following comparison: "dog" < "Dog" A. True B. False C. They are the same word

B. False

strings-8-8: Evaluate the following comparison: "dog" < "Doghouse" A. True B. False

B. False

class

see data type below

iteration

A basic building block for algorithms (programs). It allows steps to be repeated. Sometimes called looping.

dictionary

A collection of key-value pairs that maps from keys to values. The keys can be any immutable type, and the values can be any type.

standard library

A collection of modules that are part of the normal installation of Python.

recursive definition

A definition which defines something in terms of itself. To be useful it must include base cases which are not recursive. In this way it differs from a circular definition. Recursive definitions often provide an elegant way to express complex data structures.

module

A file containing Python definitions and statements intended for use in other Python programs. The contents of a module are made available to the other program by using the import statement.

programming language

A formal notation for representing solutions.

object-oriented language

A language that provides features, such as user-defined classes and inheritance, that facilitate object-oriented programming.

nested list

A list that is an element of another list.

definite iteration

A loop where we have an upper bound on the number of times the body will be executed. Definite iteration is usually best coded as a for loop.

variable

A name that refers to a value.

value

A number or string (or other things to be named later) that can be stored in a variable or computed in an expression.

random number

A number that is generated in such a way as to exhibit statistical randomness.

reference diagram

A picture showing a variable with an arrow pointing to the value (object) that the variable refers to. See also state snapshot.

documentation

A place where you can go to get detailed information about aspects of your programming language

object-oriented programming

A powerful style of programming in which data and the operations that manipulate it are organized into classes and methods.

deterministic

A process that is repeatable and predictable.

keyword

A reserved word that is used by the compiler to parse program; you cannot use keywords like if, def, and while as variable names.

program

A sequence of instructions that specifies to a computer actions and computations to be performed.

pattern

A sequence of statements, or a style of coding something that has general applicability in a number of different situations. Part of becoming a mature Computer Scientist is to learn and establish the patterns and algorithms that form your toolkit. Patterns often correspond to your "mental chunking".

tuple

A sequential collection of items, similar to a list. Any python object can be an element of a tuple. However, unlike a list, tuples are immutable.

data type

A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are integers (int), floating-point numbers (float), and strings (str).

icon

A small picture that represents some functionality in a computer program. A user clicks on an icon to cause an action to be performed by a program.

None

A special Python value. One use in Python is that it is returned by functions that do not execute a return statement with a return argument.

for loop

A statement in Python for convenient repetition of statements in the body of the loop.

loop

A statement or group of statements that execute repeatedly until a terminating condition is satisfied.

conditional statement

A statement that controls the flow of execution depending on some condition. In Python the keywords if, elif, and else are used for conditional statements.

assert statement

A statement that verifies that a boolean condition is true.

canvas

A surface within a window where drawing takes place.

activecode

A unique interpreter environment that allows Python to be executed from within a web browser.

graphical user interface

A user interacts with a computer program by pointing, clicking, and dragging icons and widgets in a window on a computer screen.

index

A variable or value used to select a member of an ordered collection, such as a character from a string, or an element from a list.

Q-1: What value is printed when the following statement executes? print(18 % 3) A. 0 B. 6 C. 6.0

A. 0

intro-8-1: Which of the following is a run-time error? A. Attempting to divide by 0. B. Forgetting a colon at the end of a statement where one is required. C. Forgetting to divide by 100 when printing a percentage amount.

A. Attempting to divide by 0.

list-2-2: A list can contain only integer items. A. False B. True

A. False

intro-9-2: Who or what typically finds semantic errors? A. The programmer. B. The compiler / interpreter. C. The computer. D. The teacher / instructor.

A. The programmer.

dict-3-9: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print("dog" in mydict) A. True B. False

A. True

func-1-12: True or false: A function can be called several times by placing a function call in the body of a loop. A. True B. False

A. True

list-5-2: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(3.14 in alist) A. True B. False

A. True

designtest-1-1: Is this a testable function? sum = 0 def add(x, y): global sum sum = x + y A. Yes. B. No.

A. Yes.

strings-6-6: What is printed by the following statements? s = "python rocks" print(s[-3]) A. c B. k C. s D. Error, negative indices are illegal.

A. c

modulus operator

Also called remainder operator or integer remainder operator. Gives the remainder after performing integer division.

GUI

An abbreviation for a "graphical user interface."

design by contract

An approach to designing functions that specifies function behavior using preconditions and postconditions.

tuple assignment

An assignment to all of the elements in a tuple using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.

Python shell

An interactive user interface to the Python interpreter. The user of a Python shell types commands at the prompt (>>>), and presses the return key to send these commands immediately to the interpreter for processing.

semantic error

An error in a program that makes it do something other than what the programmer intended.

syntax error

An error in a program that makes it impossible to parse — and therefore impossible to interpret.

bug

An error in a program.

Q-1: What will be the contents of "myfile.txt" after executing the following code?: f = open("myfile.txt", "w") for i in range(3): f.write("agoodstring") f.close() A. "agoodstring\nagoodstring\nagoodstring" B. "agoodstringagoodstringagoodstring" C. Nothing, as the call to open() is incorrect. D. "agoodstring"

B. "agoodstringagoodstringagoodstring"

Q-1: 10. What does the following code print?: for i in range(3): print(i, end = ' ') for character in ['a', 'b', 'c']: print(character, end = ' ') A. a 1 b 2 c 3 B. 0 'a' 'b' 'c' 1 'a' 'b' 'c' 2 'a' 'b' 'c' C. 1 a 2 b 3 c D. 1 2 3 a b c

B. 0 'a' 'b' 'c' 1 'a' 'b' 'c' 2 'a' 'b' 'c'

Q-1: 1. What does the following code print?: for num in [1, 2, 3, 4, 5]: print(num, end = ' ') A.5 spaces B. 1 2 3 4 5 C. num num num num num D. end end end end end

B. 1 2 3 4 5

select-2-4: Say you are registering for next semester's classes. You have choice A, which is your art class, and choice B, which is your math class. You need both of them, but it's a race between time and luck. If you end up registering on time for choice A, but you don't get your choice B, which logical operators would be true? A. A and B B. A or B C. not A D. not B

B. A or B D. not B

Q-1: Assume that "pease.txt" is the name of a text file holding the text to the poem "Pease Porridge Hot." What is the content of the variable t after executing the following code segment?: f = open("pease.txt", "r") t = f.read() A. None B. All the text of the file in one string C. All characters from the file except the 'r' characters D. Only the 'r' characters from the file

B. All the text of the file in one string

list-16-4: What is printed by the following statements? alist = [4, 2, 8, 6, 5] alist = alist + 999 print(alist) A. [4, 2, 8, 6, 5, 999] B. Error, you cannot concatenate a list with an integer.

B. Error, you cannot concatenate a list with an integer.

intro-13-2: What are comments for? A. To tell the computer what you mean in your program. B. For the people who are reading your code to know, in natural language, what the program is doing. C. Nothing, they are extraneous information that is not needed. D. Nothing in a short program. They are only needed for really large programs.

B. For the people who are reading your code to know, in natural language, what the program is doing.

intro-7-2: Who or what typically finds syntax errors? A. The programmer. B. The compiler / interpreter. C. The computer. D. The teacher / instructor.

B. The compiler / interpreter.

intro-8-2: Who or what typically finds runtime errors? A. The programmer. B. The interpreter. C. The computer. D. The teacher / instructor.

B. The interpreter.

Q-1: Which of the following is TRUE about Button widgets? A. They come in standard types, each of which has a dedicated callback function that cannot be overridden. B. They can be attached to a programmer-defined callback function. C. They must be activated with the `isactive` parameter before they can be used, even if they have already been created and placed on the screen. D. They must have a callback function defined for them at the time the button is created. Callback functions cannot be added to Buttons later.

B. They can be attached to a programmer-defined callback function.

dict-1-5: A dictionary is an unordered collection of key-value pairs. A. False B. True

B. True

list-11-3: What is printed by the following statements? alist = [4, 2, 8, 6, 5] blist = alist blist[3] = 999 print(alist) A. [4, 2, 8, 6, 5] B. [4, 2, 8, 999, 5]

B. [4, 2, 8, 999, 5]

list-8-6: What is printed by the following statements? alist = [4, 2, 8, 6, 5] alist[2] = True print(alist) A. [4, 2, True, 8, 6, 5] B. [4, 2, True, 6, 5] C. Error, it is illegal to assign

B. [4, 2, True, 6, 5]

Q-1: What will the following code print? class MyClass: """Make an object of type 'MyClass'.""" def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "({0}, {1})".format(self.x, self.y) myInstance = MyClass(x=1, y=2) print(myInstance) A. (0, 0) B. Make an object of type 'MyClass'. C. (1, 2) D. <__main__.MyClass object at 0x000001EF0016CDC8>

C. (1, 2)

list-4-3: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[2].upper()) A. Error, you cannot use the upper method on a list. B. 2 C. CAT

C. CAT

list-24-4: What is printed by the following statements? myname = "Edgar Allan Poe" namelist = myname.split() init = "" for aname in namelist: init = init + aname[0] print(init) A. Poe B. EdgarAllanPoe C. EAP D. William Shakespeare

C. EAP

strings-9-3: What is printed by the following statements: s = "Ball" s[0] = "C" print(s) A. Ball B. Call C. Error

C. Error

strings-14-3: What is printed by the following statements: s = "ball" r = "" for item in s: r = item.upper() + r print(r) A. Ball B. BALL C. LLAB

C. LLAB

list-6-4: What is printed by the following statements? alist = [1, 3, 5] print(alist * 3) A. 9 B. [1, 1, 1, 3, 3, 3, 5, 5, 5] C. [1, 3, 5, 1, 3, 5, 1, 3, 5] D. [3, 9, 15]

C. [1, 3, 5, 1, 3, 5, 1, 3, 5]

list-14-5: What is printed by the following statements? alist = [4, 2, 8, 6, 5] temp = alist.pop(2) temp = alist.pop() print(alist) A. [4, 8, 6] B. [2, 6, 5] C. [4, 2, 6]

C. [4, 2, 6]

composition (of functions)

Calling one function from within the body of another, or using the return value of one function as an argument to the call of another.

scaffolding

Code that is used during program development to assist with development and debugging. The unit test code that we added in this chapter are examples of scaffolding.

unit test

Code that tests a function to determine if it works properly

Q-1: 13. What are the values that the variable x receives during execution of the following Python code?: for i in range(0, 20, 3) : x = i % 5 A. The value of x can't be predicted by looking at the code B. 0 3 6 9 12 15 18 C. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 D. 0 3 1 4 2 0 3

D. 0 3 1 4 2 0 3

Q-1: What value is printed when the following statement executes? print(21 % 4) A. 4.25 B. 2 C. 4 D. 1

D. 1

Q-1: 22. What should the value of n be in the following block of code? (The third line should be "merrily merrily merrily merrily"): print("row row row your boat" print("gently down the stream" for i in range(n): print("merrily") print("life is but a dream.") A. 3 B. 5 C. len("merrily") D. 4

D. 4

testfunc-1-4: Rewrite the following 3 lines of code with a single assert: result = engage_thruster(22) if result != 'OK': print("Test 2: FAIL") A. assert result != 'OK' B. assert engage_thruster(22) == result C. assert engage_thruster(22) != 'OK' D. assert engage_thruster(22) == 'OK'

D. assert engage_thruster(22) == 'OK'

func-4-2: When assert x==y is executed and x and y have the same values, what will happen? A. A runtime error will occur B. A message is printed out saying that the test failed. C. x will get the value that y currently has D. Nothing will happen E. A message is printed out saying that the test passed.

D. Nothing will happen

list-22-3: What is printed by the following statements? alist = [4,2,8,6,5] blist = [num*2 for num in alist if num%2==1] print(blist) A. [4,2,8,6,5] B. [8,4,16,12,10] C. 10 D. [10].

D. [10].

decrement

Decrease by 1.

shallow equality

Equality of references, or two references that point to the same object.

deep equality

Equality of values, or two references that point to objects that have the same value.

constructor

Every class has a "factory", called by the same name as the class, for making new instances. If the class has an initializer method, this method is used to get the attributes (i.e. the state) of the new object properly set up.

reassignment

Making more than one assignment to the same variable during the execution of a program.

aliases

Multiple variables that contain references to the same object.

token

One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.

logical operator

One of the operators that combines boolean expressions: and, or, and not.

comparison operator

One of the operators that compares two values: ==, !=, >, <, >=, and <=.

key-value pair

One of the pairs of items in a dictionary. Values are looked up in a dictionary by key.

branch

One of the possible paths of the flow of execution determined by conditional execution.

postcondition

Part of a function specification that states the work the function completed by the function if the precondition is satisfied.

dead code

Part of a program that can never be executed, often because it appears after a return statement.

control flow

See flow of execution in the next chapter.

attribute

Some state or value that belongs to a particular object. For example, tess has a color.

sequential

The default behavior of a program. Step by step processing of algorithm.

semantics

The meaning of a program.

relative file path

The name of a file that includes a path to the file from the current working directory of a program. An relative file path never starts with a /.

recursion

The process of calling the function that is already executing.

debugging

The process of finding and removing any of the three kinds of programming errors.

problem solving

The process of formulating a problem, finding a solution, and expressing the solution.

rules of precedence

The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.

raise

To cause an exception by using the raise statement.

deep copy

To copy the contents of an object as well as any embedded objects, and any objects embedded in them, and so on; implemented by the deepcopy function in the copy module.

instantiate

To create an instance of a class, and to run its initializer.

dot notation

Use of the dot operator, ., to access functions inside a module, or to access methods and attributes of an object.

close

When you are done with a file, you should close it.

write

Will add characters to the end of a file that has been opened for writing.

readline

Will read a single line from the file, up to and including the first instance of the newline character.

open

You must open a file before you can read its contents.

server

a computer or computer program which manages access to a centralized resource or service in a network.

Server-side web applications

programs that run on web server computers, rather than on the user's local machine. Typically, a server-side web application displays a form with text boxes and other data collection mechanisms. The user fills out the form, clicks a submit button, and the browser sends the form to the web application on the server, which processes the request, and responds with another web page.

specification-based tests

tests that are designed based only on the information in the function specification, without considering any of the details in the function implementation.

URL (Uniform Resource Locator)

the address of a web page.

query string

the part of a URL that assigns values to specified parameters, such as a search query in Google

HTML(Hypertext Markup Language) pages:

the standard markup language for documents designed to be displayed in a web browser. It tells the web browser that the user sees how it should look and what information should be on the page.

float

A Python data type which stores floating-point numbers. Floating-point numbers are stored internally in two parts: a base and an exponent. When printed in the standard format, they look like decimal numbers. Beware of rounding errors when you use floats, and remember that they are only approximate values.

precondition

A boolean condition that the caller of a function must ensure is true in order for the function to produce correct results

base case

A branch of the conditional statement in a recursive function that does not give rise to further recursive calls.

range

A built-in function in Python for generating sequences of integers. It is especially useful when we need to write a for loop that executes a fixed number of times.

event loop

A built-in function of a GUI toolkit that "listens" for operating system events and then calls an appropriate event-handler for each event.

delimiter

A character or string used to indicate where a string should be split.

list

A collection of objects, where each object is identified by an index. Like other types str, int, float, etc. there is also a list type-converter function that tries to turn its argument into a list.

expression

A combination of operators and operands (variables and values) that represents a single result value. Expressions are evaluated to give that result.

terminating condition

A condition that occurs which causes a loop to stop repeating its body. In the for loops we saw in this chapter, the terminating condition has been when there are no more elements to assign to the loop variable.

chained conditional

A conditional branch with more than two possible flows of execution. In Python chained conditionals are written with if ... elif ... else statements.

key

A data item that is mapped to a value in a dictionary. Keys are used to look up values in a dictionary.

turtle

A data object used to create pictures (known as turtle graphics).

mutable data type

A data type in which the elements can be modified. All mutable types are compound types. Lists are mutable data types; strings are not.

collection data type

A data type in which the values are made up of components, or elements, that are themselves values.

immutable data type

A data type whose values cannot be changed. Modifying functions create a totally new object that does not change the original one.

infinite recursion

A function that calls itself recursively without ever reaching the base case. Eventually, an infinite recursion causes a runtime error.

type conversion function

A function that can convert a data value from one type to another.

method

A function that is attached to an object. Invoking or activating the method causes the object to respond in some way, e.g. forward is the method when we say tess.forward(100).

event-handler

A function that processes an event. These functions are also called callback functions.

boolean function

A function that returns a boolean value. The only possible values of the bool type are False and True.

random number generator

A function that will provide you with random numbers, usually between 0 and 1.

fruitful function

A function that yields a return value instead of None.

print function

A function used in a program or script that causes the Python interpreter to display a value on its output device.

modifier

A function which changes its arguments inside the function body. Only mutable types can be changed by modifiers.

pure function

A function which has no side effects. Pure functions only make changes to the calling program through their return values.

chatterbox function

A function which interacts with the user (using input or print) when it should not. Silent functions that just convert their input arguments into their output results are usually the most useful ones.

algorithm

A general step by step process for solving a problem.

state snapshot

A graphical representation of a set of variables and the values to which they refer, taken at a particular instant during the program's execution.

block

A group of consecutive statements with the same indentation.

infinite loop

A loop in which the terminating condition is never satisfied.

nested loop

A loop inside the body of another loop.

indefinite iteration

A loop where we just need to keep going until some condition is met. A while statement is used for this case.

mapping type

A mapping type is a data type comprised of a collection of keys and associated values. Python's only built-in mapping type is the dictionary. Dictionaries implement the associative array abstract data type.

variable name

A name given to a variable. Variable names in Python consist of a sequence of letters (a..z, A..Z, and _) and digits (0..9) that begins with a letter. In best programming practice, variable names should be chosen so that they describe their use in the program, making the program self documenting.

pseudo-random number

A number that is not genuinely random but is instead created algorithmically.

optional parameter

A parameter written in a function header with an assignment to a default value which it will receive if no corresponding argument is given for it in the function call.

slice

A part of a string (substring) specified by a range of indices. More generally, a subsequence of any sequence type in Python can be created using the slice operator (sequence[start:stop]).

incremental development

A program development plan intended to simplify debugging by adding and testing only a small amount of code at a time.

event-driven programming

A program that only executes tasks when a user specially requests a task.

source code

A program, stored in a file, in a high-level language before being compiled or interpreted.

high-level language

A programming language like Python that is designed to be easy for humans to read and write.

portability

A property of a program that can run on more than one kind of computer.

newline

A special character that causes the cursor to move to the beginning of the next line.

tab

A special character that causes the cursor to move to the next tab stop on the current line.

initializer method

A special method in Python (called __init__) that is invoked automatically to set a newly-created object's attributes to their initial (factory-default) state.

operator

A special symbol that represents a simple computation like addition, multiplication, or string concatenation.

shell mode

A style of using Python where we type expressions at the command prompt, and the results are shown immediately. Contrast with source code, and see the entry under Python shell.

loop variable

A variable used as part of a for loop. It is assigned a different value on each iteration of the loop, and is used as part of the terminating condition of the loop, when it can no longer get a further value.

counter

A variable used to count something, usually initialized to zero and incremented in the body of a loop.

temporary variable

A variable used to store an intermediate value in a complex calculation.

widget

A visual element of a graphical user interface that allows a user to give commands to an executing program. Example widgets include a command button, a slider bar, or a list box.

Q-1: In a Python Class definition, what is the purpose of 'self' in attribute assignment (for instance, 'self.x = x'), and in method definitions (for instance, 'def myFunc(self):')? A. 'self' is used to tell one instance of a class apart from another instance (like being able to tell apart `alex` and `tess` in our work with turtles). B. 'self' refers to the module in which the class is defined, giving it access to any functions or constants also defined in that module. C. 'self' refers to the class definition itself, or the template used to make instances of the class.

A. 'self' is used to tell one instance of a class apart from another instance (like being able to tell apart `alex` and `tess` in our work with turtles).

strings-12-3: How many times is the letter o printed by the following statements? s = "python rocks" idx = 1 while idx < len(s): print(s[idx]) idx = idx + 2 A. 0 B. 1 C. 2

A. 0

dict-3-8: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} answer = mydict.get("cat") // mydict.get("dog") print(answer) A. 2 B. 0.5 C. bear D. Error, divide is not a valid operation on dictionaries.

A. 2

data-7-6: What value is printed when the following statement executes? print(18 / 4) A. 4.5 B. 5 C. 4 D. 2

A. 4.5

list-3-3: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(len(alist)) A. 7 B. 8

A. 7

data-9-4: What is the value of the following expression: 2 ** 2 ** 3 * 3 A. 768 B. 128 C. 12 D. 256

A. 768

modules-1-4: To find out information on the standard modules available with Python you should: A. Go to the Python Documentation site. B. Look at the import statements of the program you are working with or writing. C. Ask the professor D. Look in this textbook.

A. Go to the Python Documentation site.

func-4-5: Consider the following code: def square(x): for counter in range(x): runningtotal = 0 runningtotal = runningtotal + x return runningtotal What happens if you put the initialization of runningtotal (the line runningtotal = 0) inside the for loop as the first instruction in the loop? A. The square function will return x instead of x * x B. The square function will cause an error C. The square function will work as expected and return x * x D. The square function will return 0 instead of x * x

A. The square function will return x instead of x * x

strings-8-6: Evaluate the following comparison: "Dog" < "Doghouse" A. True B. False

A. True

tdd-1-3: Test-First Development often involves writing more code than traditional development. A. True B. False

A. True

select-1-5: Which of the following is a Boolean expression? Select all that apply. A. True B. 3 == 4 C. 3 + 4 D. 3 + 4 == 7E. "False"

A. True B. 3 == 4 D. 3 + 4 == 7E. "False"

Q-1: The textbook describes a few different categories of widgets - i.e., sets of widgets that have similar functionality. Which of the following descriptions does NOT match any of these categories? A. Widgets that allow the user to arbitrarily add functionality to them through the GUI window itself. B. Widgets that execute a command when clicked. C. Widgets that do not execute commands, but accept input from a user (e.g. selecting from several options, inputting a number, etc.). D. Widgets that do not execute commands, but provide the user special tools to input specific types of data (e.g. choosing a file from the file system, choosing a color, etc.)

A. Widgets that allow the user to arbitrarily add functionality to them through the GUI window itself.

list-7-2: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[4:]) A. [ [ ], 3.14, False] B. [ [ ], 3.14] C. [ [56, 57, "dog"], [ ], 3.14, False]

A. [ [ ], 3.14, False]

list-14-4: What is printed by the following statements? alist = [4, 2, 8, 6, 5] alist.insert(2, True) alist.insert(0, False) print(alist) A. [False, 4, 2, True, 8, 6, 5] B. [4, False, True, 2, 8, 6, 5] C. [False, 2, True, 6, 5]

A. [False, 4, 2, True, 8, 6, 5]

intro-5-1: A program is: A. a sequence of instructions that specifies how to perform a computation. B. something you follow along at a play or concert. C. a computation, even a symbolic computation. D. the same thing as an algorithm.

A. a sequence of instructions that specifies how to perform a computation.

func-1-8: Which of the following is a valid function header (first line of a function definition)? A. def drawCircle(t): B. def drawCircle: C. drawCircle(t, sz): D. def drawCircle(t, sz)

A. def drawCircle(t):

modules-3-2: Which statement allows you to use the math module in your program? A. import math B. include math C. use math D. You don't need a statement. You can always use the math module

A. import math

modules-4-3: Which of the following is the correct way to reference the value pi within the math module. Assume you have already imported the math module. A. math.pi B. math(pi) C. pi.math D. math->pi

A. math.pi

Q-1: What is the correct way to invoke the add method on the object myInstance, and store the result in a new variable? class MyClass: """Make an object of type 'MyClass'.""" def __init__(self, x=0, y=0): self.x = x self.y = y def add(self): return self.x + self.y myInstance = MyClass(x=5, y=4) A. myVar = myInstance.add() B. myVar = add(myInstance.x, myInstance.y) C. myVar = myInstance.add D. myVar = add(myInstance)

A. myVar = myInstance.add()

list-11-4: Consider the following lists: list1=[1,100,1000] list2=[1,100,1000] list3=list1 Which statements will output True? (Select all that apply). A. print(list1 == list2) B. print(list1 is list2) C. print(list1 is list3) D. print(list2 is not list3)E. print(list2 != list3)

A. print(list1 == list2) C. print(list1 is list3) D. print(list2 is not list3)E. print(list2 != list3)

s = "python rocks" print(s[7:11] * 3) A. rockrockrock B. rock rock rock C. rocksrocksrocks D. Error, you cannot use repetition with slicing.

A. rockrockrock

intro-4-4: The activecode interpreter allows you to (select all that apply): A. save programs and reload saved programs. B. type in Python source code. C. execute Python code right in the text itself within the web browser. D. receive a yes/no answer about whether your code is correct or not.

A. save programs and reload saved programs. B. type in Python source code. C. execute Python code right in the text itself within the web

intro-3-1: Source code is another name for: A. the instructions in a program, stored in a file. B. the language that you are programming in (e.g., Python). C. the environment/tool in which you are programming. D. the number (or "code") that you must input at the top of each program to tell the computer how to execute your program.

A. the instructions in a program, stored in a file.

object

Also known as a data object (or data value). The fundamental things that programs are designed to manipulate (or that programmers ask to do things for them).

runtime error

An error that does not occur until the program has started to execute but that prevents the program from continuing.

escape sequence

An escape character, \, followed by one or more printable characters used to designate a nonprintable character.

boolean expression

An expression that is either true or false.

statement

An instruction that the Python interpreter can execute. So far we have only seen the assignment statement, but we will soon meet the import statement and the for statement.

codelens

An interactive environment that allows the user to control the step by step execution of a Python program

byte code

An intermediate language between source code and object code. Many modern languages first compile source code into byte code and then interpret the byte code with a program called a virtual machine.

cursor

An invisible marker that keeps track of where the next character will be printed.

invoke

An object has methods. We use the verb invoke to mean activate the method. Invoking a method is done by putting parentheses after the method name, with some possible arguments. So wn.exitonclick() is an invocation of the exitonclick method.

instance

An object that belongs to a class. tess and alex are different instances of the class Turtle

integer division

An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.

data structure

An organization of data for the purpose of making it easier to use.

exception

Another name for a runtime error.

executable¶

Another name for object code that is ready to be executed.

loop body

Any number of statements nested inside a loop. The nesting is indicated by the fact that the statements are indented under the for loop statement.

whitespace

Any of the characters that move the cursor without printing visible characters. The constant string.whitespace contains all the white-space characters.

sequence

Any of the data types that consist of an ordered collection of elements, with each element identified by an index.

formal language

Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.

natural language

Any one of the languages that people speak that evolved naturally.

strings-6-4: What is printed by the following statements? s = "python rocks" print(len(s)) A. 11 B. 12

B. 12

Q-1: What is the value of the following expression: 2 + 3**2*2 A. 22 B. 20 C. 83 D. 27

B. 20

list-4-2: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[5]) A. [ ] B. 3.14 C. False

B. 3.14

dict-3-11: What is printed by the following statements? total = 0 mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} for akey in mydict: if len(akey) > 3: total = total + mydict[akey] print(total) A. 18 B. 43 C. 0 D. 61

B. 43

Q-1: What value is printed when the following statement executes? print(22 // 4) A. 4.5 B. 5 C. 4 D. 2

B. 5

list-3-2: What is printed by the following statements? alist = [3, 67, "cat", 3.14, False] print(len(alist)) A. 4 B. 5

B. 5

strings-10-5: How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s[3:8]: print("HELLO") A. 4 B. 5 C. 6 D. Error, the for statement cannot use slice.

B. 5

data-3-4: What value is printed when the following statement executes? print( int(53.785) ) A. Nothing is printed. It generates a runtime error. B. 53 C. 54 D. 53.785

B. 53

dict-1-6: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23} print(mydict["dog"]) A. 12 B. 6 C. 23 D. Error, you cannot use the index operator with a dictionary.

B. 6

Q-1: J. [6 pts]. What is printed when the following statements execute? a = 7 b = 50 c = 20 // 7 d = "4" b = b % a - 1 print(2*str(a)+str(c)+str(b)+d) A. 0 B. 77204 C. 20 D. An error occursE. 77024

B. 77204

modules-4-6: One reason that lotteries don't use computers to generate random numbers is: A. There is no computer on the stage for the drawing. B. Because computers don't really generate random numbers, they generate pseudo-random numbers. C. They would just generate the same numbers over and over again. D. The computer can't tell what values were already selected, so it might generate all 5's instead of 5 unique numbers.

B. Because computers don't really generate random numbers, they generate pseudo-random numbers.

Q-1: It is possible to write your own methods for performing arithmetic on instances of your own class (for instance methods like add(), subtract(), etc.), but it is NOT possible to cause built-in operators like + and - to do anything besides their default functionality. A. True B. False

B. False

Q-1: Multiple different layout managers should be used in the same parent widget to provide the programmer more control over the overall layout of a GUI window. A. True B. False

B. False

Q-1: Using a File Chooser like filedialog.askopenfilename() opens a File Chooser window for the user, opens the file they select in 'read' mode, and then returns the opened file object into a variable that can have methods such as readlines() called on it. A. True B. False

B. False

checkassump-1-5: An assert statement displays output if the condition is True. A. True B. False

B. False

data-5-1: True or False: the following is a legal variable name in Python: A_good_grade_is_A+ A. True B. False

B. False

testfunc-1-5: Consider the following function which is supposed to return the first character of its argument: def get_first(msg): return msg[1] Now, consider this unit test: assert get_first('Bells') == 'B' This assertion fails. Is the unit test in error, or the function it is testing? A. Unit test B. Tested function C. Both are in error D. Both are correct

B. Tested function

func-1-7: What is one main purpose of a function? A. To improve the speed of execution B. To help the programmer organize programs into chunks that match how they think about the solution to the problem. C. All Python programs must be written using functions D. To calculate values.

B. To help the programmer organize programs into chunks that match how they think about the solution to the problem.

func-3-7: Can you use the same name for a local variable as a global variable? A. Yes, and there is no reason not to. B. Yes, but it is considered bad form. C. No, it will cause an error.

B. Yes, but it is considered bad form

Q-1: When implementing an interactive widget that you need to fetch values from such as an Entry: A. You must associate a typical Python variable like an int, string, or list with the widget to store its current value. B. You must associate a special "variable object" like tk.StringVar or tk.BooleanVar with the widget to store its current value. C. You can access the current values of all widgets through the "widgetvals" property of the main window (the Tk() object running the event loop.) D. You may call the 'get()' method directly on the widget to store its current value into a local variable.

B. You must associate a special "variable object" like tk.StringVar or tk.BooleanVar with the widget to store its current value.

func-2-7: What is wrong with the following function definition: def addEm(x, y, z): return x + y + z print('the answer is', x + y + z) A. You should never use a print statement in a function definition. B. You should not have any statements in a function after the return statement. Once the function gets to the return statement it will immediately stop executing the function. C. You must calculate the value of x+y+z before you return it. D. A function cannot return a number.

B. You should not have any statements in a function after the return statement. Once the function gets to the return statement it will immediately stop executing the function.

list-13-6: What is printed by the following statements? alist = [4, 2, 8, 6, 5] blist = [alist] * 2 alist[3] = 999 print(blist) A. [4, 2, 8, 999, 5, 4, 2, 8, 999, 5] B. [[4, 2, 8, 999, 5], [4, 2, 8, 999, 5]] C. [4, 2, 8, 6, 5] D. [[4, 2, 8, 999, 5], [4, 2, 8, 6, 5]]

B. [[4, 2, 8, 999, 5], [4, 2, 8, 999, 5]]

modules-5-1: A module is another name for: A. the code inside a function B. a file containing Python code C. the comments before a function D. a small block of Python code

B. a file containing Python code

intro-11-1: The differences between natural and formal languages include: A. natural languages can be parsed while formal languages cannot. B. ambiguity, redundancy, and literalness. C. there are no differences between natural and formal languages. D. tokens, structure, syntax, and semantics.

B. ambiguity, redundancy, and literalness.

checkassump-1-6: Consider the following function. Which assert should be added to check its precondition? def getfirst(msg): """returns first character of msg Precondition: len(msg) > 0 """ return msg[0] A. assert len(msg) <= 0 B. assert len(msg) > 0 C. assert msg[0] D. none of these

B. assert len(msg) > 0

list-4-4: What is printed by the following statements? alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False] print(alist[2][0]) A. 56 B. c C. cat D. Error, you cannot have two index values unless you are using slicing.

B. c

intro-4-5: Codelens allows you to (select all that apply): A. measure the speed of a program's execution. B. control the step by step execution of a program. C. write and execute your own Python code. D. execute the Python code that is in codelens.

B. control the step by step execution of a program. D. execute the Python code that is in codelens.

intro-12-2: The print function: A. sends information to the printer to be printed on paper. B. displays a value on the screen. C. tells the computer to put the information in print, rather than cursive, format. D. tells the computer to speak the information.

B. displays a value on the screen.

func-1-9: What is the name of the following function? def drawSquare(t, sz): """Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) A. def drawSquare(t, sz) B. drawSquare C. drawSquare(t, sz) D. Make turtle t draw a square with side sz.

B. drawSquare

designtest-1-2: Consider the following function. What would an appropriate precondition be? def getfirst(msg): """returns first character of msg""" return msg[0] A. len(msg) <= 0 B. len(msg) > 0 C. msg == "" D. none of these

B. len(msg) > 0

Q-1: 32. What does the following function print? (You should run it to see.): import os def check(): something = os.listdir(".") for x in something: print(x) A. prints all the words in the original (1900) edition of The Wizard of Oz B. prints all the files in the program's folder C. prints a list of all the states in alphabetical order D. prints nothing

B. prints all the files in the program's folder

strings-6-5: What is printed by the following statements? s = "python rocks" print(s[len(s)-5]) A. o B. r C. s D. Error, len(s) is 12 and there is no index 12.

B. r

modules-4-4: Which module would you most likely use if you were writing a function to simulate rolling dice? A. the math module B. the random module C. the turtle module D. the game module

B. the random module

debug-4-2: Which of the following explains why wait_time_int = int(wait_time_int) is an error? A. You cannot use a variable on both the left and right hand sides of an assignment statement. B. wait_time_int does not have a value so it cannot be used on the right hand side. C. This is not really an error, Python is broken.

B. wait_time_int does not have a value so it cannot be used on the right hand side.

increment

Both as a noun and as a verb, increment means to increase by 1.

list-29-10: What is printed by the following statements? list= [5, 2, 1, 4, 9, 10] min_value = 0 for item in list: if item < min_value: min_value = item print(min_value) A. 10 B. 1 C. 0 D. There is an error in the code so it cannot run.

C. 0

Q-1: 2. What does the following code print?: for i in range(7): print(i, end = ' ') A. 0 1 2 3 4 5 6 7 B. 1 2 3 4 5 6 7 C. 0 1 2 3 4 5 6 D. 7

C. 0 1 2 3 4 5 6

data-11-4: What is printed when the following statements execute? x = 12 x = x - 1 print(x) A. 12 B. -1 C. 11 D. Nothing. An error occurs because x can never be equal to x

C. 11

strings-10-4: How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s: print("HELLO") A. 10 B. 11 C. 12 D. Error, the for statement needs to use the range function.

C. 12

data-11-5: What is printed when the following statements execute? x = 12 x = x - 3 x = x + 5 x = x + 1 print(x) A. 12 B. 9 C. 15 D. Nothing. An error occurs because x cannot be used that many times in assignment statements.

C. 15

dict-2-4: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23} mydict["mouse"] = mydict["cat"] + mydict["dog"] print(mydict["mouse"]) A. 12 B. 0 C. 18 D. Error, there is no entry with mouse as the key.

C. 18

strings-11-4: How many times is the letter o printed by the following statements? s = "python rocks" for idx in range(len(s)): if idx % 2 == 0: print(s[idx]) A. 0 B. 1 C. 2 D. Error, the for statement cannot have an if inside.

C. 2

strings-5-12: What is printed by the following statements? v = 2.34567 print('{:.1f} {:.2f} {:.7f}'.format(v, v, v)) A. 2.34567 2.34567 2.34567 B. 2.3 2.34 2.34567 C. 2.3 2.35 2.3456700

C. 2.3 2.35 2.3456700

list-14-6: What is printed by the following statements? alist = [4, 2, 8, 6, 5] alist = alist.pop(0) print(alist) A. [2, 8, 6, 5] B. [4, 2, 8, 6, 5] C. 4 D. None

C. 4

rec-3-1: How many recursive calls are made when computing the sum of the list [2,4,6,8,10]? A. 6 B. 5 C. 4 D. 3

C. 4

list-23-2: What is printed by the following statements? alist = [ [4, [True, False], 6, 8], [888, 999] ] if alist[0][1][0]: print(alist[1][0]) else: print(alist[1][1]) A. 6 B. 8 C. 888 D. 999

C. 888

dict-4-2: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} yourdict = mydict yourdict["elephant"] = 999 print(mydict["elephant"]) A. 23 B. None C. 999 D. Error, there are two different keys named elephant.

C. 999

Q-1: 18. What shape does the following code draw?: import turtle wn = turtle.Screen() janet = turtle.Turtle() janet.back(75) for i in range(3) : janet.forward(150) janet.left(120) A. a parallelagram B. a star with three points C. An equilateral triangle D. a right triangle

C. An equilateral triangle

Q-4: What is the the output of the following print code? class Car: def __init__(self): self.color = "Red" self.size = "Big" BMW = Car() Tesla = Car() x = BMW is Tesla y = type(BMW)==type(Tesla) print(x, y) A. True True B. True False C. False True D. False False

C. False True

intro-9-1: Which of the following is a semantic error? A. Attempting to divide by 0. B. Forgetting a colon at the end of a statement where one is required. C. Forgetting to divide by 100 when printing a percentage amount.

C. Forgetting to divide by 100 when printing a percentage amount.

intro-3-2: What is the difference between a high-level programming language and a low-level programming language? A. It is high-level if you are standing and low-level if you are sitting. B. It is high-level if you are programming for a computer and low-level if you are programming for a phone or mobile device. C. It is high-level if the program must be processed before it can run, and low-level if the computer can execute it without additional processing. D. It is high-level if it easy to program in and is very short; it is low-level if it is really hard to program in and the programs are really long.

C. It is high-level if the program must be processed before it can run, and low-level if the computer can execute it without additional processing.

func-3-5: What is a variable's scope? A. Its value B. The range of statements in the code where a variable can be accessed. C. Its name

C. Its name

select-4-3: How many statements can appear in each block (the if and the else) in a conditional statement? A. Just one. B. Zero or more. C. One or more. D. One or more, and each must contain the same number.

C. One or more.

intro-2-1: What is the most important skill for a computer scientist? A. To think like a computer. B. To be able to write code really well. C. To be able to solve problems. D. To be really good at math.

C. To be able to solve problems.

list-6-3: What is printed by the following statements? alist = [1, 3, 5] blist = [2, 4, 6] print(alist + blist) A. 6 B. [1, 2, 3, 4, 5, 6] C. [1, 3, 5, 2, 4, 6] D. [3, 7, 11]

C. [1, 3, 5, 2, 4, 6]

list-13-5: What is printed by the following statements? alist = [4, 2, 8, 6, 5] blist = alist * 2 blist[3] = 999 print(alist) A. [4, 2, 8, 999, 5, 4, 2, 8, 6, 5] B. [4, 2, 8, 999, 5] C. [4, 2, 8, 6, 5]

C. [4, 2, 8, 6, 5]

list-17-5: What is printed by the following statements? alist = [4, 2, 8, 6, 5] blist = [ ] for item in alist: blist.append(item+5) print(blist) A. [4, 2, 8, 6, 5] B. [4, 2, 8, 6, 5, 5] C. [9, 7, 13, 11, 10] D. Error, you cannot concatenate inside an append.

C. [9, 7, 13, 11, 10]

func-4-5: For the hangman game, this 'blanked' function takes a word and some letters that have been guessed, and returns a version of the word with _ for all the letters that haven't been guessed. Which of the following is the correct way to write a test to check that 'under' will be blanked as 'u_d__' when the user has guessed letters d and u so far? A. assert blanked('under', 'du', 'u_d__') == True B. assert blanked('under', 'u_d__') == 'du' C. assert blanked('under', 'du') == 'u_d__'

C. assert blanked('under', 'du') == 'u_d__'

dict-3-7: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} keylist = list(mydict.keys()) keylist.sort() print(keylist[3]) A. cat B. dog C. elephant D. bear

C. elephant

strings-7-3: What is printed by the following statements? s = "python rocks" print(s[3:8]) A. python B. rocks C. hon r D. Error, you cannot have two numbers inside the [ ].

C. hon r

Q-1: Say that we create a new GUI window with the line mywin = tk.Tk(). Which of the following is the correct way to create a new label to place on the window with the text "Here is my label!"? A. label = Tk(Label("Here is my label!")) B. label = tk.Label().set_text("Here is my label!") C. label = tk.Label(mywin, text="Here is my label!") D. label = tk.Label("Here is my label!", window=mywin)

C. label = tk.Label(mywin, text="Here is my label!")

Q-1: Given a Button widget called myButton, what is the correct way to use the grid layout manager to ensure that the button is aligned to the left side of its parent widget? A. myButton.grid(expand="west") B. myButton.grid(column=0) C. myButton.grid(sticky=tk.W) D. myButton.grid(side=tk.LEFT)

C. myButton.grid(sticky=tk.W)

modules-5-2: Create a module by: A. writing a new function or class B. placing an import statement at the top of a file C. placing code in a Python file in the same directory as your other source code D. creating a comment block at the beginning of a file

C. placing code in a Python file in the same directory as your other source code

Q-1: 9. What does the following code do?: total = 0 for num in [27, 12, 45, 100, 12]: total = total + num print(total / 5) A. prints the first and last number in the list B. it's impossible to tell what this code does without running it C. prints the average of the numbers in the list D. prints the numbers in the list

C. prints the average of the numbers in the list

strings-5-11: What is printed by the following statements? x = 2 y = 6 print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y)) A. Nothing - it causes an error B. sum of {} and {} is {}; product: {}. 2 6 8 12 C. sum of 2 and 6 is 8; product: 12. D. sum of {2} and {6} is {8}; product: {12}.

C. sum of 2 and 6 is 8; product: 12.

Q-1: 5. What does the following code print?: for i in range(1, 10, 2): print(i, end = ' ') A. 1 3 5 7 9 2 B. 2 4 5 8 C. 2 2 2 2 2 D. 1 3 5 7 9

D. 1 3 5 7 9

data-4-6: What is printed when the following statements execute? day = "Thursday" day = 32.5 day = 19 print(day) A. Nothing is printed. A runtime error occurs. B. Thursday C. 32.5 D. 19

D. 19

Q-1: What value is printed when the following statement executes? print(18 // 8) A. 4.25 B. 5 C. 4 D. 2

D. 2

data-7-8: What value is printed when the following statement executes? print(18 % 4) A. 4.25 B. 5 C. 4 D. 2

D. 2

Q-1: 8. What does the following code print?: for i in range(5, -1, -1): print(i, end = ' ') A. 5 -1 -1 B. 5 4 3 2 1 C. 4 3 2 1 0 D. 5 4 3 2 1 0

D. 5 4 3 2 1 0

Q-1: [2 pts]. What does the following code print? Please note that end = ' ' in the print statement adds a space at the end of what gets printed: for i in range(5, -1, -1): print(i, end = ' ') A. 5 4 3 2 1 B. 5 -1 -1 C. 4 3 2 1 0 D. 5 4 3 2 1 0

D. 5 4 3 2 1 0

Q-1: 19. What shape does the following function draw? Assume t is a turtle; n and length are integers.: def mystery(t, n, length) : angle = 360/n for i in range(n) : t.forward(length) t.left(angle) A. A circle B. The letter H C. A right triangle D. A polygon with n sides

D. A polygon with n sides

Q-1: Which of the following is TRUE about events in Python GUI programming? A. Events can only be bound to interactive widgets like Buttons and Checkbuttons. B. When an event is generated, any other event currently being handled is paused until the new one is processed. C. When an event is generated, it is automatically associated with whatever widget had the program's focus at the time the event was created. D. Events can only be generated by user interaction, e.g. mouse clicks and key presses.

D. Events can only be generated by user interaction, e.g. mouse clicks and key presses.

rec-3-2: Suppose you are going to write a recusive function to calculate the factorial of a number. fact(n) returns n * n-1 * n-2 * ... * 1, and the factorial of zero is definded to be 1. What would be the most appropriate base case? A. n == 0 B. n == 1 C. n >= 0 D. n <= 1

D. n <= 1

modules-5-3: What determines the name of our import? A. the first variable name in the module B. a comment early in the module C. it's called whatever we name it in the "import" statement D. the filename of the module

D. the filename of the module

data-10-5: After the following statements, what are the values of x and y? x = 15 y = x x = 22 A. x is 15 and y is 15 B. x is 22 and y is 22 C. x is 15 and y is 22 D. x is 22 and y is 15Check MeCompare me

D. x is 22 and y is 15Check MeCompare me

comment

Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.

element

One of the values in a list (or other sequence). The bracket operator selects elements of a list.

operand

One of the values on which an operator operates.

nesting

One program structure within another, such as a conditional statement inside a branch of another conditional statement.

body

The block of statements in a compound statement that follows the header.

condition

The boolean expression in a conditional statement that determines which branch is executed.

state

The collection of attribute values that a specific data object maintains.

absolute file path

The name of a file that includes a path to the file from the root directory of a file system. An absolute file path always starts with a /.

object code

The output of the compiler after it translates the program.

list traversal

The sequential accessing of each element in a list

recursive call

The statement that calls an already executing function. Recursion can even be indirect — function f can call g which calls h, and h could make a call back to f.

syntax

The structure of a program.

default value

The value given to an optional parameter if no argument for it is provided in the function call.

return value

The value provided as the result of a function call.

boolean value

There are exactly two boolean values: True and False. Boolean values result when a boolean expression is evaluated by the Python interepreter. They have type bool.

shallow copy

To copy the contents of an object, including any references to embedded objects; implemented by the copy function in the copy module.

clone

To create a new object that has the same value as an existing object. Copying a reference to an object creates an alias but doesn't clone the object.

parse

To examine a program and analyze the syntactic structure.

interpret

To execute a program in a high-level language by translating it one line at a time.

initialization (of a variable)

To initialize a variable is to give it an initial value. Since in Python variables don't exist until they are assigned values, they are initialized when they are created. In other programming languages this is not the case, and variables can be created without being initialized, in which case they have either default or garbage values.

traverse

To iterate through the elements of a collection, performing a similar operation on each.

handle an exception

To prevent an exception from terminating a program by wrapping the block of code in a try / except construct.

generalize

To replace something unnecessarily specific (like a constant value) with something appropriately general (like a variable or parameter). Generalization makes code more versatile, more likely to be reused, and sometimes even easier to write.

evaluate

To simplify an expression by performing the operations in order to yield a single value.

compile

To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.

prompt string

Used during interactive input to provide the user with hints as to what type of value to enter.

read

Will read the entire contents of a file as a string. This is often used in an assignment statement so that a variable can reference the contents of the file.

readlines

Will read the entire contents of a file into a list where each line of the file is a string and is an element in the list.

IP address

a special address indicating the request came from the browser on the same computer that the Flask server is running on.

protocol

a system of rules that allows two or more entities of a communications system to transmit information. The protocol defines the rules, syntax, semantics and synchronization of communication and possible error recovery methods.

web browser

an application software for accessing the World Wide Web. When a user requests a web page from a particular website, the web browser retrieves the necessary content from a web server and then displays the page on the user's device.

Client-side web applications

programs that are downloaded to a web browser and executed on the user's local machine. Client-side applications are typically written in JavaScript and embedded in web pages.

Q-22: What is the value of the following expression: 2 + 3**2*2 A. 22 B. 20 C. 83 D. 27

A. 22

select-3-2: Which of the following properly expresses the precedence of operators (using parentheses) in the following expression: 5*3 > 10 and 4+6==11 A. ((5*3) > 10) and ((4+6) == 11) B. (5*(3 > 10)) and (4 + (6 == 11)) C. ((((5*3) > 10) and 4)+6) == 11 D. ((5*3) > (10 and (4+6))) == 11

A. ((5*3) > 10) and ((4+6) == 11)

data-9-3: What is the value of the following expression: 16 - 2 * 5 // 3 + 1 A. 14 B. 24 C. 3 D. 13.667

A. 14

Q-1: 12. How many times will the following loop execute? (Choose the most accurate statement.): for i in range(10, 25): print(i) A. 15 times B. 25 times C. zero or more times D. at least one timeE. at least 10 times but no more than 25 times

A. 15 times

Q-1: What is printed when the following statements execute? x = 12 x = x - 3 x = x + x x = x * 1 print(x) A. 18 B. 9 C. 12 D. Nothing. An error occurs because x cannot be used that many times in assignment statements.

A. 18

data-8-4: What is printed when the following statements execute? n = input("Please enter your age: ") # user types in 18 print ( type(n) ) A. <class 'str'> B. <class 'int'> C. <class 18> D. 18

A. <class 'str'>

modules-1-3: In Python a module is: A. A file containing Python definitions and statements intended for use in other Python programs. B. A separate block of code within a program. C. One line of code in a program. D. A file that contains documentation about functions in Python.

A. A file containing Python definitions and statements intended for use in other Python programs.

func-1-6: What is a function in Python? A. A named sequence of statements. B. Any sequence of statements. C. A mathematical expression that calculates a value. D. A statement of the form x = 5 + 4.

A. A named sequence of statements.

func-3-6: What is a local variable? A. A temporary variable that is only used inside a function B. The same as a parameter C. Another name for any variable

A. A temporary variable that is only used inside a function

func-2-8: What will the following function return? def addEm(x, y, z): print(x + y + z) A. None B. The value of x + y + z C. The string 'x + y + z'

A. None

intro-2-2: An algorithm is: A. A solution to a problem that can be solved by a computer. B. A step by step list of instructions that if followed exactly will solve the problem under consideration. C. A series of instructions implemented in a programming language. D. A special kind of notation used by computer scientists

B. A step by step list of instructions that if followed exactly will solve the problem under consideration.

select-4-4: What does the following code print (choose from output a, b, c or nothing)? if 4 + 5 == 10: print("TRUE") else: print("FALSE") A. TRUE B. FALSE C. TRUE on one line and FALSE on the next D. Nothing will be printed

B. FALSE

intro-11-2: True or False: Reading a program is like reading other kinds of text. A. True B. False

B. False

strings-3-3: What is printed by the following statements? s = "python" t = "rocks" print(s + t) A. python rocks B. python C. pythonrocks D. Error, you cannot add two strings together.

C. pythonrocks

select-2-3: What is a correct Python expression for checking to see if a number stored in a variable x is between 0 and 5? A. x > 0 and < 5 B. x > 0 or x < 5 C. x > 0 and x < 5

C. x > 0 and x < 5

Q-1: After the following statements, what are the values of x and y? x = 15 y = x x = y y = x + 7 A. x is 15 and y is 15 B. x is 22 and y is 22 C. x is 15 and y is 22 D. x is 22 and y is 15

C. x is 15 and y is 22

data-2-11: What is the data type of 'this is what kind of data'? A. Character B. Integer C. Float D. String

D. String

Q-1: 6. What does the following code print?: for i in range(24, 30, 3): print(i, end = ' ') A. 24 27 B. 27 30 C. 24 27 30 D. 24 30 3

A. 24 27

Q-1: What value is printed when the following statement executes? print(18 / 4) A. 4.5 B. 5 C. 4 D. 2

A. 4.5

modules-4-5: The correct code to generate a random number between 1 and 100 (inclusive) is: A. prob = random.randrange(1, 101) B. prob = random.randrange(1, 100) C. prob = random.randrange(0, 101) D. prob = random.randrange(0, 100)

A. prob = random.randrange(1, 101)

intro-10-1: The difference between programming and debugging is: A. programming is the process of writing and gradually debugging a program until it does what you want. B. programming is creative and debugging is routine. C. programming is fun and debugging is work. D. there is no difference between them.

A. programming is the process of writing and gradually debugging a program until it does what you want.

strings-3-4: What is printed by the following statements? s = "python" excl = "!" print(s+excl*3) A. python!!! B. python!python!python! C. pythonpythonpython! D. Error, you cannot perform concatenation and repetition at the same time.

A. python!!!

strings-4-3: What is printed by the following statements? s = "python rocks" print(s[2] + s[-5]) A. tr B. ps C. nn D. Error, you cannot use the [ ] operator with the + operator.

A. tr

intro-6-1: Debugging is: A. tracking down programming errors and correcting them. B. removing all the bugs from your house. C. finding all the bugs in the program. D. fixing the bugs in the program.

A. tracking down programming errors and correcting them.

strings-5-5: What is printed by the following statements? s = "python rocks" print(s[1] * s.index("n")) A. yyyyy B. 55555 C. n D. Error, you cannot combine all those things together.

A. yyyyy

Q-1: 3. What does the following code print?: for i in range(1, 7): print(i, end = ' ') A. 1 2 3 4 5 6 7 B. 1 2 3 4 5 6 C. 1 7 D. 0 1 2 3 4 5 6

B. 1 2 3 4 5 6

intro-3-3: Pick the best replacements for 1 and 2 in the following sentence: When comparing compilers and interpreters, a compiler is like 1 while an interpreter is like 2. A. 1 = a process, 2 = a function B. 1 = translating an entire book, 2 = translating a line at a time C. 1 = software, 2 = hardware D. 1 = object code, 2 = byte code

B. 1 = translating an entire book, 2 = translating a line at a time

Q-1: [2 pts]. What will the following print? def sumsquare(alpha, beta): a = alpha**2 + beta**2 return a a = 3 b = 4 c = sumsquare(a,b) print(a, b, c) A. 3 4 25.0 B. 3 4 25 C. 3.0 4.0 25.0 D. 25 4 25

B. 3 4 25

Q-1: 4. What does the following code print?: for i in range(90, 100): print(i, end = ' ') A. 91 92 93 94 95 96 97 98 99 100 B. 90 91 92 93 94 95 96 97 98 99 C. 90 91 92 93 94 95 96 97 98 99 100 D. 91 100

B. 90 91 92 93 94 95 96 97 98 99

modules-1-5: True / False: All standard Python modules will work in activecode. A. True B. False

B. False

intro-7-1: Which of the following is a syntax error? A. Attempting to divide by 0. B. Forgetting a colon at the end of a statement where one is required. C. Forgetting to divide by 100 when printing a percentage amount.

B. Forgetting a colon at the end of a statement where one is required.

data-2-10: How can you determine the type of a variable? A. Print out the value and determine the data type based on the value printed. B. Use the type function. C. Use it in a known equation and print the result. D. Look at the declaration of the variable.

B. Use the type function.

strings-4-2: What is printed by the following statements? s = "python rocks" print(s[3]) A. t B. h C. c D. Error, you cannot use the [ ] operator with a string.

B. h

strings-5-4: What is printed by the following statements? s = "python rocks" print(s.count("o") + s.count("p")) A. 0 B. 2 C. 3

C. 3

data-7-7: What value is printed when the following statement executes? print(18 // 4) A. 4.25 B. 5 C. 4 D. 2

C. 4


Set pelajaran terkait

Financial Management Chapters 3 & 4

View Set

Series 79: CH 9-- Syndication of Securities Offerings

View Set

Exam 1- Chapter 5- IS5610 Cybersecurity

View Set

Chapter 25 Normal Newborn: Needs, Care, and Feeding

View Set

Social Advertising Fundamentals, Facebook Ad Structure and Campaign Options/Targeting, Advanced Audience Research and Targeting

View Set

Kuby Immunology Exam 5 Ch's 15-20

View Set

Financial Accounting- Chapter #6

View Set