CSC401 - Introduction to Programming, Ch2 - CSC401, CSC 401 Test 2, python, Python Programming Review, Introduction to Computer Programming: Python, Python Programming Test, Introduction to Python 3 Programming, Introduction to Programming in Python...

Ace your homework & exams now with Quizwiz!

Which mathematical operator is used to raise five to the second power in Python?

**

Algebraic Operators

+, -, *, /, //, %, **

Algebraic Expression

- 3 + 7 - 2 * 3 + 1 - 14//3 - 2**4

Python Data Types

- Integer - Floating point - Boolean - String - List

Algebraic Funtions

- abs() - min() - max()

Boolean Operators

- and - or - not

String Operators

- in - not in - s * n, n * s - s + t - s[i]

Constructors

- int() - float() - str() - list()

List Functions

- len(lst) - min(lst) - max(lst) - sum(lst)

List Methods

- lst.append(item) - lst.count(item) - lst.index(item) - lst.insert(index, item) - lst.pop() - lst.remove(item) - lst.reverse() - lst.sort()

List Operators

- x in lst - x not in lst - lstA + lstB - lst * n, n * lst - lst[i]

for num in range(4):

0, 1, 2, 3

After the execution of the following statement, the variable price will reference the value _____. price = int(68.549)

68

When applying the .3f formatting specifier to the following number, 76.15854, the result is _______________.

76.159

Comparison Operators

>, <, ==, >=, <=, !=

Implicit Type Conversion

>>> 3 + 0.35 3.35

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

true

A Python int can represent indefinitely large numbers

quotation marks or apostrophes (single quotes)

A Python string literal is always enclosed in

boolean

A Python variable which can only have two values, True or False. These True of False values reduce down to a 1 or 0, on or off.

While Loops

A While loop permits code to execute repeatedly until a certain condition is met. This is useful if the number of iterations required to complete a task is unknown prior to flow entering the loop.

Function

A ________ definition is a sequence of statements that defines a new command

dictionary

A collection of key/value pairs that maps from keys to values.

Compiler

A complex computer program that takes another program written in a high-level language and translates it into an equivalent program in the machine language of some computer

loops

A control structure for controlling the path through the code called ______. There are often times in our programs when we want to do something over and over and over until some condition is met.

True

A counted loop is designed to iterate a specific number of times

sequence

A data type that is made up of elements organized linearly, with each element accessed by an integer index.

Interpreter

A program that simulates a computer that understands a high-level language which analyzes and executes the source code instruction by instruction as necessary

compiler

A program that takes source code and converts it to machine code by producing a separate file.

interpreter

A program that takes source code and translates it to machine code when that code is needed.

understand the problem

A programmer's most important task before planning the logic of a program is to:

interpreted programming

A programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions.

high-level language

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

sytax

A programming language's rules are it's:

subprogram

A section of a computer program that is stored only once but can be used when required at several different points in the program, thus saving space. Also called a procedure or function.

algorithm

A set of commands that returns a value. This differs from a procedure, which is a set of commands that doesn't necessarily have to return a value.

algorithm

A set of specific steps for solving a category of problems

Statement:

A single line of Python code.

pixel

A single point on a graphics screen is called a

True

A single point on a graphics screen is called a pixel.

microprocessors

CPUs located on small chips

x = float(x) print(x)

Cast the string "x" as a float (take the value at the x location, convert it to a float, and return it back to the x location.)

mutation

Change or cause to change in form or nature

attributes

Characteristics of an object which may be used to reference other objects or save object state information.

source code

Code written in a specific language like Java, C++, Ruby, or Python. This code would be converted to machine code at or before running.

False

Comments make a program more efficient (T/F)

high-level computer languages

Computer languages designed to be used and understood by humans

software

Computer programs are also known as:

When the + operator is used with two strings, it performs string _______________.

Concatenation

A(n) ??-controlled loop causes a statement or set of statements to repeat as long as a condition is true.

Condition

What type of loop structure repeats the code based on the value of the Boolean expression

Condition-controlled loop

True/False: According to the behavior of integer division, when an integer is divided by an integer, the result will be a float.

False

True/False: In Python, an infinite loop usually occurs when the computer accesses the wrong memory address.

False

True/False: Python allows you to compare strings, but it is not case sensitive.

False

True/False: Python formats all floating-point numbers to two decimal places when outputting using the print statement.

False

True/False: The Python language is not sensitive to block structuring of code.

False

_____ is the process of inspecting data that has been input to a program to make sure it is valid before it is used in a computation.

Input validation

true

Instance variables are used to store data inside an object

immutable

Not able to change in form or nature

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

Target Variable

memory

Temporary, internal storage

CPU

The "brain" of the computer is the

format operator

The % operator takes a format string and a tuple of values and generates a string by inserting the data values into the format string at the appropriate locations.

logical operators

The AND and OR operators. The important property they have which is different from other operators is that the second operand expression is evaluated only when necessary.

methods

The set of messages that an object responds to are called the ______ of the object

True

The split method breaks a string into a list of substrings, and join does the opposite

Any computer can carry out the same tasks as any other computer

The statement "All computers have the same power" means:

false

The statement myShape.move(10,20) moves myShape to the point (10,20)

{}

The string "slots" that are fulled in by the format method are marked by

syntax

The structure of a program

counted loop

The template for <variable> in range(<expr>) describes a

a generic sentinel value

The term "eof" represents:

batch

The term for a program that does its I/O with files is

flowcharts and pseudo-code

The two most commonly used tools for planning a program's logic are:

Numeric constant

The value 3 is a ______.

24

The value of 4! is

string

The value of this variable type doesn't necessary need to be a letter. We can also have ______s that are numbers.

Garbage

The value stored in an uninitialized variable is ______?

int(some_number)

The variable "some_number" holds a floating point number. What expression gives the value of some_number as an int?

cast

There are times when you will want to take a variable that is one type and make it behave like it's a different type. We call this ______ing. For example, if you have a string and you want to be a number, you would ______ it as a float.

