CSCE 110 Final
'10-90-64633'
>>> [str(number) for number in numbers] ['10', '90', '64633'] >>> '-'.join([str(number) for number in numbers])
1
>>> a = 'aggies' >>> a.index('g')
15
>>> a = 3.141592 >>> camel = 42 >>> fout.write('{0} and {1}'.format(camel, a))
{1, 2, 3, 4, 'apple'}
>>> a = [1, 2, 3, 4, 1, 3, 'apple'] >>> b = set(a) >>> b
'apple orange peach'
>>> another_line = 'apple orange peach ' >>> another_line.strip()
{2, 3, 4}
>>> b = {2, 3, 4, 'apple'} >>> b.remove('apple') >>> b
True
>>> d1 = {'a': 1, 'b':2} >>> d2 = {'b': 2, 'a': 1} >>> d1 == d2
[i + 's' for i in fruit]
>>> fruit = ['apple', 'pear', 'grape'] What line of code do you need to add to get the following output? ['apples', 'pears', 'grapes']
['apples', 'pears', 'grapes']
>>> fruit = ['apple', 'pear', 'grape'] >>> [i + 's' for i in fruit]
0 -1
>>> fruit = ['apple', 'pear', 'grape'] >>> fruit.index('apple') if 'apple' in fruit else -1 >>> fruit.index('peach') if 'peach' in fruit else -1
6
>>> fruit = ['apple', 'pear', 'grape'] >>> fruit.index('grape') + 4
ValueError
>>> fruit = ['apple', 'pear', 'grape'] >>> fruit.index('peach')
['appleapple', 'grapegrape', 'pearpear']
>>> fruits = ['apple', 'grape', 'orange', 'pear', 'melon'] >>> blist = [x * 2 for x in fruits if 'p' in x] >>> blist
[x for x in fruits if 'p' in x]
>>> fruits = ['apple', 'grape', 'orange', 'pear', 'melon'] >>> alist = CODE HERE >>> alist What code needs to go in line 2 in order to get the following output? ['apple', 'grape', 'pear']
16 (The return value is the number of characters that were written)
>>> line1 = 'This is the end\n' >>> fout.write(line1)
fout.write(line2)
>>> line2 = "Let's start again.\n" What code do you have to add next to get an output of 19? >>> CODE HERE
[str(number) for number in numbers]
>>> numbers = [10, 90, 64633] What line of code do you need to add to get the following output? ['10', '90', '64633']
['10', '90', '64633']
>>> numbers = [10, 90, 64633] >>> [str(number) for number in numbers]
2
>>> x = 52 >>> fout.write(str(x))
ValueError (100 is not in list)
>>> x = [10, 20, 30, 20] >>> x.index(100)
1
>>> x = [10, 20, 30, 20] >>> x.index(20)
path
A string like 'C:\\Python39' that identifies a file or directory is called what?
lists, tuples
Among the four collection data types (lists, tuples, sets and dictionaries) which allows for duplicate elements?
lists, dictionaries
Among the four collection data types (lists, tuples, sets and dictionaries) which are mutable?
sets
Among the four collection data types (lists, tuples, sets and dictionaries) which are unordered?
lists, tuples, dictionaries (only keys can be indexed)
Among the four collection data types (lists, tuples, sets and dictionaries) which can be indexed?
class, instance
An instance/class attribute is a Python variable that belongs to a class rather than a particular object. It is shared between all the objects of this class. An instance/class attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object.
Program will print 'Hello' if we change print(d) to print(self.d).
Analyze the code below: class Demo: def __init__(self,d): self.d=d def print(self): print(d) a = Demo(''Hello'') a.print() You cannot use print(self) as a function name. Program has an error because class A does not have a constructor. Program will print 'Hello' if we change print(d) to print(self.d). Syntax Error.
instance
Before you use some objects, like a Turtle object, you must create them. This is formally called creating an __________ instance of the object's class.
mutable
Class objects are mutable/immutable.
File1.readline ()
Consider the file object: File1. How would you read the first line of text? File1.readline () File1.readline () File1.readline () File1.read ()
This is line 1
Consider the following text file: Example1.txt: This is line 1 This is line 2 This is line 3 What is the output of the following lines of code? with open("Example1.txt","r") as File1: file_stuff=File1.readline() print(file_stuff) This is line 1 This is line 1 This is line 2 This is line 3 This is line 1 This is line 2
class Mobile: pass
Create a class called 'Mobile' without any attributes or behavior.
num*fact(num-1) (Suppose n=5 then, 5*4*3*2*1 is returned which is the factorial of 5.)
Fill in the line of the following Python code for calculating the factorial of a number. def fact(num): if num == 0: return 1 else: return _____________________ num*fact(num-1) (num-1)*(num-2) num*(num-1) fact(num)*fact(num-1)
49
Find the output of the code given below? l = [int(x*x) for x in range(3,12,4)] print(l[-2]) 12 9 25 49
Open('dog_breeds.txt', 'r')
Given the file dog_breeds.txt, which of the following is the correct way to open the file for reading as a text file? Open('dog_breeds.txt', 'w') Open('dog_breeds.txt', 'rb') Open('dog_breeds.txt', 'r') Open('dog_breeds.txt', 'wb')
False (this is true for Local)
Global variables accessible only inside the function where the variable was initialized.
global
Global/local variables are accessible throughout the program and inside every function.
C
How can we swap two numbers a = 10, b = 20 in python without using third variable? A - a = b b = a B - a,b = b,a C - both a & b D - b = a a = b
join(seq)
How will you merge elements in a sequence?
lstrip()
How will you remove all leading whitespace in string?
list.pop(obj=list[-1]), list.remove(obj)
How will you remove last object from a list? How will you remove an object from a list?
+
If you define a method named __add__ for a class, you can use this operator on the class objects.
a string
In Python, whatever you enter as input, the input() function converts it into a string an integer a list a number a set
immutable, mutable
In dictionaries, keys are mutable/immutable, and values are mutable/immutable.
len([char for char in string if char == " "])
List comprehension: Count the number of spaces in a string answer = ?
[num for num in nums if num % 8 == 0]
List comprehension: Find all of the numbers from 1-1000 that are divisible by 8 answer = ?
[num for num in nums if "6" in str(num)]
List comprehension: Find all of the numbers from 1-1000 that have a 6 in them answer = ?
local, global
Local/global variables are defined inside a function, while local/global variables are not defined inside any function.
inside
Methods are different from functions because they are defined inside/outside a class definition.
student_obj=Student()
Observe the given 'Student' class and perform the below mentioned operation: class Student: def __init__(self): self.name="" self.mark=0.0 Create an object 'student_obj' for the class 'Student'.
-1
Predict the output: def f(n): if (n < 10): return n - 5 return f(f(n+1)); print(f(4)) 1 0 -1 None
12
Predict the output: def fun(i,j): if(i==0): return j else: return fun(i-1,j+1) print(fun(4,8)) 10 11 12 13
faster, less
Programs that use pure functions (as opposed to modifiers) are faster/slower to develop and more/less error-prone.
def increment(self, seconds): seconds += self.time_to_int() return int_to_time(seconds)
Rewrite the following increment function as a method. def increment(time, seconds): time.second += seconds if time.second >= 60: time.second -= 60 time.minute += 1 if time.minute >= 60: time.minute -= 60 time.hour += 1
It is an illegal command (+ Operator cannot be operated on the sets.)
Suppose we are given with two sets(s1&s2) then what is the output of the code S1 + S2 Adds the elements of the both the sets. Removes the repeating elements and adds both the sets. It is an illegal command. Output will be stored in S1.
(0,0)
The coordinates for turtle's initial position, known as the origin.
read(), readline()
The file function read()/readlines() reads the entire contents of the file and returns a string, while read()/readline() reads and returns the next single line from the file.
is, ==
The is/== operator checks whether both the operands refer to the same object or not, while the is/== operator compares the values of both the operands and checks for value equality.
self
The name used to refer to the current instance of a class within the class definition is: this other self None that
pixel
The smallest rectangular display area on a computer screen.
os.path.exists()
This function checks whether a file or directory exists.
os.path.isdir()
This function checks whether it is a directory.
os.path.isfile()
This function checks whether it is a file.
os.listdir()
This function returns a list of the files (and other directories) in the given directory.
__str__
This method returns a string representation of an object.
Infile.read(2)
To read two characters from a file object infile, we use ____________ Infile.read(2) Infile.read() Infile.readline() Infile.readlines()
del, remove()
To remove a list element, you can use either del/remove() if you know exactly which element(s) you are deleting or del/remove() if you do not know.
'w'
To write a file, you have to open it with what mode as a second parameter? >>> fout = open('output.txt', ???)
False
True/False >>> a1 = [1, 2, 3, 4] >>> a2 = [4, 3, 2, 1] >>> print(a1 == a2)
True
True/False Class methods are defined within a class and perform some action helpful to that specific type of object.
False
True/False The syntax for invoking a class method is the same as the syntax for calling a function.
False
True/False dict1 = {'a': 10, 'b': 20, 'c': 30} dict2 = {'c': 30, 'a': 10, 'b': 20} print(dict1 != dict2)
True
True/False A function can be called from anywhere in a program's code, including code within other functions.
True
True/False A local variable cannot be accessed anywhere outside the function where it is initialized.
False
True/False A recursive function may or may not have a recursive case.
True
True/False Classes can contain functions, called methods available only to objects of that type.
True
True/False Every data value in Python is an object.
True
True/False Every object is an instance of some class.
True
True/False Most of the computation is expressed in terms of operations on objects.
False
True/False Objects are immutable.
False
True/False Only problems that are recursively defined can be solved using recursion.
False
True/False Strictly speaking, functions are necessary.
True
True/False When a function is called, any expressions supplied as arguments are first evaluated.
False
True/False: The larger the pixel, the smoother the lines drawn with them will be.
methods
What are classes made up of?
Append the file "Example.txt"
What do the following lines of code do? with open("Example.txt","a") as writefile: writefile.write("This is line A\n") writefile.write("This is line B\n") Write to the file "Example.txt" Append the file "Example.txt" Read the file "Example.txt"
error (There is no indent.)
What do the following lines of code do? with open("Example3.txt","w") as file1: file1.write("This is line C\n") Append the file "Example3.txt". error Read the file "Example3.txt".
A list of lines
What does the <readlines()> method returns? Str A list of lines List of single characters List of integers
[0, 3, -9, -6, 0, 0]
What does the following code print? nums = [0, -5, 3, -9, -6, -11, 0, 0, 5, 3, 27] print([num for num in nums if num % 3 == 0][:-2]) [0, 3] [0, 3, -9, -6, 0, 0] [0, 3, -9, -6, 0, 0, 3] [0, 3, -9, -6, 0, 0, 3, 27]
['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
What does the following code print? s = 'Hello World!' l = [_s.upper() for _s in s[:-1]] print(l) ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D'] ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D', '!'] It throws an error
['Bye', 'OK']
What does the following code print? words = ['Bye', 'OK', 'Savage', 'Love', 'Calibrate', 'Height', 'Linguistic'] print([word for word in words if len(word) <= 3]) ['Bye', 'OK'] ['Savage', 'Love', 'Calibrate', 'Height', 'Linguistic'] It throws an error
Program gets into an infinite loop
What happens if the base condition isn't defined in recursive programs? Program gets into an infinite loop Program runs once Program runs n number of times where n is the argument given to the function An exception is thrown
True
What is output of 33 == 33.0 ? False True 33 None of the above
input_file = open('ex1.txt', 'r') input_file.close()
What is the correct way to open, read, and close a file called ex1?
True
What is the output of 3 in [1, 2, 3]?
1 2 3
What is the output of for x in [1, 2, 3]: print x?
[786, 2.23]
What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) and tinytuple = (123, 'john')?
a list of Nones (print() returns None.)
What is the output of print(k) in the following Python code snippet? k = [print(i) for i in my_string if i not in "aeiou"] print(k) all characters of my_string that aren't vowels a list of Nones list of Trues list of Falses
good
What is the output of the below snippet of code? def fact(n): if n == 0: return "good" else: return fact(n-4) print(fact(16)) 16 good good good goodgood None of the above
D (Because decrementing condition of 'n' is not present in the while loop.)
What is the output of the following code? def nprint(message, n): while(n > 0): print(message) n-=1 nprint('z', 5) A - zzzz B - zzzzz C - Syntax Error D - Infinite Loop
7
What is the output of the following code? a_list = ['a', 10, 1.23, 'Tom'] b_tuple = (1, 2, 3, 4, 5, 6) print(a_list.index('Tom') + b_tuple.index(5)) 5 6 7 8 Error
[0, 100, -10, 200, -20, 300]
What is the output of the following program? a_list = [-10, 10, -20, 20, -30, 30] b_list = [i*10 if i > 0 else i + 10 for i in a_list] print(b_list) [-100, 100, -200, 200, -300, 300] [-20, 20, -30, 30, -40, 40] [0, 20, -10, 30, -20, 40] [0, 100, -10, 200, -20, 300] Error
NameError
What is the output of the following program? def f(): s = 100 print(s) f() print(s)
24
What is the output of the function if n = 4? def fact(n): if n == 0: return 1 else: return n*fact(n-1) 4 40 24 None
[20, 40, 60, 80, 100]
What is the output? numbers = [10, 20, 30, 40, 50] result = [] for number in numbers: result += [number * 2] print(result)
['P', 'Y', 'T', H', 'O','N']
What is the result of the code given below? print([char.upper() for char in "python"]) ['PYTHON'] 'PYTHON' ['P', 'Y', 'T', H', 'O','N'] PYTHON
[0, 1, 0, 3, 0, 5, 0, 7, 0, 9]
What is the value of l in the code below? l = [0 if x % 2 == 0 else x for x in range(10)] [0, 0, 2, 0, 4, 0, 6, 0, 8, 0] [0, 1, 0, 3, 0, 5, 0, 7, 0, 9] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] It throws an error.
[0, 1, 4]
What is the value of l in the code below? l = [i * i for i in range(3)] [0, 1, 2] [0, 1, 4] [0, 1, 4, 9] It throws an error
[0, 1, 2, 3, 4, 1, 2, 3, 4, 5]
What is the value of l in the code below? l = [i + j for i in range(2) for j in range(5)] [0, 1, 2, 3, 4, 1, 2, 3, 4, 5] [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
[0]
What is the value of l in the code below? l = [i for i in [i for i in range(5)][:-4]] [0] [0, 1, 2, 3, 4] [4] It throws an error
catching an exception
What is this called? try: fin = open('bad_file') except: print('Something went wrong.'
3 7
What will be the output of below Python code? class A: def __init__(self,num): num=3 self.num=num def change(self): self.num=7 a=A(5) print(a.num) a.change() print(a.num)
1 2
What will be the output of below Python code? class Student: def __init__(self,name,id): self.name=name self.id=id print(self.id) std=Student("Simon",1) std.id=2 print(std.id)
prints all characters of my_string that aren't vowels
What will be the output of the following Python code snippet? k = [print(i) for i in my_string if i not in "aeiou"] prints all the vowels in my_string prints all the consonants in my_string prints all characters of my_string that aren't vowels prints only on executing print(k)
[('H', 1), ('E', 1), ('L', 1), ('L', 1), ('O', 1), (' ', 1), ('W', 1), ('O', 1), ('R', 1), ('L', 1), ('D', 1)]
What will be the output of the following Python code snippet? my_string = "hello world" k = [(i.upper(), len(i)) for i in my_string] print(k) [('HELLO', 5), ('WORLD', 5)] [('H', 1), ('E', 1), ('L', 1), ('L', 1), ('O', 1), (' ', 1), ('W', 1), ('O', 1), ('R', 1), ('L', 1), ('D', 1)] [('HELLO WORLD', 11)] none of the mentioned
[['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']]
What will be the output of the following Python code snippet? print([[i+j for i in "abc"] for j in "def"]) ['da', 'ea', 'fa', 'db', 'eb', 'fb', 'dc', 'ec', 'fc'] [['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']] [['da', 'db', 'dc'], ['ea', 'eb', 'ec'], ['fa', 'fb', 'fc']] ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
What will be the output of the following Python code snippet? print([i+j for i in "abc" for j in "def"]) ['da', 'ea', 'fa', 'db', 'eb', 'fb', 'dc', 'ec', 'fc'] [['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']] [['da', 'db', 'dc'], ['ea', 'eb', 'ec'], ['fa', 'fb', 'fc']] ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
['h', 'e', 'l', 'l', 'o'] (We are iterating over each letter in the string.)
What will be the output of the following Python code snippet? print([i.lower() for i in "HELLO"]) ['h', 'e', 'l', 'l', 'o'] 'hello' ['hello' hello
Syntax error
What will be the output of the following Python code snippet? print([if i%2==0: i; else: i+1; for i in range(4)]) [0, 2, 2, 4] [1, 1, 3, 3] Syntax error none of the mentioned
[0, 1, 2]
What will be the output of the following Python code snippet? x = [i**+1 for i in range(3)]; print(x); [0, 1, 2] [1, 2, 5] error, **+ is not a valid operator error, ';' is not allowed
7 (First, a=1+2+3=6. Then, after setattr() is invoked, x.a=6+1=7.)
What will be the output of the following Python code? class change: def __init__(self, x, y, z): self.a = x + y + z x = change(1,2,3) y = getattr(x, 'a') setattr(x, 'a', y+1) print(x.a) 6 7 0 Error
"Hello World" is displayed
What will be the output of the following Python code? class test: def __init__(self,a="Hello World"): self.a=a def display(self): print(self.a) obj=test() obj.display() The program has an error because constructor can't have default arguments Nothing is displayed "Hello World" is displayed The program has an error display function doesn't have parameters
100 (The fun(fun(n+11)) part of the code keeps executing until the value of n becomes greater than 100, after which n-5 is returned and printed.)
What will be the output of the following Python code? def fun(n): if (n > 100): return n - 5 return fun(fun(n+11)); print(fun(45)) 50 100 74 Infinite loop
17
What will be the output of the following Python code? def test(i,j): if(i==0): return j else: return test(i-1,i+j) print(test(4,7)) 13 7 17 infinite loop
C. Error: I/O operation on closed file.
What will be the output of the following code snippet? colors = ['red\n', 'yellow\n', 'blue\n'] f = open('colors.txt', 'w') f.writelines(colors) f.close() f.seek(0,0) for line in f: print (line) A. redyellowblueOption 1 B. ['red\n', 'yellow\n', 'blue\n'] C. Error: I/O operation on closed file. D. Compilation errorOption 3
.read()
When reading a file using the file object, what method is best for reading the entire file into a single string? .readline() .read() .read_file_to_str() .readlines()
__init__()
When we create an object, which function inside the class of that object is invoked automatically?
The file is created
When you try to open a file with the mode 'a' and if the file does not exist, what happens? The file is overwritten. The file is created. An error occurs. The file is open for reading. The file is closed.
The file is open for reading
When you try to open a file with the mode 'r' and if the file already exists, what happens? The file is overwritten. The file is created. An error occurs. The file is open for reading. The file is closed.
An error occurs
When you try to open a file with the mode 'r' and if the file does not exist, what happens? The file is overwritten. The file is created. An error occurs. The file is open for reading. The file is closed.
The file is overwritten
When you try to open a file with the mode 'w' and if the file already exists, what happens? The file is overwritten. The file is created. An error occurs. The file is open for reading. The file is closed.
The file is created
When you try to open a file with the mode 'w' and if the file does not exist, what happens? The file is overwritten. The file is created. An error occurs. The file is open for reading. The file is closed.
classes
Where do objects come from?
Os.path.isfile(logo)
Which of the following functions can be used to check if a file "logo" exists? Os.path.isFile(logo) Os.path.exists(logo) Os.path.isfile(logo) Os.isFile(logo)
All of the above
Which of the following statements are true? When you open a file for reading, if the file does not exist, an error occurs When you open a file for writing, if the file does not exist, a new file is created When you open a file for writing, if the file exists, the existing file is overwritten with the new file All of the above
Every recursive function must have a return value
Which of the following statements is false about recursion? Every recursive function must have a base case Infinite recursion can occur if the base case isn't properly mentioned A recursive function makes the code easier to understand Every recursive function must have a return value
5 apple 6 14.7 7 12 8 pear
a_list = ['apple', 14.7, 12, 'pear'] for index, item in enumerate(a_list, 5): print(index, item)
False
b = {1, 2, 3, 4, 'apple'} c = {3, 4, 'apple', 'banana'} b.issubset(c)
False
b = {1, 2, 3, 4, 'apple'} c = {3, 4, 'apple', 'banana'} b.issuperset(c)
True
b = {1, 2, 3, 4, 'apple'} d = set([1, 2]) d.issubset(b)
instance
class Person: def __init__(self, name): self.name = name Is self.name an instance or class variable?
10:55:00
class Time: def __add__(self, other): seconds = self.time_to_int() + other.time_to_int() return int_to_time(seconds) **assume time_to_int is written as a method >>> start = Time(9, 45, 0) >>> duration = Time(1, 10, 0) >>> print(start + duration)
11:25:30
class Time: def __str__(self): return '{0:02d}:{1:02d}:{2:02d}'.format(self.hour, self.minute, self.second) >>> time = Time(11, 25, 30) >>> print(time)
[x for x in fruits if x != "apple"]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"] Write a code using list comprehension that only accepts items that are not "apple".
True
l1 = [0 for i in range(10)] l2 = [0 if x % 2 == 0 else x for x in range(0, 20, 2)] print(l1 == l2)
result = [number * 2 for number in numbers]
numbers = [10, 20, 30, 40, 50] CODE HERE print(result) What code needs to go in line 2 in order to get the following output? [20, 40, 60, 80, 100]