CMPSC 132 midterm

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23} mydict["mouse"] = mydict["cat"] + mydict["dog"] print(mydict["mouse"])

18

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.

Defensive programming

An approach to programming that attempts to identify possible threats and proactively create code to avoid them; also called secure programming.

object-oriented programming

Combines data and functionality and wraps it inside an object • Objects are the center of the process • Python is primarily designed as an object-oriented programming language Each object has its own local state • Each object also knows how to manage its own local state, based on method calls • Method calls are messages passed between objects • Several objects may all be instances of a common types -Different types may relate to each other

A programmer created this code for a client: def divide(numerator, denominator): quotient = numerator / denominator return quotient The programmer tested this code with the following three sets of data and the results were: >>> divide(9, 3)3.0 >>> divide(-50, 5)-10.0 >>> divide(389, -26)-14.961538461538462 However, once the program was in use, the client reported that sometimes the program crashed. Could you explain why?

Didn't test for a 0 value in demoniatror

Property Method

Easier way to combine getters and setters

update() method

Extend a dictionary

We can implement a pure OOP program without using classes in our code

False

Debugging

Finding and fixing problems in your algorithm or program, most efficient way to test

keys() or values() method

Get keys or values as a list

Aliases

Multiple variables that contain references to the same object.

Syntax errors

Occur when the programmer does not follow the rules of the programming language.

Type error 3

Passing an incorrect number of arguments to a function

Software Development Life Cycle

Requirements, Design, coding, debugging test, deployment

sorted()

Return a new sorted list.

Slicing

Selecting a portion of a collection

Which type of error prevents a program from compiling and running?

Syntax error

procedure-oriented programming is characterized by

The breaking down of a main problem into sub-problems • The use of functions or procedures to solve these subproblems • The use of both global and local variables to store data • The use of parameters to pass data to the functions or procedure

Indentation error

The lines of the program are not properly indented.

Type error 2

Using non-function objects in function calls

unit testing advantages

We can write down several test cases and let them be checked every time we make changes to our code-without the tedious work of typing every thing all over again, and without the risk of forgetting anything or by omitting crucial tests simply due to laziness

When comparing compilers and interpreters, a compiler is like X while an interpreter is like Y

X = translating an entire book, Y = translating a line at a time

What is printed by the following statements? aList = [46, 2, 8, 6, 5, 10] aList[2] = True print(aList)

[46, 2, True, 6, 5, 10]

What will the following function return? def adding(x, y, z): print(x + y + z) a) none b) the value of x+y+z c) the str of 'x+y+z' d) the number 0

a

What is the value of a and b at the end the following statements? a=95 b=a a=a+1 a="Text" b=a*3

a = 'Text', b= 'TextTextText'

The get() method

access the value associated with a key, similar to the [ ] operator

s.extend(t)

adds the elements of t to the end of s

s.append(x)

adds the single element x to the end of s

invoking a method

allowing the method to execute; also known as called into action, harry.changeName('Lupin')

Name error

an exception that occurs when Python is asked to produce a value for a variable that has not been assigned a value

By default split() uses white space to delimit elements. To use a different separator,pass a _____ split():

argument

Variables in python are called

attributes

Which of the following best defines a class? a) scope of an object b) blueprint of an object c) instance of an object d) parent of an object

b

which of the following is FALSE? a) everything in python is an object b) just as houses are built from blueprints, classes are built from objects c)building a new object from even a large class is simple, one statement d) all of the above are true

b

What is the term used to indicate the variables and constants of a class? a) data characters b) constants c) attributes d) identifiers

c

Which of the following is not a common type of syntax error? a) forgetting a colon b) forgetting a parenthesis c) using 'True" as a boolean value d) indentation incorrect

c

immuttable objects

cannot be changed in place i.e(list, dict)

continue

causes to immediately skip the processing of the rest of the body of a loop for the current iteration.

A ___creates a new type where objects are instances of the class:

class

Basic OOP principles

classes, data abstraction, polymorphism, inheritance, encapsulation

Argument error

code syntax mistake

Key error

code syntax mistake

s.join()

combines the elements of a list to form a string

plus operator

concatenate two lists

What is the final value of s after this code is executed: s= "Penn State"s[1]="E" a) "Penn State E" b) "PEnn State" c) "PennE State" d) there's a runtime error