True/False: A better way to repeatedly perform an operation is to write the statements for the task once, and then place the statements in a loop that will repeat the statements as many times as necessary.

True

True/False: An action in a single alternative decision structure is performed only when the condition is true.

True

True/False: Both of the following for clauses would generate the same number of loop iterations: 'for num in range(4):' for num in range(1,5):

True

True/False: Computer programs typically perform three steps: Input is received, some process is performed on the input, and output is produced.

True

True/False: Expressions that are tested by the if statement are called Boolean expressions.

True

True/False: In Python, print statements written on separate lines do not necessarily output on separate lines.

True

True/False: In flowcharting, the decision structure and the repetition structure both use the diamond symbol to represent the condition that is tested.

True

True/False: Nested decision structures are one way to test more than one condition.

True

True/False: Python allows programmers to break a statement into multiple lines.

True

True/False: RAM is a volatile memory used for temporary storage while a program is running.

True

True/False: The CPU understands instructions written in a binary machine language.

True

True/False: The \t escape character causes the output to skip over to the next horizontal tab.

True

True/False: The first line in the while loop is referred to as the condition clause.

True

variables can be reassigned?

True

False

True or False: A chaotic function can't be computed by a computer

False

True or False: Computer science is the study of computers

Syntax

_______ of a language is its form

Semantics

_______ of a language is its meaning

loop

a control construct for executing portions of a program multiple times

input file

a file from which data is read

output file

a file that data is written to

method

a function that belongs to an object

true

a hardware float can represent a larger range of values than a hardware int

arithmetic operators

a mathematical function that takes two operands and performs a calculation on them. Examples: +, -, *, **, %, /, //

argument

a value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.

high-level language

allows simple creation of powerful and complex programs

sets

an abstract data type that can store certain values, without any particular order, and no repeated values

end-line comment

appears at the end of a line of code

Language design binding

bounding a symbol to an operation

main

by convention, the statements of a program are often placed in a function called

main function

called when the program starts

secondary storage

can hold data for long periods of time

direct access

can jump directly to any piece of data in the file

data types

categorize value in memory; int, float, str

turtle.pencolor('blue')

changes the color drawn to blue

turtle.fillcolor('green')

changes the color used for filling shapes to green

turtle.heading(90)

changes the heading of the turtle to north or up

turtle.shape('turtle')

changes the shape of the turtle to a turtle

low-level language

close in nature to machine language

_______________ are notes of explanation that document lines or sections of a program.

comments

input device

component that collects the data Ex. keyboards, mouse, touch screen, camera

A(n) _______________ expression is made up of two or more Boolean expressions.

compound

true

computers represent numbers using base 2 representations

In a decision structure, the action is _______________ executed because it is performed only when a certain condition is true.

conditionally

operator

constructs which behave generally like functions, but which differ syntactically or semantically from usual functions. Examples: arithmetic (addition with +, comparison with >) and logical operations (such as AND or &&)

string

contains a string of letters

text file

contains data that has been encoded as text

binary file

contains data that has not been converted to text

A(n) _____ structure is a logical design that controls the order in which a set of statements execute.

control

upper

converts all the characters of a string to upper case

str

converts to a string

The _______________ is the part of a computer that actually runs programs and is the most important component in a computer.

cpu

argument

data given to a function

output

data produced by the computer for other people or devices

operand

data that may have operators performed upon it. Example: 2 + 3 The numbers 2 and 3 here are operands and are performing addition through the use of the + operator.

input

data the computer collects from people and other devices

Python uses _______________ to categorize values in memory.

data types

short circuit evaluation

deciding the value of a compound Boolean expression after evaluating only one sub expression

Write a function named powers() that takes a positive integer n as input and prints, on the screen, all the powers of 2 from 2^1 to 2^n.

def powers(n): for i in range(1,n+1): print(2**i)

keyword

define the language's syntax rules and structure, and they cannot be used as variable names

digital

describes any device that stores data as binary numbers

relational operator

determines whether a specific relationship exists between two values Ex. <

flowchart

diagram that graphically depicts the steps in a program

In flowcharting, the _______________ symbol is used to represent a Boolean expression.

diamond

types of secondary storage

disk drive, solid state drive, flash memory, optical devices

print function

displays output on the screen

bit

electrical component that can hold positive or negative charge, like on/off switch

In a print statement, you can set the _____ argument to a space or empty string to stop the output from advancing to a new line.

end

==

equal to

traceback

error message that gives information regarding line numbers that caused the exception

exception

error that occurs while a program is running

value-returning function

executes the statements it contains, and then returns a value back to the statement that called it

Boolean expression

expression tested by if statement to determine if it is true or false

True

expressions are built from literals, variables, and operators

pseudocode

fake code

sequential access

file read sequentially from beginning to end, can't skip ahead

After the execution of the following statement, the variable sold will reference the numeric literal value as a(n) _____ data type: sold = 256.752

float

Iterate through list "pets" through the indexes

for i in range(len(pets)): #i is assigned 0, 1, 2... print(pets[p]) #print object at index i

output device

formats and presents output Ex. video display, printers

The _______________ specifier is a special set of characters that specify how a value should be formatted.

formatting

Distinguish method vs. a built in function

function has curly braces after it, method has .'dot' notation.

raw_input()

function that enabled the user to insert their string. Now obsolete

input()

function that enables user to insert data as a string

assignment statement

gives value to a variable

>

greater than

>=

greater than or equal to

The term _______________ refers to all of the physical devices that a computer is made of.

hardware

win = GraphWin("MyWindow")

how would you create a 200x200 graphics window titled MyWindow?

Python provides a special version of a decision structure known as the _______________ statement, which makes the logic of the nested decision structure simpler to write

if elif else

A(n) _______________ statement will execute one block of statements if its condition is true, or another block if its condition is false.

if/else

True

in Python, x = x + 1 is a legal statement

ints to floats

in a mixed-type expression involving ints and floats, Python will convert from ____ to _____

