CSCE 110 Midterm
functions
range() and main() are considered these in python
5, 6, 7, 8, 9
range(5,10) returns what?
immutable
tuples are mutable/immutable
==
Which operator can be used to compare two values?
T
T/F The 'in' operator is used to check if a value exists within an iterable object container such as a list. Evaluates to true if it finds a variable in the specified sequence and false otherwise.
yes
Can lists have heterogenous elements? ex: ['dog', 78]
yn
What is the output of the following code? str = "pynative" print (str[1:3])
J,h,o,n
What is the output of the following loop: for l in 'Jhon': if l == 'o': pass print(l, end=", ")
9.0
What is the value of the following Python Expression: print(36 / 4)
(3,4)
What will be the output of the following Python code? p = (2,3,4,5) p[1:-1]
(3,5,4)
What will be the output of the following Python code? p = (2,3,5,4) p[1:4]
[2,5,8]
What will be the output of the following Python code? p = (2,3,5,4,8,9) [p[y] for y in range(0, len(p), 2)]
('apple', 'mango')
What will be the output of the following Python code? x1 = ('apple',) x2 = ('mango',) x3 = x1 + x2 print(x3) (apple, mango) ('apple', 'mango') ('apple''mango') None
set
Which collection does not allow duplicate members? set list tuple
replace()
Which method can be used to replace parts of a string?
<class 'dict'>
axa = {} print(type(axa)) What gets printed? <class 'set'> <class 'dict'> <class 'list'>
element
in the list ['hello', 78], hello and 78 are called this.
docstring
optional comments are called this '''Hello'''
[0.0, 1.0)
Almost all module functions depend on the basic function random(), which generates a random float uniformly in this range. use: random.random():
left to right, right to left
Almost all the operators have left to right/right to left associativity (ex: 5 * 2 // 3 is equivalent to (5 * 2) // 3) but the Exponent operator (**) has left to right/right to left associativity (ex: 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2)).
random.randrange(99, 200, 3)
Choose the correct function from the following list to get the random integer between 99 to 200, which is divisible by 3. random.randrange(99, 200, 3) random.randint(99, 200, 3) random.random(99, 200, 3)
aTuple[1][1]
Choose the correct way to access value 20 from the following tuple: aTuple = ("Orange", [10, 20, 30], (5, 15, 25)) aTuple[1:2][1] aTuple[1:2](1) aTuple[1:2][1] aTuple[1][1]
WelcomeWelcome
Guess the correct output of the following String operations: str1 = 'Welcome' print(str1*2)
Yna PYnat tive PYnativ PYnativ
Guess the correct output of the following code? str1 = "PYnative" print(str1[1:4], str1[:5], str1[4:], str1[0:-1], str1[:-1])
(2,3)
If x=(1,2,3,4), x[1:-1] is _________
ductionary
In order to store values in terms of key and value which core data type is used.
string, tuple, range, integer, float, Boolean
List the data types in python that are IMMUTABLE
list, dictionary, set
List the data types in python that are MUTABLE
tuple str tuple
List the type for each: t1 = 'a', t2 = ('a') t3 = ('a',)
parentheses, index (slicing), exponent, multiplication/division/modulus, add and subtract, comparisons, Boolean (not, and, then or)
Order of operations in python
cannot
Python sets can/cannot contain changeable objects such as list and dictionary.
title(), capitalize()
Python string method capitalize()/title() returns a copy of the string in which the first characters of all the words are capitalized whereas the string method capitalize()/title() returns a copy of the string in which just the first word of the entire string is capitalized.
x, y and z
Read the following Python code carefully and point out the global variables: y, z = 1, 2 def f(): global x x = y+z
sampleDict = {}, sampleDict = dict()
Select correct ways to create an empty dictionary: sampleDict = {} sampleDict = dict() sampleDict = dict{}
True True
Select the correct output of the following String operations: myString = "pynative" stringList = ["abc", "pynative", "xyz"] print(stringList[1] == myString) print(stringList[1] is myString)
Welcom PYnative
Select the correct output of the following String operations: str1 = 'Welcome' print (str1[:6] + ' PYnative')
True True
Select the correct output of the following String operations: strOne = str("pynative") strTwo = "pynative" print(strOne == strTwo) print(strOne is strTwo)
sampleDict['class']['student']['marks']['history']
Select the correct way to access the value of a history subject sampleDict = { "class":{ "student":{ "name":"Mike", "marks":{ "physics":70, "history":80 } } } } answers: sampleDict['class']['student']['marks']['history'] sampleDict['class']['student']['marks'][1] sampleDict['class'][0]['marks']['history']
student[1]["age"]
Select the correct way to print Emma's age: student = {1: {'name': 'Emma', 'age': '27', 'sex': 'Female'}, 2: {'name': 'Mike', 'age': '22', 'sex': 'Male'}} answers: student[0][1] student[1]["age"] student[0]["age"]
A, C
Select the correct ways to get the value of marks key: student = { "name": "Emma", "class": 9, "marks": 75 } A. m = student.get(2) B. m = student.get('marks') C. m = student[2]) D. m = student['marks'])
A, B
Select which is true for for loop: A. Python's for loop used to iterates over the items of list, tuple, dictionary, set, or string B. else clause of for loop is executed when the loop terminates naturally C. else clause of for loop is executed when the loop terminates abruptly D. We use for loop when we want to perform a task indefinitely until a particular condition is met
T
T/F Dictionary keys must be immutable
T
T/F In Python if a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.
T
T/F In Python, 'Hello', is the same as "Hello"
F
T/F In Python, a variable must be declared before it is assigned a value.
T
T/F In Python3, Whatever you enter as input, the input() function converts it into a string
F
T/F In order to execute an operation over arguments of different data types, convert all of them to the same type beforehand.
F
T/F Items are accessed by their position in a dictionary and All the keys in a dictionary must be of the same type.
T
T/F Python does not support a character type; a single character is treated as strings of length one.
T
T/F The symmetric_difference() method returns a set that contains all items from both sets, but not the items that are present in both sets.
T
T/F The union() method returns a new set with all items from both sets by removing duplicates
strings
The join() function only works on a list of ________, NOT a list of integers, floats, or booleans.
loop
To access set items use this.
random.uniform(20.5, 50.5)
To generate a random float number between 20.5 to 50.5, which function of a random module I need to use? random.random(20.5, 50.5) random.uniform(20.5, 50.5) random.randrange(20.5, 50.5) random.randfloat(20.5, 50.5)
a b c Tom Jane Jack
What are the outputs? >>> a = {'a': 'Tom', 'b': 'Jane', 'c': 'Jack'} >>> for person in a: print(person) >>> for person in a: print(a[person])
Concatenates string1 and string2
What does the expression string1 + string2 do? Repeats string1 string2 times (string2 must be in numeric format). Concatenates string1 and string2. It's a syntax error. Adds string1 to string2 (both must be in numeric format).
[11, 15, 19]
What is output for: b = [11,13,15,17,19,21] ptint(b[::2])
print(type(x))
What is the correct syntax to output the type of a variable or object in Python?
Walter Smith Nicole Smith Steven Smith
What is the ouput? name_list = ['Walter', 'Nicole', 'Steven'] for name in name_list: print(name, 'Smith')
True
What is the output (True or False)? 'abc' not in x
False
What is the output (True or False)? 'ale' in 'apple'
True
What is the output (True or False)? 10 < 5 or 15 != 60
PYnative // is for // Python Lovers//
What is the output of the following code print('PYnative ', end='//') print(' is for ', end='//') print(' Python Lovers', end='//')
True
What is the output of the following code: dict1 = {"key1":1, "key2":2} dict2 = {"key2":2, "key1":1} print(dict1 == dict2)
False True
What is the output of the following code: str1 = "My salary is 7000" str2 = "7000" print(str1.isdigit()) print(str2.isdigit())
TypeError (A tuple is immutable.)
What is the output of the following code? aTuple = (100, 200, 300, 400, 500) aTuple[1] = 800 print(aTuple) answer choices: TypeError (100, 800, 200, 300, 400, 500) (800, 100, 200, 300, 400, 500)
400 (200, 300, 400)
What is the output of the following code? aTuple = (100, 200, 300, 400, 500) print(aTuple[-2]) print(aTuple[-4:-1])
Hello-Python
What is the output of the following code? my_list = ["Hello", "Python"] print("-".join(my_list))
Syntax error (We cannot access items in a set by referring to an index because the 'set' object does support indexing(set is unordered). if you try to access items using the index, you will get TypeError: 'set' object does not support indexing. To access set items use looping.)
What is the output of the following code? sampleSet = {"Yellow", "Orange", "Black"} print(sampleSet[1]) answers: Yellow Syntax Error Orange
15
What is the output of the following code? xx = 15 def var_test(): xx = 25 var_test() print(xx)
25
What is the output of the following code? xx = 15 if True: xx = 25 print(xx)
100
What is the output of the following code? xx = 50 def var_test(): xx = 100 return xx print(var_test())
True (In Python, any non-zero value is considered TRUE. So it will evaluate to true)
What is the output of the following if statement: a, b = 12, 5 if a + b: print('True') else: print('False')
[30, 40, 50] [10, 20, 30, 40] [40, 50, 60, 70, 80]
What is the output of the following list operation? aList = [10, 20, 30, 40, 50, 60, 70, 80] print(aList[2:5]) print(aList[:4]) print(aList[3:])
40 [20, 30, 40]
What is the output of the following list operation? sampleList = [10, 20, 30, 40, 50] print(sampleList[-2]) print(sampleList[-4:-1])
2, 1, 0, -1, -2, -3, -4
What is the output of the following range() function: for num in range(2,-5,-1): print(num, end=", ") ans choices: 2, 1, 0 2, 1, 0, -1, -2, -3, -4, -5 2, 1, 0, -1, -2, -3, -4
{'Yellow', 'Orange', 'Red', 'Black', 'Green', 'Blue'}
What is the output of the following set operation? sampleSet = {"Yellow", "Orange", "Black"} sampleSet.update(["Blue", "Green", "Red"]) print(sampleSet) answers: {'Yellow', 'Orange', 'Red', 'Black', 'Green', 'Blue'} {'Yellow', 'Orange', 'Black', ["Blue", "Green", "Red"]} TypeError: update() doesn't allow list as a argument.
(100, 100)
What is the output of the following tuple operation? aTuple = (100,) print(aTuple * 2) TypeError (100, 100) (200)
{40, 10, '10', 50, 20, 60, 30}
What is the output of the following union operation? set1 = {10, 20, 30, 40} set2 = {50, 20, "10", 60} set3 = set1.union(set2) print(set3) answers: {40, 10, 50, 20, 60, 30} {40, '10', 50, 20, 60, 30} {40, 10, '10', 50, 20, 60, 30}
(30, 40, 50) (10, 20, 30, 40) (40, 50, 60, 70, 80)
What is the output of the following: aTuple = (10, 20, 30, 40, 50, 60, 70, 80) print(aTuple[2:5], aTuple[:4], aTuple[3:])
[25, 10]
What is the output of the following? aList = [5, 10, 15, 25] print(aList[::-2])
{'first': 1, 'second': 2, 'third': 3}
What is the output of the following? sampleDict = dict([ ('first', 1), ('second', 2), ('third', 3) ]) print(sampleDict) answers: [ ('first', 100), ('second', 200), ('third', 300) ] Options: SyntaxError: invalid syntax {'first': 1, 'second': 2, 'third': 3}
{'Blue', 'Orange', 'Yellow', 'Black'} (no duplicates)
What is the output of the following? sampleSet = {"Yellow", "Orange", "Black"} sampleSet.add("Blue") sampleSet.add("Orange") print(sampleSet) answers: {'Blue', 'Orange', 'Yellow', 'Orange', 'Black'} {'Blue', 'Orange', 'Yellow', 'Black'}
{'Blue', 'Orange', 'Yellow', 'Black'}
What is the output of the following? sampleSet = {"Yellow", "Orange", "Black"} sampleSet.add("Blue") sampleSet.add("Orange") print(sampleSet)
'catcat dogdogdog'
What is the output? 'cat' * 2 + ' ' + 'dog' *3
('abc', 'abc', 'abc')
What is the output? ("abc",)*3
'1:2:3'
What is the output? >>> ':'.join(['1', '2', '3'])
[0, 0, 0, 0] [1, 2, 3, 1, 2, 3]
What is the output? >>> [0] * 4 >>> [1, 2, 3] * 2
H e l l o
What is the output? >>> a = 'Hello' >>> for c in a: print(c)
[1, 2, 3, 4, 5, 6]
What is the output? >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> c
1
What is the output? >>> a = {'a': 1, 'b': 'Jane', 'b': 'Jack'} >>> a['a']
{'a': 'Tom', 'b': 'Jack'}
What is the output? >>> a = {'a': 1, 'b': 'Jane', 'b': 'Jack'} >>> a['a'] = 'Tom' >>> a
'#apple'
What is the output? >>> line = ' #apple ' >>> stripped_line = line.strip() >>> stripped_line
True False
What is the output? >>> sentence = 'jack and jill went up the hill' >>> words = sentence.split() >>> 'jill' in words >>> 'the hill' in words
7
What is the output? >>> sentence = 'jack and jill went up the hill' >>> words = sentence.split() >>> len(words)
['jack', 'and', 'jill', 'went', 'up', 'the', 'hill']
What is the output? >>> sentence = 'jack and jill went up the hill' >>> words = sentence.split() >>> words
'apple:banana:cantaloupe'
What is the output? >>> sep = ':' >>> values = ['apple', 'banana', 'cantaloupe'] >>> sep.join(values)
apple pear grape orange
What is the output? >>> t = ('apple', 'pear', 'grape', 'orange') >>> for x in t: print(x)
a b c d e f
What is the output? >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> for x in t: print(x)
{'c', 'b', 'a'}
What is the output? >>> t = set(('a', 'b', 'c', 'c')) >>> t
('a', 'p', 'p', 'l', 'e', 's')
What is the output? >>> t = tuple('apples') >>> t
('apple', 'grape', 'peach')
What is the output? >>> t = tuple(['apple', 'grape', 'peach']) >>> t
TypeError
What is the output? >>> t = {'a', 'b', 'c', 'c', 'd', 'd'} >>> t {'c', 'a', 'd', 'b'} >>> t[1]
c b a
What is the output? >>> t = {'a', 'b', 'c'} >>> for item in t print(item)
'apple banana cantaloupe'
What is the output? >>> values = ['apple', 'banana', 'cantaloupe'] >>> sep.join(values) 'apple:banana:cantaloupe' >>> ' '.join(values)
{40, 10, 50, 20}
What is the output? A = {30, 20, 10} B = {50, 30, 40} print(A.symmetric_difference(B))
n a m e s
What is the output? a_string = 'names' i = 0 while i < len(a_string): print(a_string[i]) i += 1
before loop count = 0 count = 1 count = 2 after loop count = 3
What is the output? count = 0 print('before loop') while count < 3: print('count =', count) count += 1 print('after loop') print('count =', count)
I love Python! True False
What is the output? def print_msg(): print('I love Python!') def is_even(num, divisor): print(num % divisor == 0) print_msg() is_even(10, 2) is_even(7, 10)
0 1 2 3 4 5 6 7 8
What is the output? for i in range(9): if i == 3: continue print(i)
0 1 2 3
What is the output? for i in range(9): if i > 3: break print(i)
[-10, -40, -70] (create a list of integers from -10 to -100 in increments of -30)
What is the output? list(range(-10, -100, -30))
0 1 2
What is the output? numbers = range(3) for number in numbers: print(number)
begin a is positive end
What is the output? print('begin') a = 34 if a > 0: print('a is positive') print('end')
['a', 'p', 'p', 'l', 'e', 's']
What is the output? t = list('apples') print(t)
['apple', 'grape', 'peach']
What is the output? t = list(('apple', 'grape', 'peach')) print(t)
[0,3,6,9] (this creates a list integers from 0 to 9 in increments of 3)
What is the output? list(range(0, 10, 3))
0.0
What is the result of round(0.5) - round(-0.5)? 1.0 2.0 0.0
str (To create a tuple with a single item, you need to add a comma after the item, unless Python will not recognize the variable as a tuple, and it will treat it as a string type.)
What is the type of the following variable: aTuple = ("Orange") print(type(aTuple)) list tuple array str
line.lstrip(), line.rstrip()
What two functions remove whitespace from the front and back, respectively?
10 20 30 40
What will be the output of the following Python code? def f(p, q, r): global s p = 10 q = 20 r = 30 s = 40 print(p,q,r,s) p,q,r,s = 1,2,3,4 f(5,10,15)
100
What will be the output of the following Python code? def f1(): x=100 print(x) x=+1 f1()
15
What will be the output of the following Python code? def f1(): x=15 print(x) x=12 f1()
13
What will be the output of the following Python code? def san(x): print(x+1) x=-2 x=4 san(12)
(2,3,4,5)
What will be the output of the following Python code? x = (2,3) y = (4,5) z = x+y z
(8,6)
What will be the output of the following Python code? x,y - 6,8 x,y = y,x x,y
100
What will be the output of the following Python code? x=100 def f1(): global x x=90 def f2(): global x x=80 print(x)
4 12
What will be the output of the following Python code? x=12 def f1(a,b=x): print(a,b) x=15 f1(4)
(2,3,2,3)
What will be the output of the following Python code? p = (2,3) p * 2
list
Which collection is ordered, changeable, and allows duplicate members? set list dictionary tuple
find()
Which function returns the index of the first occurrence of a substring (or -1, if the substring does not exist in a string)?
strip()
Which method can be used to remove any whitespace from both the beginning and the end of a string?
upper()
Which method can be used to return a string in upper case letters?
title()
Which method should I use to convert String "welcome to the beautiful world of python" to "Welcome To The Beautiful World Of Python"
random.sample(samplelist, 4)
Which method should I use to get 4 elements from the following list randomly? random.choice(samplelist, 4) random.sample(samplelist, 4) samplelist = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
can
each element in a list can/cannot be modified.
random.choice()
mylist = ['apple', 'banana', 'cherry'] What function would you choose to return a random element from this list?
1, 2, or 3
random.randint(1, 3) will randomly return what integers?
random.choice(str)
str = "PYnative". Choose the correct function to pick a single character from a given string randomly. random.sample(str) random.choice(str) random.get(str, 1)
{2, 3}
what is the output of this intersection: a = {1,2,3} b = {2,3,4} a & b
{1, 2, 3, 'c', 'b', 'a'}
what is the output of this union: a = {1,2,3} b = {'a', 'b', 'c'} a | b
Error
What gets printed? p = 'abb' q = 2 print(p+q)
print('Hello World')
What is a correct syntax to output "Hello World" in Python?
x = "Hello"[0]
What is a correct syntax to return the first character in a string? x = "Hello"[0] x = sub("Hello", 0, 1) x = "Hello".sub(0, 1)
def myFunction():
What is the correct way to create a function in Python?
int
What is the data type of (1)?
sets are unordered and unindexed, dictionaries are ordered and mutable
What is the difference between sets and dictionaries?
True
What is the output of print 0.2 + 0.3 == 0.5
2
What is the output of print(2%6) ValueError 0.33 2
25 50
What is the output of the following code x = 50 def fun1(): x = 25 print(x) fun1() print(x)
syntax error
What is the output of the following code: sampleSet = {"Yellow", "Orange", "Black"} print(sampleSet[1]) Yellow Syntax Error Orange
50
What is the output of the following code: x = 100 y = 50 print(x and y)
75
What is the output of the following code? a = 75 def var_test(): return a print(var_test())
63
What is the output of the following code? def var_test(): b = 63 return b print(var_test())
10, 11, 12, 13, 14,
What is the output of the following code? for i in range(10, 15, 1): print( i, end=', ')
The program executed with error (The set is an unordered data structure. So you cannot access/add/remove its elements by index number.)
What is the output of the following code? sampleSet = {"Jodi", "Eric", "Garry"} sampleSet.add(1, "Vicki") print(sampleSet) {'Vicki', 'Jodi', 'Garry', 'Eric'} {'Jodi', 'Vicki', 'Garry', 'Eric'} The program executed with error
maJ
What is the output of the following code? var= "James Bond" print(var[2::-1])
-2, -3, -4
What is the output of the following for loop and range() function: for num in range(-2,-5,-1): print(num, end=", ")
Emma 25
What is the output of the following function call: def fun1(name, age=20): print(name, age) fun1('Emma', 25)
10 11 12 13
What is the output of the following nested loop: for num in range(10, 14): for i in range(2, num): if num%i == 1: print(num) break
10 Chair 10 Table 20 Chair 20 Table
What is the output of the following nested loop? numbers = [10, 20] items = ["Chair", "Table"] for x in numbers: for y in items: print(x, y)
['b','e']
What is the output of the following program? a = list('abcdefg') print(a[1::3])
90
What is the value of x after the following nested for loop completes its execution? x = 0 for i in range(10): for j in range(-1, -10, -1): x += 1 print(x)
100
What is the value of x: x = 0 while (x < 100): x+=2 print(x)
dictionary
What is this called? {"name": "apple", "color": "green"}
f
What will be the output of the following Python code? alpha = ('a', 'g', 'f') print(alpha[-1])
g
What will be the output of the following Python code? alpha = ('a', 'g', 'f') print(alpha[1])
45
What will be the output of the following Python code? d = {'jimmy':45, 'jack':40} d['jimmy']
3
What will be the output of the following Python code? fruit = ('apple', 'orange', 'apple', 'cherry', 'apple') print(fruit.count('apple'))
Error as tuple is immutable
What will be the output of the following Python code? x - (5,6,7,8) del(x[2]) Now, a=(1,2,4) Now, a=(1,3,4) Now a=(3,4) Error as tuple is immutable
('CheckCheckCheck')
What will be the output of the following Python code? x = ('Check') * 3
route66, Age, home_address
Which of the following are valid Python variable names: route66 4square ver1.3 Age home_address return
x y z = 1 2 3
Which of the following is an invalid statement? num = 1,000,000 x y z = 1 2 3 x,y,z = 1, 2, 3 x_y_z = 1,000,000
*
Which of the following operators has the highest precedence? not & * +
my-var
Which one is NOT a legal variable name? my-var Myvar my_var _myvar
**
Which operator has higher precedence in the following list % (Modulus) & (BitWise AND) ** (Exponent) > (Comparison)
break
Which statement is used to stop a loop?
T
T/F Python syntax is case-sensitive.
T
T/F The first character of a variable in Python can be a letter or an underscore.
F
T/F We can use the float numbers in range() function.
T
T/F When A is a set, A >= A
F
T/F When a is a set, a < a
True False
What is the output of the following code? listOne = [20, 40, 60, 80] listTwo = [20, 40, 60, 80] print(listOne == listTwo) print(listOne is listTwo)
10 20 30
What is the output of the following code? p, q, r = 10, 20 ,30 print(p, q, r)
<class 'function'>
What is the output of the following code? print(type(lambda:None)) <class 'type'> <class 'function'> <class 'bool'>
0, 1
For splicing x[a:b:c]: if a is missing, the value is ___ if c is missing, the value is __ if b is missing, the value is the length of the string.
3
Given the nested if-else below, what will be the value x when the code executed successfully: x = 0 a = 5 b = 5 if a > 0: if b < 0: x = x + 5 elif a > 5: x = x + 4 else: x = x + 3 else: x = x + 2 print(x)
[x,y]
If x and y are strings, which of the following is equivalent to [x] + [y] ? [x].extend([y]) [x,y] [x + y] [x].append(y)
for, while
Use a for/while loop when you know exactly how many times a loop needs to run, and a for/while loop when you can't predict how often it repeats
string, list, tuple, set, dictionary (NOT int, float, bool)
data types in python that are iterables
T
T/F In Python, a variable may be assigned a value of one type, and then later assigned a value of a different type.
F
T/F Only immutable data types can be used as keys for dictionaries in Python.
T
T/F Python function always returns a value
brackets, parentheses, squiggly braces,
What are each of the following data structures inclosed in: lists tuples dictionaries and sets
2
Given the nested if-else structure below, what will be the value of x after code execution completes: x = 0 a = 0 b = -5 if a > 0: if b < 0: x = x + 5 elif a > 5: x = x + 4 else: x = x + 3 else: x = x + 2 print(x)