Intro To Computing - Python 3 Pt 1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

def main() : a = 10 print(doTwice(a)) def doTwice(x) : x = x * 2 x = x * 2 return x main() What output is generated when this program is run?

40

How many copies of the letter A are printed by the following loop? i = 0 while i < 5 : print ("A") i = i + 1

5

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])

2. it will print all the characters in even index positions and the o character appears both times in an even location.

What are some examples for Boolean Expressions?

True, False, 3==4, 3+4==7

Evaluate the following comparison: "Dog" < "Doghouse"

True. Both match up to the g but Dog is shorter than Doghouse so it comes first in the dictionary.

T/F The string is a mutable data structure.

False

What is printed by the following code snippet? print(Hello)

Nothing, an error is produced indicating that Hello is not defined

A _______ error is detected when the action which an expression describes cannot be carried out, even though that expression is syntactically correct.

Semantic

T/F The same variable name can be used in two different methods.

True

T/F You can rewrite any for-loop as a while-loop.

True

What code snippets will generate a random integer between 0 and 79?

val = int(random() * 80) OR randomNum=random.randrange(0,80)

Assume a class exists named Fruit. Which of the following statements constructs an object of the Fruit class?

x = fruit.Fruit()

What is printed by the following statements? s = "python rocks" print(s[1] * s.index("n"))

yyyyy

How many return statements can be included in a function?

zero or more

ValueError

____ occur when you pass a parameter to a function and the function is expecting a certain type, but you pass it a different type. These errors are not always caused by user input error,

NameError

_____ almost always mean that you have used a variable before it has a value. Often these errors are simply caused by typos in your code.

Modules

functions and other resources in python that are coded in components

What range of numbers are generated by the random() function?

greater than or equal to zero and less than one

What is printed by the following statements? s = "python rocks" print(s[3])

h

What letter is displayed by the following code segment? title = "Python for Everyone" print(title[3])

h

What is printed by the following statements? s = "python rocks" print(s[3:8])

hon r. start with the character at index 3 and go up to but not include the character at index 8.

What is the value of words after the following code segment? words = "Hello" + "World" * 3

"HelloWorldWorldWorld"

Which statement(s)in python allows us to write programs that implement iterations?

"for" , "while",

hich of the following properly expresses the precedence of operators (using parentheses) in the following expression: 5*3 > 10 and 4+6==11

((5*3) > 10) and ((4+6) == 11) * and + have higher precedence, followed by > and ==, and then the keyword "and"

How many copies of the letter B are printed by the following loop? i = 0 while i == 5 : print ("B") i = i + 1

0

What is the index value of the letter 'h' in the string below ? message = "hello"

0

What will the following nested for-loop print? for i in range(3): for j in range(2): print(i, j)

0 0 0 1 1 0 1 1 2 0 2 1 i will start with a value of 0 and then j will iterate from 0 to 1. Next, i will be 1 and j will iterate from 0 to 1. Finally, i will be 2 and j will iterate from 0 to 1.

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

0. idx goes through the odd numbers starting at 1. o is at position 4 and 8.

Consider the following pseudocode. What does is produce? Set a = 0 Set b = 0 Set c = 1 Set d = 1 Output the value of d Repeat until a equals 10 Set d = b + c Set b = c Set c = d Add 1 to a Output the value of d

1 1 2 3 5 8 13 21 34 55 89

What will the following loop print on the screen? for count in range(4): print (count, end=" ")

1 2 3 4

How many times does the following while loop run? i = 0 j = 1 while j >= 1 : print (i , ";" , j) i = j + 1 if i % 2 == 0 : j = j - 1

1 time

def main() : a = 5 print(doubleIt(a)) def doubleIt(x) : return x * 2 main() What output is generated when this program is run?

10

How many times does the following loop execute? i = 0 found = False while i < 100 and found != True : i = i + 1 print (i) j = i * i if i * i * i % j == j : found = True

100 times

How long is the sequence of numbers produced by: range (-10, 11, 2)

11 numbers

How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s: print("HELLO")

