CS 1064 - Python Midterm Exam

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

true/false: a python program must be compiled into an executable form before it can be run

False

Which of the following expressions could be used to determine if a is not less than b?

a >= b

describe range function

a built-in function that produces a range of integers but it never includes the stop value in the values produced. ex: range(10) = 0 1 2 3 4 5 6 7 8 9

the print statement is:

a call to a function

describe seed value

a number that is used in a complex series of calculations to generate the 'random' numbers

whats a for loop

a repetition statement that allows you to execute a group of statements multiple times. it processes each item in a sequence of items. example: for letter in 'Python': print(letter) output = P y t h o n

whats an escape sequence (\n , \t, \uABCD)

a technique for representing a character in situations where the traditional manner would cause problems or simply be less convenient

by convention, variable names in python should be composed of:

all lowercase letters, with words separated by underscore

append function vs. remove function vs. using an index operator

append - adding an item to the end of a list remove - remove an item from a list index operator - uses an index value to find a specific element in a list

what output does the following code produce? print('apple', 'banana')

apple banana

an ___ statement doesn't affect a program's flow of control but an ____ statement does.

assignment; if

built-in functions vs. built-in types (both don't have to be imported)

built-in functions: print, input built-in types: int, float, str, list, range

what does \n do?

causes output to move to new line ex: print('One\nTwo\nThree') output = One Two Three

The circumference of a circle is two times pi times the radius of the circle. Assuming the radius is already stored in a variable named radius, compute the circumference and store it in a variable named circumference. You may also assume that the math module has already been imported.

circumference = 2 * math.pi * radius

data type can also be used interchangeably with:

class

Write a function called compute_area that accepts a numeric value as an argument representing the radius of a circle. Compute and return the area of the circle. You can assume that the math module has been imported.

def compute_area(radius): return math.pi * radius * radius

Write a function named dice_eval that accepts two parameters representing numeric dice values and returns a string describing the results. If the sum of the dice is 7 or 11, return 'Winner!'. If the sum of the dice is 2, 3, or 12, return 'Craps!'. For all other values, return a string of the form 'Point is xx', where xx is the sum.

def dice_eval(dice1, dice2): if (dice1+dice2)==7 or (dice1+dice2)==11: return 'Winner!' elif (dice1+dice2)==2 or (dice1+dice2)==3 or (dice1+dice2)==12: return 'Craps!' else: return 'Point is '+str(dice1+dice2)

Write code that sets the value of a variable named delicious to True if jellybeans is greater than 20, or licorice is greater than 30, or their sum is greater than 40. Otherwise, set it to False. Do NOT use an if statement in your solution. Assume jellybeans and licorice already have values.

delicious = jellybeans > 20 or licorice > 30 or jellybeans + licorice > 40

depth += 50 * offset is equilvalent to:

depth = depth + (50*offset)

Write code that constructs a string made up of each character in a string variable named word repeated twice. For example, if word contains 'Python', the resulting string would be 'PPyytthhoonn'. Store the constructed string in a variable called double_word. Assume that word has already been initialized.

double_word = '' for letter in word: double_word += (letter+letter)

which way would turtle be facing after this code? turtle.setheading(270) turtle.right(20) turtle.left(65)

down and right (southeast) after facing down, it turns to southwest slightly, then back to the southeast.

true/false: the body of a for loop can't contain another for loop

false

true/false: arithmetic operators have a lower precedence than relational operators

false.

true/false: an if statement can't have both an elif and else clause

false. an else clause is often used after a series of elif clauses

true/false: a python function must have at least one parameter

false. some functions can have no parameters

true/false: in python, the assignment statement is also an expression

false. the assignment operator doesn't return a value

true/false: you must use a print statement to display result of an expression in python shell

false. the expression is evaluated and the result is displayed immediately

true/false: all mathematical functions in python are part of the math module

false. there are built-in functions that perform mathematical operations

true/false: the effect of the setheading depends on the current heading of the turtle

false. when setting the heading explicitly, the current heading doesn't matter

the remainder operator (//) takes the sign of the ____ operand, not the _____.

first; second

what is pass statement and what do you use it for?

has no effect on the program and doesn't change any values of variables. it is used to serve as a placeholder for code that you'll write later

what does \t do?

horizontal tab ex: print('First name:\tMae') output = First name: Mae

Write code that prints 'Doubles!' if the values in the variables die1 and die2 are the same. Otherwise, print the sum of the two dice values. Assume that both variables have already been set.

if die1 == die2: print('Doubles!') else: print(die1 + die2)

to determine if a number is even, check if the number if evenly divisible by another number

if num % 2 == 0: print(num, 'is even.') else: print(num, 'is odd.')`

Write code that examines a string stored in a variable called product_id and prints an appropriate version of the id. If the id is composed of only numeric digits, print it as is. If it is composed of a combination of alphabetic letters and digits, print the id with all alphabetic letters in uppercase. Otherwise (if there are any other type of characters in the id), print it with all alphabetic letters in lowercase. Assume that the product_id has already been initialized.

if product_id.isdigit(): print(product_id) elif product_id.isalnum(): print(product_id.upper()) else: print(product_id.lower())

the body of a while loop may never execute because:

if the condition is false right away, the body of the loop is never executed

define sentinel value and what is it used for

it's a special value used to indicate the end of input. it must be outside the normal range of valid input values and each input value is compared to the sentinel value to know when loop terminates. example: sum = 0 num = -1 while num != 0: sum += num

when comparing strings using < or > what is it asking?

it's asking which string comes before the other based on unicode (lexicographical order)

Write code that concatenates the character strings in str1 and str2, separated by a space, and assigns the result to a variable named joined. Assume that both string variables have been initialized.

joined = str1 + ' ' + str2 print(joined)

a python identifier can only be composed of:

letters (A-Z), digits (0-9), and underscore character. identifiers can't begin with a digit

assignment operators (=) have a _____ precedence than arithmetic operators

lower

what are the modules in the python standard library that have to be imported first

math random string turtle datetime os urllib

What output is printed by the following code if it is executed when appetizer is 3 and entree is 12? if appetizer > 1: if entree < 7: print('ketchup') else: print('mustard') else: if appetizer < 0: print('mayonnaise') else: print('relish')

mustard. first condition is true, but the second is not.

which python types are mutable and immutable?

mutable- str, list, dictionaries, sets immutable- boolean, numeric, sequence, tuple

Compute the natural logarithm of 100 and add it to two times the square root of 75, storing the result in a variable named num. Assume that the math module has already been imported.

num = math.log(100) + (2*math.sqrt(75))

what output is produced? print('oak', 'elm', 'pine', end='!', sep='#')

oak#elm#pine!

python type conversion functions are what kind of functions?

object constructors b/c conversion is the process of creating a new object based on another

all python variables are:

object references, meaning they are names that refer to an object somewhere in memory

the not operator requires ___ operands

one

the turtle circle command can be used to draw a regular polygon. what determines how many sides a polygon will have?

parameter steps

a function that returns a boolean result is called a ______.

predicate function

write code that produces the following line of output: Don't you hate it when someone answers their own question? I do.

print("Don't you hate it when someone answers their own question?", end=' ') print('I do.')

Write code that prints a greeting in the following format: Hi, xxx! where xxx is the name of a person stored in the variable name. Assume that the name variable has been initialized.

print("Hi, ",name,"!", sep="")

what is text that requests user input called?

prompt

If a variable called greeting refers to the string 'hello', what does the expression greeting.upper() accomplish?

returns a new string containing the characters 'HELLO'

Turtle heading (degrees)

see week of 8/30 doc

turtle explicit positioning on coordinate system (goto function)

see week of 8/30 doc

Use an augmented assignment operator to increase the value stored in the variable size by two times the value stored in length. For example, if size is 10 and length is 4, the new value of size should be 18. Assume that size and length already have initial values.

size += (2*length)

Write code that uses a for loop and the range function to compute the sum of the integers from 250 and 300, inclusive. Assign the result to a variable named sum

sum = 0 for num in range(250, 301): sum += num

what is the strip method used for?

takes away leading or trailing whitespace characters in a string

how to swap elements in a list

temp = values[4] values[4] = values[10] values[10] = temp

when comparing numeric data, what should i be careful of?

testing two floating-point values for equality. brings up issue of numeric accuracy

define case sensitive

the difference between uppercase and lowercase letters matter

when calling the randint function, the stop value is inclusive. what does this mean?

the stop value is included in the list of numbers produced

Finding a minimum value requires that every element in the list be examined.

true

Using a while loop to check each input value for correctness is a form of input validation.

true

true/false: If either or both operands to the division operator (//) are floating-point values, then the result will be a floating-point value. if both are integers, then it performs integer division

true

true/false: python variables are created using an assignment statement

true

true/false: the value of a variable can change through a program

true

true/false: a function parameter ceases to exist when the function returns to the caller

true. a parameter is a temporary variable

true/false: the relational operators all return boolean results

true. all produce a result of true or false.

true/false: a character string can be used as the condition of an if statement

true. any object can be used as a condition.

true/false: after a function finishes executing, control returns to the place the function was called

true. control returns when a return statement is executed or when end of function is reached

true/false: position of a circle depends on current heading of turtle

true. the circle is drawn to the left of the turtle

true/false: the input function always return the read data as a character string

true. you have to convert it to another type if needed

Given a character string stored in a variable called word, write code that concatenates the fifth character of the word to the third character from the end of the word, and assigns that string to a variable named two_letters. Assume that word already has a value and is at least five characters long.

two_letters = word[4] + word[-3] it's 4 because indexes start from 0.

how to repeatedly append values to a list and to a specified range `

use a for loop. ex: squares = [] for i in range(15): squares.append(i * i) for i in range(len(squares)-1)): print(squares[i], end=' ') print(squares[-1])

you can't concatenate a string with a numeric value. so what do you do?

use the built-in function str to convert a numeric value to a string before concatenating: subtotal_statement = 'The subtotal is' + str(subtotal)

string method string.lower()

used to compare all input in lowercase

how to find a minimum or maximum value with their indexes in python

values = [58, 23, 70, 105, 64, 12, 174, 33, 51, 4, 72, 40, 84, 73, 96] min_index = 0 for i in range(1, len(values)): if values[i] < values[min_index]: min_index = i print('Minimum value:', values[min_index]) print('Found at index:', min_index)

define truthiness

when you check for truthy/falsey values by assigning a boolean to something

the sample function in the random module takes a sample with or without replacement?

without replacement, meaning all elements in the sample will be unique

what is the output of jedi * 3 if jedi refers to 'Yoda'

YodaYodaYoda

result of math.pow(3,3)

3 to the power of 3 = 27

result of 7 // 2?

3.5 --> 3 (take away fractional part)

what output is produced by this? print(15+30)

45

what are the relational operators?

== = equal != not equal < less than <= less than or equal to > greater than >= greater than or equal to

What is Unicode?

A character set that represents different alphabets and special symbols so has greater range of characters than ASCII (over 100,000)

what causes an infinite loop?

A loop condition that is never false.

what is the result of business[6] if business refers to the string 'Time Warner'

'a' (start from 0 and count characters until index 6)

what is the result of son[-3] if son refers to the string 'Justin'

't' (third character from the end, don't start from 0)

what are the arithmetic operators?

+ = addition - = subtraction * = multiplication / = division % = gets remainder in integer division ** = exponent // = integer/floor division, returning only integer quotient

what evaluates to false aside from boolean expressions?

-numeric value of 0 -empty sequence, like an -empty string(' ') or empty list([]) -empty dictionary ({}) -None

If the variable num contains a positive integer, what are the only two possible results of the expression num % 2? 1 and 2

0 and 1, because 2 either divides the number evenly or there is 1 leftover

if both operands are positive, the remainder operator with a divsor of n will produce an answer in the range _____

0 to n-1

Write code that sets the value of a variable named result to the sum of the values in the variables num1 and num2, unless that sum is in the range 20 to 30, inclusive, in which case set result to 0. Assume num1 and num2 already have values.

1. if 20 <= num1 + num2 <= 30: result = 0 else: result = num1 + num2 2. sum = num1 + num2 if sum in range(20,31): result = 0 else: result = sum

what output does this give? if num1 = 2 and num2 = 3. num2 /= num1 * num2

1. multiple num1 and num2 = 6 2. divide num2 by 6 = 0.5 (expressions are evaluated first)

What value is stored in num after the following code is executed? list = [2, 4, 6, 8, 10] num = 0 for val in list: if val != 6: num = num + val

24. for every value in list that is not 6, add it to num. and continue until end of list

What output is printed by the following code? str = 'Rephactor Python' index = 0 num = 0 while index < len(str): if str[index] == 'o': num += 1 index += 1 print('Num:', num)

Num: 2 b/c the if statement checks to see every index to find 'o'. when they find o, they take initial value of num which is zero and add 1 to it. there's two o's so the body of the while loop gets executed twice so num gets added twice which makes it 2.

what output is produced? print('Ready', end=' ') print('Set', end='') print('Go')

Ready SetGo


Set pelajaran terkait

What is Physical Fitness and Why I Should Do It

View Set