comment

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

statement

individual instruction used in high-level language

The _____ function reads a piece of data that has been entered at the keyboard and returns that piece of data, as a string, back to the program.

input

The _____ built-in function is used to read a number that has been typed on the keyboard.

input()

input validation

inspecting input before it is processed by the program

statement

instruction that the Python interpreter can execute

integer vs. float

integer is a number w/out a decimal; float is a number with a decimal

The Python _______________ is a program that can read Python programming statements and execute them.

interpreter

The Python _______________ is a program that can read Python programming statements and execute them.

interpreter or console

count-controlled loop

iterates a specific number of times

byte

just enough memory to store a letter or small number, divided into 8 bits

False

keywords make good variable names

How do you identify the length of a list?

len(list)

<

less than

<=

less than or equal to

turtle.penup()

lifts the pen to stop drawing

In Python, a comma-separated sequence of data items that are enclosed in a set of brackets is called a _____.

list

What type of error produces incorrect results but does not prevent the program from running?

logic

control structure

logical design that controls order in which set of statements execute

infinite loop

loop that does not have a way of stopping

nested loop

loop that is contained inside another loop

reassignment operators

makes an assignment to an existing variable. Examples: +=, -=, *=, /=

repetition structure

makes computer repeat included code as necessary

indentations in python

mean that there is a code block

The % symbol is the remainder operator and it is also known as the _______________ operator.

modulus

turtle.forward(50)

moves a turtle forward 50 units

variable

name that refers to a value

variable

name that represents a value stored in the computer memory

!=

not equal

comments

notes of explanation within a program

numeric literal

number written in a program

iteration

one execution of the body of a loop

false

operations like addition and subtraction are defined in the math library

logical operators

operators that can be used to create complex Boolean expressions Ex. and, or

operators

perform operations on data

programmer

person who can design, create, and test computer programs aka software developer

function

piece of prewritten code that performs an operation

turtle.dot()

places a dot on the screen

key words

predefined words used to write program in high-level language

syntax error

prevents code from being translated

"reading data from"

process of retrieving data from a file

A(n) _______________ is a set of instructions that a computer follows to perform a task.

program

modularized program

program wherein each task within the program is in its own function

system software

programs that control and manage basic operations of a computer

application software

programs that make computers useful for every day tasks

What is the informal language that programmers use to create models of programs that have no syntax rules and are not meant to be compiled or executed?

pseudocode

turtle.stamp()

puts a stamp down in the current shape

turtle.pendown()

puts the pen down so the turtle can draw

How do you iterate through a list by index instead of value?

range(len(list))

readline method

reads a line from the file

read method

reads entire file contents into memory

garbage collection

removal of values that are no longer referenced by variables

"writing data to"

saving data on a file

In _______________ mode, the interpreter reads the contents of a file that contains Python statements and executes each statement.

script

string

sequence of characters that is used as data

program

set of instructions that a computer follows to perform a task aka software

syntax

set of rules to be followed when writing a program

sequence structure

set of statements that execute in the order they appear

algorithm

set of well-defined logical steps that must be taken to perform a task

void function

simply executes the statements it contains and then terminates

Programs are commonly referred to as

software

operators

special tokens that represent computations like addition, multiplication and division

sentinel

special value that marks the end of a sequence of items

design structure

specific actions performed only if a condition exists aka selection structure

source code

statements written by programmer

mode

string specifying how the file will be opened Ex. 'r' 'w' 'a'

string literal

string that appears in actual code of a program

for

the Python keyword that proceeds a block of code to loop through a series of statements.

false

the int data type is identical to the mathematical concept of an integer

semantic

the meaning of a program

true

the number of possible rearrangements of n items is equal to n!

central processing unit (CPU)

the part of the computer that actually runs programs. the most important component

accumulator

the pattern used to compute factorial is

hardware

the physical devices that make up a computer

square root

the sqrt function computes the _____ of a number

target variable

the variable which is the target of the assignment at the beginning of each iteration

iterate

to say or do again

math operator

tool for performing calculations

Which of the following represents an example to calculate the sum of the numbers (accumulator)?

total += number

upper-left

traditionally, the ___________ corner of a graphics window has coordinates (0,0)

interpreter

translates and executes instructions in high-level language program

assembler

translates assembly language to machine language for execution by CPU

compiler

translates high-level language program into separate machine language programs

Boolean variable can reference one of two values: _____.

true or false

turtle.left(25)

turns a turtle left 25 degrees

dual alternative decision structure

two possible paths of execution Ex. if, else

Language Implementation binding

type sizes vary from machine to machine but are bounded when the compiler is installed

assignment statement

used to create a variable and make it reference data

open function

used to open a file

compiler

used to translate high-level language into machine language

assembly language

uses short words (mnemonics) for instructions instead of binary numbers

operands

values surrounding operator

A(n) _______________ is a name that represents a value stored in the computer's memory.

variable

abs

what is not a Python type-conversion?

Circle(Point(50,50),10).draw(win)

what statement would draw a circle of radius 10 and centered at (50,50) in a graphics window win?

from mymodule import *

what statement would import all the components of a library named mymodule ?

Lifetime

when a variable exists in a program

main memory

where computer stores a program while program is running, and data used by the program aka Random Access Memory (RAM)

What is the format for the while clause in Python

while condition : statement

while loop

while condition is true, do something

Assignment Statement

x = 4

sort method

x.sort() method is used to sort a list.

exponentation

z = a**2 print(z)

addition, multiplication, division

z2 = a + (b * z) / a print(z2)

int

A Python data type that holds positive and negative whole numbers

comments

Are intended for human readers, ignored by Python, and begin with a # sign

for loop

Executes a block once for each element of a collection.

False

Are programmers comments required to create a runnable program or a form of external documentation? (T/F)

false

The process of associating a file with an object in a program is called "reading" the file

specification

The process of describing exactly what a computer program will do to solve a problem is called

Input Process Output