12. there are 12 characters, including the blank.

Consider the following Python code. def pow(b, p): y = b ** p return y def square(x): a = pow(x, 2) return a n = 5 result = square(n) print(result) What does this function print?

25 The function square returns the square of its input (via a call to pow)

What is printed by the following code snippet? print("25 + 84")

25 + 84

What is printed by the following statements? s = "python rocks" print(s.count("o") + s.count("p"))

3

How many times does the following while loop run? i = 0 j = 1 while j >= 1 : print (i , ";" , j) i = i + 1 if i % 3 == 0 : j = j - 1

3 times

What is the output of this code snippet? str = "ABCabc" i = 0 while i < len(str) : ch = str[i] if ch.islower() : print(i , " ") else : i = i + 1

3333.... (infinite loop)

How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s[3:8]: print("HELLO")

5. The blank is part of the sequence returned by slice

What value is printed when the following statement executes? print( int(53.785) )

53

What is the value of j at the end of the following code segment? j = 0 for i in range(0, 4) : j = j + i

6

n the following code, how many lines does this code print? for number in [5, 4, 3, 2, 1, 0]: print("I have", number, "cookies. I'm going to eat one.")

6

What are the final values of the variables i, j, and n at the end of this loop? i = 0 j = 12 n = 0 while i != j : i = i + 2 j = j - 2 n = n + 1

6 6 3

What are the two parts of an if statement

A condition and a body

String

A sequence of characters enclosed in quotes

Algorithm

A sequence of steps that is unambiguous, executable, ad terminating. It is a step by step list of instructions that describes a computational process.

What are the steps of the software development process?

Analyze the Problem, Determine specifications, Create a Design (come up with an algorithm), Implement the Design, Test and Debug the Program and Maintain the Program.

What will be the range of the random numbers generated by the following code snippet? import random randomNum = random.randrange(1,50)

Between 1 and 49

Consider the following code: for aColor in ["yellow", "red", "green", "blue"]: alex.forward(50) alex.left(90) What does each iteration through the loop do?

Draw one side of a square

What is printed by the following statements: s = "Ball" s[0] = "C" print(s)

Error. Strings are immutable

Evaluate the following comparison: "dog" < "Doghouse"

False. The length does not matter. Lower case d is greater than upper case D.

Evaluate the following comparison: "dog" < "Dog"

False. upper case is less than lower case according to the ordinal values of the characters.

What is printed by the following code snippet? print("Good", "Morning", "Class", "!")

Good Morning Class !

What are comments for?

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

What is the difference between a high-level programming language and a low-level programming language?

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. Python is a high level language but must be interpreted into machine code (binary) before it can be executed.

What is printed by the following statements: s = "ball" r = "" for item in s: r = item.upper() + r print(r)

LLAB. The order is reversed due to the order of the concatenation.

What does the following code print? if 4 + 5 == 10: print("TRUE") else: print("FALSE") print("TRUE")

Python will print FALSE from within the else-block (because 5+4 does not equal 10), and then print TRUE after the if-else statement completes.

What is printed by the following code snippet? name = "Robert" formalName = name.upper() print(formalName)

ROBERT

In the command range(3, 10, 2), what does the second argument (10) specify?

Range should generate a list that stops at 9 (including 9). Range will generate the list [3, 5, 7, 9].

What does the following code print if 4 + 5 == 10: print("TRUE") else: print("FALSE")

Since 4+5==10 evaluates to False, Python will skip over the if block and execute the statement in the else block.

The following code snippet contains an error. What is the error? cost = int(input("Enter the cost: ")) if cost > 100 cost = cost - 10 print("Discounted cost:", cost)

Syntax error: missing colon after if statement

What is printed by the following code snippet? print("The answer is", 25 + 84)

The answer is 109

What is printed by the following code snippet? print("The answers are:", 4 + 3 * 2, 7 * 5 - 24)

The answers are: 10 11

Assume that s is an arbitrary string containing at least 2 characters. What is displayed by the following code segment? print(s[0], s[len(s) - 1])