d

Which definition best describes an object? a) overview of a class b) instance of itself c) a data type d) instance of a class

d

if a local class is defined in a function, which of the following is TRUE of an object of that class? a) object is accessible outside the function b) object can be declared inside any other function c) object can be used outside the function d) object can be used/accessed/declared locally in that function

d

special methods

double underscores at beginning and end, don't have to invoke them directly

To add key-value pairs with assignment operator

eng2spa['one'] = 'uno'

__init__()

evaluates when the object is created, to handle this type of object initialization, assign initial values to all attributes

Methods

functions contained within a class

[begin:end]

gets the characters from begin up to but not including end

[begin:]

gets the characters from beginning to the end of the string

[:end]

gets the first characters up to but not including end

What does binding an object to a new identifier using the assignment operator do?

gives another name to the same object, doesn't create a new object

During the class instantiation operation (creating an empty object) the __init__() method is automatically _____ for the newly-created class instance

invoked

dictionary

is a map from keys to values

@property

it will be called whenever it is looked up on an instance

What line number of the following code contains an error and what type of error is it? 1. def sales_tax(amt): 2. print("Welcome to the 6% tax calculator!\n") 3. sale = amt + (sale * .06) 4. return amt 5. 6. print("The total amount after tax is: ", sales_tax(95))

line 3, runtime error

s.sort()

modifies the list it is invoked on

A Python identifier

name used to identify a variable, function, class, module or other object.

s.count(x):

number of occurences of x in the sequence s

self

particular variable refers to the object itself

Runtime errors

produced by the runtime system if something goes wrong while the program is running

Semantic errors

program runs but wrong output

How to call a method?

reference an object of the class that owns it first

s.pop()

removes and returns the last element of the list

s.remove(x)

removes the first occurrence of x in s, or raises a ValueError if x is not in s

while loop statement

repeatedly executes a target statement as long as a given condition is true.

* operator

repeats the list and then makes a new list

str.endswith(substr)

returns True if str ends with substr

str.isdigit()

returns True if str is all digits

str.startswith(substr)

returns True if str starts with substr

str.isupper()

returns True if string all upper case

str.replace(old, new)

returns a copy of str with all occurrences of old replaced with new

str.upper()

returns a copy of str with each character converted to upper case

str.strip()

returns a copy of str with leading and trailing whitespace removed

str.split(delimiter)

returns a list of substrings from str delimited by delimiter

str.join(iterable)

returns a string that is the concatenation of all the elements of iterable with string between each element

len(s)

returns the amount of elements in list

max(s)

returns the greatest element

str.find(substr)

returns the index of the first occurence of substring str

min(s)

returns the least element of s

Blocks of code are denoted by line indentation, which is ______enforced.

rigidly

interpreters

source code---interpreter---output

compilers

source code--compilers--object code--executor--output

How to avoid debugging

start small, keep it working

Attributes

store the data associated with each class instance

Create a list from a string using the string method split():

string_value.split(separator, max_split)

break

terminates execution of a loop

in operator

test for list membership

Unit Testing

test individual units or pieces of code for a system

x 'is' y

tests if two expressions evaluate to the same object

Type error

the application of an operator to an operand of an inappropriate type

mutable objects

they can be altered in place i.e(int, float)

Index error

trying to index a sequence with a number that exceeds the size of the sequence

How are attributes of an object accessed in python?

using the dot operator(.)

iteration

visiting the elements of an iterable data structure

Program mode

write an entire program by placing lines of Python instructions in a file and then use the interpreter to execute the contents of the file as a whole

debugging principles

•Make it fail every time •Change one thing at a time, for a reason •Keep track of what you have done •Do not panic if you generate a ton of errors •Version control revisited •Ask for help


Conjuntos de estudio relacionados

Reading 25: Understanding Cash Flow Statements

View Set

MIDI II Module 2 Exam--Neuroimaging & ACLS

View Set

practice question 141 exam 3 (2/2) chapters 26, 27, 28, 29, 30

View Set

Genetics Extensions of Mendelian Inheritance

View Set

CIC Surveillance & Epi Investigation Practice Questions

View Set

Chapter 7: The Outer Planets & Their Moons (Textbook Notes)

View Set