The program pattern IPO stands for:

Divisions has higher precedence than subtraction

Which of the following is true about arithmetic precedence?

for loops

"for x in list_name" ... applies something to every item in a list

if mpg < 15: print("uber polluter") elif mpg > 30: print("nice job") else: print("not bad")

#if mpg < 15, print uber polluter #if mpg > 30, print nice job #if mpg between 15 and 30, print not bad

modulus operator

%, works on integers (and integer expressions) and gives the remainder when the first number is divided by the second

list

''A variable type which can store multiple items together as one variable, and each of those items can actually have different types. For example, the first item could be integer, second item a float, and third item a string. myList = [4, 6.5, 'a'] print(myList) ''' myList has three items in and to access each individual item, we use the index of the item. Indexing starts at 0, so the first item is myList[0], the second is myList[1], and the third is myList[2] ''' print(myList[0]) print(myList[1]) print(myList[2])

Boolean Expression

2 < 3 True

What will the statement 'for num in range(2, 9, 2)' produce

2, 4, 6, 8

If value1 is 2.0 and value2 is 12, what is the output of the following command? print(value1 * value2)

24.0

The program development cycle is made up of _____ steps that are repeated until no errors can be found in the program.

3

List

A Python data type that holds an ordered collection of values, which can be of any type. This is equivalant to an "array" in many other languages. Python lists are "mutable," implying that they can be changed once created.

module

A file containing definitions and statements intended to be imported by other programs.

inheritance

A form of code reuse. We can create a new class, but instead of writing it from scratch, we can base it on an existing class.

constructor

A function that creates a new instance of a class is called

boolean function

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

Print

A function to display the output of a program. Using the parenthesized version is arguably more consistent.

print

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

Pixels

A graphics display is composed of a grid of very small picture elements whose color can be controlled. This elements are called:

false

A graphics window always has the title "Graphics Window"

block

A group of consecutive statements with the same indentation.

Which routines call which other routines.

A hierarchy chart tells you ______.

Prompt

A message that asks a user for input is a ______?

dot-notation

A method is invoked using what?

mutator

A method that changes the state of an object is called a(n)

accessor

A method that returns the value of an object's instance variable is called

Python

A modern programming language named after Monty Python

list

A mutable collection of objects. The elements in a list can be of any type, including other lists.

file

A named entity, usually stored on a hard drive, floppy disk, or CD-ROM, that contains a stream of characters.

function

A named sequence of statements that performs some useful operation.

function

A named sequence of statements that performs some useful operation. Functions may or may not take parameters and may or may not produce a result

It's not practical to solve

A problem is intractable when

validator

A program or service that checks for syntax errors prior to execution

Programming environment

A special computer program that provides facilities to make programming easier

a complete computer command

A statement is

two-way decision

A statement that can have two outcomes. An example would be an if/else statement.

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.

variable

A storage location paired with an associated name or reference. The assigned name is used to reference the data.

false

A string always contains a single line of text

Unicode

A successor to ASCII that includes characters from (nearly) all written language is

range

A type of collection that is a sequence of numbers, such as 1,2,3,4,5.

iterator

A type of loop in Python that uses the keyword "for."

GUI (graphical user interface)

A user interface organized around visual elements and user action is called a(n)

GUI

A user interface organized around visual elements and user interactions is called?

Boolean

A value that is either True or False

local variable

A variable defined inside a function. A local variable can only be used inside its function. Parameters of a function are also a special kind of local variable.

Compile time binding

A variable is bound to a type when a program is compiled

float

A variable type containing a decimal point

integer

A variable type that holds whole numbers

The scope of the variable

A variable's data type describes all of the following except _______?

integer

A whole number (not a fraction) that can be positive, negative, or zero

true

ACSII is a standard for representing characters using numeric codes

indexing

Accessing a single character out of a string is called

The variable used to keep the running total

Accumulator

true

Aliasing occurs when two variables refer to the same object

main memory

All information that a computer is currently working on is stored in

APL Precedence rules

All operators has the same precedence

high-level

An English-like programming language such as Java or Visual Basic is a ____ programming language

True

An algorithm can be written without using a programming language

recipe

An algorithm is like a

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.

runtime error

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

boolean expression

An expression that is either true or false.

variable

An identifier that labels a value for future reference

data and operations

An object combines;

integer division

An operation that divides one integer by another and yields an integer.

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.

expression

Any Python construct that has a value

The programmer's focus differs

As compared to procedural programming, with object-oriented programming, ______.

Dynamic Scope

Based on the calling sequence of subprograms

open

Before reading or writing to a file, a file object must be created via

32

Consider the following program: def main(): >>>num = eval(input("Enter a number: ") >>>for i in range(5): >>>>>>num = num // 2 >>>print(num) main() Suppose the input to this program is 1024, what is the output?

while loop

Continues to execute a block of code as long as a test expression is True.

x = int(x) print(x)

Convert the existing value of x to an integer x. If x has a decimal, it will be truncated, and you will be left with the whole number portion only.

What type of loop structure repeats the code a specific number of times

Count-controlled loop

myBool = True print(myBool)

Create a boolean variable that is set to true (case sensitive)

input

Data that is passed into a procedure

def

Defines a function

function

Defines a function in Python.a named section of a program that performs a specific task

code modularity

Dividing software or an application into smaller modules. This provides prewritten code which saves resources and provides greater manageability.

Which of the following is considered to be the world's first programmable electronic computer

ENIAC

Local variable

Every module has all of the following except ________?

Import Python's random number generator. Generate a random number, then prompt the user to guess a number between 0 and 100. If the guess was too high or too low, tell them, and prompt them to guess again. If the guess was correct, tell them, "that's it. the number was ___."

Explain the steps below: import random number = random.randint(0,100) guess = int(input("Guess a number between 0 and 100: ")) numFound = False while numFound == False: if guess > number: print("You guessed too high") guess = int(input("Guess again: ")) elif guess < number: print("You guessed too low") guess = int(input("Guess again: ")) else: print("That's it. The number was ", number) numFound = True

In Python, you would use the ?? statement to write a count-controlled loop.

For

How do you iterate through a list?

For Loop! scores = [1,2,3,4] for s in scores: print(s)

F = 9/5(C) + 32

Formula for converting Celsius into Fahrenheit

expressions

Fragments of code that produce new data values are called:

A(n) ?? validation loop is sometimes called an error trap or an error handler.

Input

Functions

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.

numbers = range(1,6)

Generate the sequence of numbers 1,2,3,4,5.

radius = 10 area = 3.14 * radius**2 circ = 2 * 3.14 * radius print("the area is:",area) print("the circumference is:",circ)

Given a circle with a radius of 10 units. Calculate the area and circumference ("circ") of the circle. The formula for area is a = pi*r^2 The formula for circumference is 2*pi*r

C All statements that are part of the true path are indented the same amount. Correct

How do you let Python know to execute multiple statements if the condition of an if statement is true? A All statements that are part of the true path are enclosed in curly braces ({ }) B All statements that are part of the true path end with a colon (:) C All statements that are part of the true path are indented the same amount. D Python doesn't allow you to execute more than one statement when the condition evaluates to true.

abs (p1.getX() - p2.getX()))