The first character of s, followed by a space, followed by the last character of s.

Source Code

The instructions in a program, stored in a file. The file that contains the instructions written in the high level language

What is the output of the following print statement? print('The path is D:\\sample\\test.')

The path is D:\sample\test.

What is a variable's scope?

The range of statements in the code where a variable can be accessed.

Semantic Error

This error is not something you can detect easily. Your program will run successfully in the sense that the computer will not generate any error messages. However, your program will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

What is the purpose of the following algorithm, written in pseudocode? num = 0 Repeat the following steps 15 times Ask user for next number If userNum < num num = userNum Print num

To find the smallest among 15 numbers.

What are some rules for forming valid Python identifiers and expressions.

To form an identifier, use a sequence of letters either in lowercase (a to z) or uppercase (A to Z). However, you can also mix up digits (0 to 9) or an underscore (_) while writing an identifier

Is the following statement legal in Python (assuming x, y and z are defined to be numbers)? return x + y < z

Yes, It is perfectly valid to return the result of evaluating a Boolean expression.

Parse Errors

____ happen when you make an error in the syntax of your program. Usually these errors can be traced back to missing punctuation characters, such as parenthesis, quotation marks, or commas

TypeErrors

_____ occur when you you try to combine two objects that are not compatible. For example you try to add together an integer and a string. Usually these can be isolated to lines that are using mathematical operators, and usually the line number given by the error message is an accurate indication of the line.

How many statements can appear in each block (the if and the else) in a conditional statement?

a block must contain at least one statement and can have many statements.

What is supplied to a function when it is called

arguments

The following code snippet has an error, how can this be corrected so it prints: 123 Main Street? 1. street = " Main Street" 2. address = 123 + street 3. print(address)

change the value '123' in line 2 to a string using the type conversion str function

codelens allows you to

control the step by step execution of a program.

Assume that you have an integer variable, pennies, that currently contains an integer number of pennies. Which statement determines the number of dollars and cents for that number of pennies?

dollars = pennies // 100 cents = pennies % 100

What is the output of the code snippet given below? s = "abcde" j = len(s) - 1 while j >= 0 : print(s[j]) j = j - 1

edcba

What happens if you give range only one argument? For example: range(4)

if you only give one number to range it starts with 0 and ends before the number specified incrementing by 1.

In python, ___, _____, and ____ are called numerical data types

int, long, float

Which statement finds the last letter of the string variable name?

last = name[len(name) - 1]

Given the code snippet below, what code is needed to print the person's initials? firstName = "Pamela" middleName = "Rose" lastName = "Smith"

print(firstName[0], middleName[0], lastName[0])

What is printed by the following statements? s = "python" excl = "!" print(s+excl*3)

python!!!

What is printed by the following statements? s = "python" t = "rocks" print(s + t)

pythonrocks

What statement computes the square root of 5 and stores it in the variable, r? Assume that the math module has already been imported.

r = math.sqrt(5)

What is printed by the following statements? s = "python rocks" print(s[len(s)-5])

r. len(s) is 12 and 12-5 is 7. Use 7 as index and remember to start counting with 0.

What command correctly generates the list [2, 5, 8]?

range(2, 10, 3). The first number is the starting point, the second is the maximum allowed, and the third is the amount to increment by.

iteration

repetition of a mathematical or computational procedure applied to the result of a previous application.

What is printed by the following statements? s = "python rocks" print(s[7:11] * 3)

rockrockrock

Run time Error

this error does not appear until you run the program. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. An example of this error would be attempting to divide by 0.

What is printed by the following statements? s = "python rocks" print(s[2] + s[-5])

tr

What is the correct Python expression for checking to see if a number stored in a variable x is between 0 and 5

x > 0 and x < 5

Consider the following Python code. Note that line numbers are included on the left. 1. def pow(b, p): 2. y = b ** p 3. return y 4. 5. def square(x): 6. a = pow(x, 2) 7. return a 8. 9. n = 5 10. result = square(n) 11. print(result) Which of the following best reflects the order in which these lines of code are processed in Python?