How would you compute the horizontal distance between points p1 and p2?

library

Huge amounts of code already written, already tested, ready for you to link to and use within your programs. Also called frameworks.

The output of the following print statement is: print ('I\'m ready to begin')

I'm ready to begin

spaces

Identifiers in Python may not contain:

The _______________ statement is used to create a decision structure.

If

C __init__ Correct

If you were asked to write a class named Car, which of the following would be the name of the constructor function? A Car Although Car is the name of our class, Python requires that every class use the keyword __init__ as its constructor's name. The correct answer is: __init__. Incorrect B __Car__ C __init__ D CarConstructor

import random number = random.randint(0,100) guess = int(input("Guess a number between 0 and 100: "))

Import Python's random number generator. Generate a random number, then prompt the user to guess a number between 0 and 100.

true

In Python "4" + "5" is "45"

true

In Python, 4+5 produces the same result type as 4.0+5.0

input

In Python, getting user input is done with a special expression called

processing

In a flowchart, a rectangle represents:

False

In a flowchart, diamonds are used to show statements, and rectangles are used for decision points

grammar

In a programming language like Python, these are the rules that the code must adhere to. When not followed, the interpreter will return a Syntax Error message. This means that the structure of the code is inconsistent with the rules of the programming language. Proper formatting for an expression would be: Expression -> Expression Operator Expression

diamond

In flowcharts, the decision symbol is a:

uses memory

In modern Python, an int value that grows larger than the underlying hardware int does what?

In scope

In most modern programming languages, a variable or constant that is declared in a module is _______ in that module.

print(myList[0])

Index the first item in the list "myList"

C sleep( ).

In order to have your program pause during execution, you use which of the following methods from the time module? A pause( ). B wait( ). C sleep( ). D hold( ).

an import statement

In order to use functions in the math library, a program must include

statements

In programming languages, these are like sentences in English. They use words, numbers, and punctuation to express one thought.

function

In programming, this is a named section of a program that performs a specific task. It only executes when invoked. Is able to both take inputs and provide outputs.

data

Information that is stored and manipulated by computers is called

Issue with Dynamic Type Binding

Its hard to find serious errors

Different type of bindings

Language design binding Language implementation binding Compile time binding Load time binding Link time binding

number

Legal Identifiers cannot start with a

Issues with Dynamic Scope

Less type checking Less reliable

Secondary memory

Magnetic or optical media are generally used for:

Where does a computer store a program and the data that the program is working with while the program is running?

Main memory

RAM (Random Access Memory)

Main memory is also called

using a sequence of bits, using binary representation, and also using only zeroes and ones.

Modern digital computers represent numbers in what ways? (3 ways)

for x in range(1,6): print(x * 2)

Multiply each number ("x") within the given range (of 1 to 5) by 2.

Attributes of a Variable

Name Address Type Value Scope Lifetime

multiplication

Name that operation. z = a*b print(z)

division

Name the operation. a = 5 b = 6 c = a / b (Note: c is a floating point number)

Objects

Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.

slicing

Obtaining a subset of data from a string, array, or list. You may have also heard this called string extraction. In Python you would do this: <String>[<Start Number>:<Stop Number>] = <String>

A compiler is no longer needed after a program is translated.

One difference between a compiler and an interpreter is:

myList = ['a', 2, 'puppies', 4] for item in myList: print(item)

One of the other collection types we saw was a list. In a list, it's a collection of items that can be of different types and we can iterate over the list in the same way that we iterate over a string or a sequence of numbers. For example...

element

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

conditional statement

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

When using the _____ operator, one or both subexpressions must be true for the compound expression to be true.

Or

PEMDAS

Order of operations that Python follows

a is greater than or equal to 4

Output for the following: a = 5 if a < 4: print("a is less than 4") else: print("a is greater than or equal to 4")

procedure

Takes in inputs, does some processing, and produces outputs. This differs from an algorithm, because the processing simply has to execute a set of commands and doesn't necessarily have to return a value.

a = 5 if 4 <= a <= 10: print("a is between 4 and 10") else: print("a is < 4 or > 10")

Print "a is between 4 and 10" or "a is < 4 or > 10" when a equals 5.

while my_str != "d" and my_str != "g": print("not a valid selection")

Print "not a valid selection" if my_str is unequal to d and g.

seconds = 200 mins = int(seconds / 60) s = seconds % 60 print("200 seconds is ",mins, " mins and ", s, "seconds")

Print 200 seconds as a mixed expression of minutes and seconds.

myList = [4, 6.5, 'a'] print(myList)

Print the list "myList," with values of 4, 6.5, and 'a' respectively.

b = 6 print(b)

Print the value of a variable "b" that equals 6.

x = 0 while x < 5: x = x + 1 print(x)

Print x as "x+1" as long as x is less than 5.

False

Printing summaries is a typical housekeeping task. (T/F)

Call

Programmers say that one module can ______ another; meaning that the first module causes the second module to execute.

False

Programs no longer require modification after they are written and debugged

loop

Provide a way to evaluate the same block of code an arbitrary number of times

dictionary

Provides a mapping between keys, which can be values of any immutable type, and values, which can be any value. Because this is implemented using a hash table, the time to lookup a value does not increase (significantly) even when the number of keys increases.

Functions

Python builds functions using the syntax: def function_name(variable): Functions can be stand-alone or can return values. Functions can also contain other functions.

False

Python does not allow the input of multiple values with a single statement

True

Python identifiers must start with a letter or underscore

Why use classes?

Python is an object-oriented programming language, which means it manipulates programming constructs called objects. You can think of an object as a single data structure that contains data as well as functions

mutable

Python lists are _______, but strings are not

+, -, *, /

Python operators that perform mathematical operations.

What symbol is used to mark the beginning and end of a string?

Quotation

Main memory is commonly known as _______________.

RAM

What type of volatile memory is usually used only for temporary storage while running a program?

RAM

exception

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

The ?? function is a built-in function that generates a list of integer values.

Range

if a == 3: print("a equals 3")

Relational operators all perform the same task of specifying a relation in an if statement, that is then evaluated to be true or false For example, to check if a is equal to 3, you use...

A(n) ?? structure causes a statement or set of statements to execute repeatedly.

Repetition

What is the structure that causes a statement or a set of statements to execute repeatedly?

Repetition

Class

Same as data type

Static Scope

Scope rules are determined prior to execution

string

Sequence of characters surrounded by quotes

false

Since floating point numbers are extremely accurate, they should generally be used instead of integers

return

Specifies the value to be outputted by a function back to its function call

Classes of variable Lifetime

Static Stack-Dynamic Explicit Heap Dynamic Implicit Heap Dynamic

Data Type

String, Int, Float, Boolean

Strings

Strings store characters and have many built-in convenience methods that let you modify their content.

the value contains 10

Suppose a program executes the following statement: >>>value = eval(input("Enter a number: ")) In response to the prompt, the user types 5 + 5. What is the result?

x = x + 5

Suppose that the variable x currently has the value 20. What statement would cause the value of x to become 25?

10 and 10

Suppose the variable x has the value 5 and y has the value 10. After executing these statements: >>> x = y >>> y = x what will the values of x and y be, respectively?

10 and 5

Suppose the variable x has the value 5 and y has the value 10. After executing these statements: >>> x, y = y, x what will the values of x and y be, respectively?

hello()

Suppose we interactively define a new function as follows: def hello(): print("Hello") print("Computers are fun") What would you type to invoke (run) this function?

print

The Python reserved word for performing output to the screen is:

clone

The _____ method is provided to make a copy of a graphics object

print()

The ______ statement is a command built in to Python. When you run the .py file, the Python interpreter knows to display whatever is contained between the ().

append

The _______ method can be used to add an item to the end of a list

is a binary operator

The assignment operator _____.

False

The best way to write a program is to immediately type in some code and then debug it until it works

True

The detail loop in a typical program will execute the most. (T/F)

Method & procedure

The following are terms used as a synonym for module in some programming languages.

The range() Function

The range() function returns a list of integers, the sequence of which is defined by the arguments passed to it. Used in for loops.

To make names easier to read, separate long names by using underscores or capitalization for each new word.

The following is valid advice for naming variables?

an expression that returns the result of evaluating what the user types

The fragment of code eval(input("Enter a number: ")) is best describes as:

What can be computed?

The fundamental question of computer science is

To create an algorithm that solves the problem

The goal of the design phase of the software development process is:

To determine what the program should do

The goal of the specification phase of the software development process is:

arguments

The inputs to a procedure. (may also be called parameters)

parameters

The inputs to a procedure. There can be any number of parameters, including none. (may also be called arguments)

parameters

The items listed in the parentheses of a function definition are called

s-1

The last character of a string s is at position

input, processing, and output

The major computer operations include:

getMouse()

The method in the graphics library used to get a mouse click is

False

The method in the graphics library used to get a mouse click is readMouse.

Functional cohesion

The more that a module's statements contribute to the job, the greater the ________ of the module.

float

The most appropriate data type for storing the value of pi is

translate programming language statements into machine language

The most important task of a compiler or interpreter is to:

32

The number of distinct values that can be represented using 5 bits is

If the "if" is true

The only time the "else" block won't execute

flow of execution

The order in which statements are executed during a program run.

precedence

The order of operations. A rule used to clarify which procedures should be performed first in a given mathematical expression.

input and output

The parallelogram is the flowchart symbol representing

while

Think of ______ as a repeating "if."

invoke

To activate, usually references the calling of a function in a program.

concatenate

To connect or link in a series or chain.

modulus (%)

To convert decimals to mixed expressions, use the ______. (i.e., to convert 200 seconds into minutes and seconds, use the ______ of dividing by 60.)

iteration

To repeat a section of code.

indexing

To select sub-sequences. Positions are numbered starting with 0.

evaluate

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

print(c)

Use this statement to check the value of a variable "c"

Goto Statement

Used to branch from one part of code to another

comparison operator

Used to make a comparison between two values. Examples: <, >, <=, >=, ==, !=

graphics window

Using graphics.py allows graphics to be drawn into a

Flase

Using graphics.py allows graphics to be drawn into a python shell.

The len() Function

Using len(some_object) returns the number of _top-level_ items contained in the object being queried. Length of string

Overloaded operators

Using the same operator for different operations

The str() Function

Using the str() function allows you to represent the content of a variable as a string, provided that the data type of the variable provides a neat way to do so. str() does not change the variable in place, it returns a 'stringified' version of it.

Static Lifetime

Variable exists in a memory location before execution

Implicit heap dynamic Lifetime

Variable exists when assigned a value