1, 5, 9, 10, 6, 2, 3, 7, 11 Python starts at line 1, notices that it is a function definition and skips over all of the lines in the function definition until it finds a line that it no longer included in the function (line 5). It then notices line 5 is also a function definition and again skips over the function body to line 9. On line 10 it notices it has a function to execute, so it goes back and executes the body of that function. Notice that that function includes another function call. Finally, it will return to line 11 after the function square is complete.

What is the value of length after this statement: length = len("Good Morning")?

12

Given the code snippet below, what is returned by the function call: mystery(5,3)? def mystery(num1, num2) : result = num1 * num2 return result

15

a = input("Enter the value of a: ") b = input("Enter the value of b: ") print (a + b)

15. The inputs are automatically evaluated as strings and not integers.

def main() : a = 2 doubleIt(a) print(a) def doubleIt(x) : x = x * 2 main() What output is generated when this program is run?

2

What is printed when the following statements execute? n = input("Please enter your age: ") # user types in 18 print ( type(n) )

<class 'str'> (All input from users is read in as a string)

What is a Boolean function?

A function that returns True or False

What is the difference between a tab ('\t') and a sequence of spaces?

A tab will line up items in a second column, regardless of how many characters were in the first column, while spaces will not.

Pseudocode

Algorithms are often written in a stylized version of English called ______. It is using simple instructions, understandable by a human and should be a series of simple instructions. Using the five building blocks of representations: creating variables, modifying variables, get input or produce output, check for true/false and make decisions, and (if needed) repeat a block of instructions.

How can you determine the type of a variable?

By using the type function Example: print(type(123)) print(type('this is a string'))

What will the following code print if x = 3, y = 5, and z = 2? if x < y and x < z: print("a") elif y < x and y < z: print("b") else: print("c")

C. Since the first two Boolean expressions are false the else will be executed.

How many copies of the letter C are printed by the following loop? i = 0 while i < 5 : print ("C") i = i - 1

Infinity

Who/what typically finds syntax errors?

The compiler / interpreter.

What does the following code print? x = -10 if x < 0: print("The negative number ", x, " is not valid here.") print("This is always printed")

The negative number -10 is not valid here This is always printed

Consider the following code: def square(x): runningtotal = 0 for counter in range(x): 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?

The square function will return x instead of x * x. The variable runningtotal will be reset to 0 each time through the loop. However because this assignment happens as the first instruction, the next instruction in the loop will set it back to x. When the loop finishes, it will have the value x, which is what is returned.

What is printed by the following code snippet if itemCount contains a value of 10 and cost contains 80: if itemCount > 5 : discount = 0.8 totalCost = cost * discount print("Total discounted price is:", totalCost)

Total discounted price is: 64.0

T/F : Functions can have multiple arguments and can return multiple return values.

True

Which type of loop can be used to perform the following iteration: You choose a positive integer at random and then print the numbers from 1 up to and including the selected integer.

a for-loop or a while-loop

The following code contains an infinite loop. Which is the best explanation for why the loop does not terminate? n = 10 answer = 1 while n > 0: answer = answer + n n = n + 1 print(answer)

n starts at 10 and is incremented by 1 each time through the loop, so it will always be positive

Suppose that b is False and x is 0. Which of the following expressions evaluates to True?

not b or b

What output is generated by the following code snippet? firstName = "Pamela" middleName = "Rose" lastName = "Smith" print(firstName[0], middleName[0], lastName[5])

nothing, this causes an index of bounds error

Given the following code snippet, what is considered a parameter variable(s)? def mystery(num1, num2) : result = num1 ** num2 return result mystery(10, 2)

num1, num2

The activecode interpreter allows you to

save programs and reload saved programs, type in python source code, and execute python code right in the text itself.


Ensembles d'études connexes

Practice Cognitive Ability - Human Resource Selection & Staffing

View Set

AP Calc AB (Serrano) 2.1-2.5 Notes

View Set

Financial Accounting - Final Exam

View Set

PrepU: Ch. 8 Fluid and Electrolyte Imbalance

View Set