Stack Dynamic Lifetime

Variable exists when declaration statement is executed

Explicit heap dynamic Lifetime

Variable exists when memory is Allocated

Dynamic Type binding

Variable types are bounded during the runtime or can change during the runtime

Static Type binding

Variable types does not change after the program compiles

Variables

Variables are assigned values using the '=' operator, which is not to be confused with the '==' sign used for testing equality. A variable can hold almost any type of value such as lists, dictionaries, functions.

Named constant

Variables that are assigned a value that cannot be changed

programming languages

Visual Basic, C++, and Java are all examples of computer ...

Comments

What are nonexecuting statements that programmers place within code to explain program statements in English?

1. Performing arithmetic with a value before inputting it 2. Accepting two input values when a program requires only one 3. Dividing by 3 when you meant to divide by 30

What are some examples of logical errors?

read, readline, readlines

What are the file-reading methods in Python?

Specification, Testing/Debugging, and Maintenance

What are the steps in the software development process?

C There's no guarantee as to what order the key-value pairs will appear in the output. Correct

What can be said about the output from the following line of code that prints the dictionary, my_dictionary? A The key-value pairs will be arranged so that the keys are in increasing order. B The key-value pairs will be arranged so that the values are in increasing order. C There's no guarantee as to what order the key-value pairs will appear in the output. D Only the values will be printed from this statement.

str

What cannot be used to convert a string of digits into a number?

Triangle (not) Rectangle, Polygon, Oval are classes

What class is not a class in the graphic library? What are three classes?

cyan

What color is color_rgb(0,255,255)?

shape.draw(win)

What command would be used to draw the graphics object shape into the graphics window win?

win.setcoords(0,0,10,10)

What command would set the coordinates of win to go from (0,0) in the lower-left corner to (10,10) in the upper-right?

p2.getX() - p1.getX()

What computes the horizontal distance between points p1 and p2?

Red Green Blue

What does 'rgb' stand for?

Graphical user interface

What does GUI stand for?

Name & data type

What does a declaration provide for a variable

Small changes in the initial conditions lead to dramatic changes in the result.

What does it mean for a mathematical model to be "chaotic?"

Line(Point(2,3), Point(4,5))

What expression would create a line from (2,3) to (4,5)?

ord

What function gives the Unicode value of a character?

Rectangle

What graphics class would be best for drawing a square?

B A syntax error would occur. Correct

What happens when you attempt to sort a list containing both strings and numbers? The string values will come before all of the numeric values. B A syntax error would occur. C The values will be treated like strings and sorted accordingly. While this seems like a natural way to handle a situation like this, it's not something that Python 3 allows. The correct answer is: A syntax error will occur. Incorrect D The numeric values will come before all of the string values.

statements

What is NOT used in an expression?

They are usually only approximations.

What is a disadvantage of using binary floating point representations?

Constructor

What is a method that creates a new instance of a class?

misspelling a programming language word

What is an example of a syntax error?

A python numeric type that can represent positive and negative whole numbers.

What is an int?

Aliasing

What is it called when two different variables refer to the same object in "memory"?

sqrt()

What is not a built-in operation?

clone()

What is the Method that returns duplicate of the object is?

It causes the program to do something 10 times.

What is the effect of the following Python statement? >>>for i in range(10):

sticky-note

What is the most accurate model of assignment in Python?

Abstraction

What is the name for the process of paying attention too important properties while ignoring nonessential details.

1. Understand the problem 2. Plan the logic 3. Code the program 4. Use software (compiler or interpreter) to translate the program into machine language 5. Test the program 6. Put the program into production 7. Maintain the program

What is the order of the programming process?

2 6 10 14

What is the output from the following program fragment? >>>for i in [1, 3, 5, 7] >>>>>>print(2 * i, end=" ")

D It keeps the Frame open until the user chooses to close it.

What is the purpose of the Frame's mainloop method? A It adds other widgets to the Frame. B It creates the Frame. C To pause the program for a specified amount of time. D It keeps the Frame open until the user chooses to close it.

[1,3,5]

What is the result of evaluating "list(range(1,7,2))?

7.0

What is the result of evaluating 3 + 4.0?

1

What is the result of evaluating 7%2?

3

What is the result of evaluating 7//2?

[0, 1, 2, 3, 4]

What is the result of evaluating the expression list(range(5))?

s[-1]

What is the same as s[0:-1]

0.71136

What is your first number printed by the following program, assuming that the user enters 0.24 as the input? def main(): x = eval(input("Enter a number between 0 and 1:")) for i in range(10): x = 3.9 * x * (1 - x) print(x)

rational

What isn't a Python data type?

Entry

What kind of object can be used to get text input in a graphics window?

plotPixel(x,y,color)

What method is used to draw pixel at the raw position(x,y) ignoring any coordinate transformations set up by SetCoords?

B The x and y locations of the upper-left and lower-right corners of the oval's bounding box.

What parameters are required to make an oval using the create_oval method? A The x and y locations of the oval's center and the oval's height and width. B The x and y locations of the upper-left and lower-right corners of the oval's bounding box. C The x and y locations of the upper-left corner of the oval and its height and width. D The x and y locations of the oval's two foci and the distance from these foci.

p = win.getMouse()

What statement can be used to get the position of a mouse click from the user?

Count-controlled loop

What type of loop structure repeats the code a specific number of times.

C Counter controlled loop.

What type of loop uses a variable to keep track of the number of times the loop body should execute? A Conditional loop. B Control loop. C Counter controlled loop. D Infinite loop.

5

What would Python print as a result of this interaction: >>> print(2 + 3)

p = win.getMouse()

What would you you use to find the position of a mouse click from the user?

Methods

When a class has its own functions, those functions are called methods. You've already seen one such method: __init__().

Load time binding

When a program is loaded the addresses are bound to the variables

Link time binding

When a program links to a library the names of the variables and subprograms in the library are bound

requires more memory to store.

When a python int gets "too large" it:

Scope

When a variable is visible

A This code is executed only if the loop exits normally. Correct

When is the code in the else clause of a loop executed? A This code is executed only if the loop exits normally. B This code is executed only if the loop doesn't exit normally. C The code is always executed. D Never. You can't place an else clause after a looping structure.

When will the following loop terminate? while keep_on_going != 999 :

When keep_on_going refers to a value not equal to 999

True

When you use an IDE, as opposed to a simple text editor to develop a program, some help is provided (T/F)

Why would you use range(len(list))?

When you want to iterate through a list by index instead of value. ie: list of strings ie: when comparing values in a list. -index i is followed by i+1

False

When you write a program that will run in a GUI environment as opposed to a command-line environment, all the syntax is the same (T/F).

A input

Which Python function is used to get string input from the user? A input B raw_input C get_input D string_input

It is electronic

Which is not part of the definition of a computer?

Entry objects can be edited by another user

Which is one difference between a text object and an entry object?

B Entry. Correct

Which of the following Tkinter widgets allows the user to enter text data into the program? A Textbox. Although many other languages call these components Textboxes, this isn't the term for the text input widget in Tkinter. The correct answer is: Entry. B Entry. C Button. D Checkbutton.

setTextColor(color) setStyle(style) setText(string)

Which of the following are three method of 'Entry' object?

D range(10, 21, 2)

Which of the following calls to the range function will give me the even numbers from 10 to 20, including both 10 and 20? A range(10, 20) B range(10, 20, 2) C range(9, 20, 2) D range(10, 21, 2)

D choice == "Y" or "y"

Which of the following compound conditions will evaluate to true even when the value in the choice variable is "N"? A choice == "Y" or choice == "y" B choice == "Y" or == "y" C choice == "Y" and choice == "y" D choice == "Y" or "y"

C c Correct

Which of the following flags opens a shelf file for both reading and writing? A r+ B w+ The 'w+' flag opens a regular data file for both reading and writing, but not for a shelf file. The correct answer is: c. Incorrect C c D None because it isn't possible to open a shelf file for both reading and writing.

instance variable

Which of the following is not a category of an object method?

monitor

Which of the following is not one of the functional building blocks of a computer system:

B The statements that may create an exception are put in the try block, and the statements to execute should an exception occur are put in the except block. Correct

Which of the following is true regarding exception handling? The statements that may create an exception are put in the except block, and the statements to execute should an exception occur are put in the try block. This is exactly opposite of how exception handling code is set up. The correct answer is: The statements that may create an exception are put in the try block, and the statements to execute should an exception occur are put in the except block. B The statements that may create an exception are put in the try block, and the statements to execute should an exception occur are put in the except block. C All of the statements are put inside the try block, and typically the except block is left empty. D All of the statements are put inside the except block and typically the try block is left empty.

B CTRL + C

Which of the following key combinations will stop Python in the middle of running an infinite loop? A CTRL + X B CTRL + C C ALT + F D ALT + E

A self.

Which of the following keywords must be included as a parameter in every class function? A self. B class. C def. D param.

A coords( ).

Which of the following methods changes the location of a shape on the Canvas? A coords( ). B move_shape(). C relocate( ). D update( ).

A grid( ).

Which of the following methods registers a widget with the layout manager so that the widget is displayed on the Frame? A grid( ). B layout( ). C add( ). D register( ).

B A constructor is a special function that sets the initial values of an object's variables.

Which of the following statements best describes a constructor? A A constructor is a special variable that stores the initial values of the object. B A constructor is a special function that sets the initial values of an object's variables. C A constructor is a part of IDLE that builds classes. D A constructor is a special function that displays all of the values of all variables in a particular object.

D continue.

Which of the following statements can be used inside a loop structure to skip the remaining lines of code in that iteration of the loop and start a new iteration? A break. B else. C skip. D continue.

C The parameter list is placed in the first line of the function definition, just after the function name. Correct

Which of the following statements regarding parameter lists is correct? A If a function doesn't require any parameters, then parentheses aren't used. B If more than one parameter is required, each one is separated by a colon. C The parameter list is placed in the first line of the function definition, just after the function name. D Parameters are always listed with the data type first, followed by the variable name.

D print (emp01.__doc__ )

Which of the following statements will print the documentation string comment that's a part of the Employee object named emp01? A print (Employee.__class__ ) B print (emp01.__documentation__ ) C print (emp01.__class__ ) D print (emp01.__doc__ )

B A class.

Which of the following terms describes code that is used as a blueprint to create a Python object? A A pattern. B A class. C An instance. D A blueprint.

B Name mangling.

Which of the following terms describes the action of the interpreter to somewhat deny direct access to an object's variables? A Encapsulation. B Name mangling. C Data hiding. D Access restriction.

D se.

Which of the following values is used with the create_text method's anchor option so that the point specified represents the lower-right corner of the text placement? A nw. B ne. C sw. D se.

Modularization allows you to more easily reuse your work

Why use modularization?

win.close()

Windows can be closed/destroyed by issuing what command?

coding

Writing a program in a language such as C++ or Java is known as _____ the program

interpreted language

You write source code and that file is used to run the program. When you run that file an interpreter is used to process the source code when it is needed. Can run on any platform and is easier to test. User must have the interpreter to run the program.

compiled language

You write source code, and compiler goes through that code and creates a separate file containing the machine code. That new file is used to run the program. Can be faster than interpreted code. Must be compiled for a specific platform.

The line continuation character is a _____.

\

Class Syntax

•call class then class name (parameter) • then create a function def__init with 'self' as the 1st parameter comma then 2nd parameters. •call self.name = name and self.occupation = occupation •create a new variable and have it equal to your example object and use built in parameters to build your objects parameters.


Related study sets

Polysaccharides (Complex Sugars)

View Set

Caffeine, Ephedrine, and Ma Huang

View Set

Chapter 01: Mental Health and Mental Illness

View Set

microecon Final exam chapters 10, 11, 12, 13

View Set