Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Python Midterm Exam, the questions are based on python3 syntax
Question 1: Consider following code, what will be printed?
int a
a=2+3
a=10
print(a)
A. 5
B. 10
C. Nothing
D. Error
Question 2: Consider following code, what will be printed?
a=10
b=3
c=a//b
print(type(c))
A. <class 'float'>
B. <class 'int'>
C. Nothing
D. Error
Question 3: Consider following code, which (one) statement below is true?
a=5
b=10
c=15
d=a+b+c
a="The value of d is "+ d
print(a)
A. Program will throw an error because variable ‘a’ cannot be changed from int to string
B. Program will run and print “The value of d is 30”
C. Program will not run because of an incorrect concatenation on line 5
D. Program will run and print “The value of d is ”
Question 4: Consider following code, use numbers after hashtags as line numbers, which of the lines will result in
error?
_m=3 #1
n=3 #2
s3=3 #3
$m=3 #4
in=3 #5
A. 1,3
B. 4,5
C. 3,4
D. 1,3,4,5
Question 5: Consider following code, what will be printed?
s="ab"
s=s*2
print(len(s), " ", s[5])
A. 4 b
B. 2 b
C. Error, because string cannot be multiplied by a number
D. Error, because s does not have element at index 5
Question 6: Write a program (~3 lines) that takes two user inputs and outputs the sum of the two floats user has
entered. Do not validate user input (it’s ok if program breaks because user did not enter a valid float)
Sample output:
first number:1.2
second number:1.3
2.5
.
.
.
.
.
.
.
.
Question 7: What does this line print:
>>> bool("False") and bool("") and bool(1)
A. True
B. False
C. Error because strings cannot be converted to booleans
D. Error because numbers cannot be converted to booleans
Question 8: Consider following code. What will be printed?
a=10
b=20
c=30
d=40
if(a != b):
if(b <= c):
print("1")
elif(b == c):
print("2")
else:
print("3")
else:
if(a > b):
print("4")
else:
print("5")
A. 5
B. 1
C. 3
D. Running the program will result in an error
Question 9: Consider following code. What will be printed?
a=0
b=0
while(a<12):
a=a+3
while(a>b):
b=b+4
print(a, " ", b)
A. The program will result in an error
B. 15 12
C.12 12
D.15 16
Question 10: Write 3 lines (or less) of code that will keep asking the user “wanna play?” as long as the user enters
“yes”. If you write more than 3 lines of code, this answer will be marked wrong.
.
.
.
.
.
.
Question 11: Complete the program below, so it prints ‘2,3,4,5,’ exactly.
s=“”
for number in range(
):
s=s+
print(s)
Question 12: Consider following code. What will be printed?
for number in range(1,13,4):
if(number == 4):
continue
if(number == 5):
break
print(number)
A.
1
5
B.
1
5
9
C.
1
D. Nothing will be printed
E. Program results in error
Question 13: Complete following program such that it prints ‘Python’ backwards - ‘nohtyP’
s="Python"
for i in range(1,7):
print(
) #your code goes inside print statement
Question 14: Use slice notation to extract the “hello” from string s:
s="hello, how are you?"
.
.
Question 15: Following code runs and prints:
0
7
complete the program so it produces the output above
l1=[1,2,3,4]
l2=[5,6,7,0]
___________________________ #code missing here
print(min(l1))
print(max(l1))
Question 16: Consider the code below, what will be printed?
l1=[12,32,12,32,12]
l2=["0", "1", "2", "3", "4", "5"]
s=""
for number in l1:
s=s+l2[l1.count(number)]
print(s)
A. 32323
B. 43434
C. 32
D. The program will result in an error
Question 17: One of the lines in the following code causes an error, circle that line
s = ["P", "y", "t", "h", "o", "n"]
p = [0,0,0,0,0,0]
l = "Python"
r = "000000"
for k in range(len(l)):
p[k]=s[k]
r[k]=l[k]
print(r)
print(p)
Question 18: Complete following code so that it prints [0, 5]
l = [1,2,3,4,5]
l[__:__]=[___]
print(l)
Question 19: Sample output of the program below is:
enter the size of the matrix:2
element at [0, 0]:1
element at [0, 1]:2
element at [1, 0]:3
element at [1, 1]:4
[['1', '2'], ['3', '4']]
Complete the program such that it produces the output above
size=input("enter the size of the matrix:")
b = []
for i in range(______________):
___________________________
for j in range(______________):
n = input("element at [{}, {}]:".format(___________________))
_______________________________________________
_________________________________
print(b)
Question 20: Consider the code below, what will be printed?
y = [1,2]
x = [6,7]
a=y
b = x[:]
d = y*1
e = x+[]
y[0] = 100
x[0] = 600
print(a, b, d, e)
A.[100, 2] [6, 7] [1, 2] [6, 7]
B.[1, 2] [6, 7] [1, 2] [6, 7]
C.[100, 2] [600, 7] [1, 2] [6, 7]
D. Running this program will result in an error
Question 21: Consider the code below, what will be printed?
x=["melon", "Apple", "banana", "Apricot"]
x.sort()
print(x)
A. ['Apple', 'melon’, 'banana', ’Apricot']
B. ['Apple', 'Apricot', 'banana', 'melon']
C. ['banana', 'melon’, 'Apple',’Apricot']
D. ["melon", “Apple", "banana", "Apricot"]
Question 22: True or False? It is not possible to create a custom sort function for standard Python types. Circle
Correct Answer: True
False
Question 23: Consider the code below. What will be printed?
x = [[1],[3],[5]]
y = x[:]
x[0]=100
x[1][0]=4
print(y)
A.[[1], [3], [5]]
B.[100, [4], [5]]
C.[100, [3], [5]]
D.[[1], [4], [5]]
Question 24: True or False? Python has built-in module that handles deep copy of the standard Python types True
False
Question 25: True or False? Following code will error out.
True
t=(1,2,3,4,5)
t[2] = 0
print(t)
Question 26: True or False? Sets are immutable. True
False
False
Question 27: For the data structure below, write a code that will loop through the structure and print each element
out
data_set={“And now here is my secret","All grown-ups were once children”}
.
.
.
.
.
Question 28: True or False? Any immutable and hashable object can be a dictionary key. True
False
Question 29: Given the structure below, write a program that adds up the values of the items and prints the total
data={"milk":4.25, "bread":3.00, "honey":5.00}
.
.
.
.
.
.
.
.
.
Question 30: What all is printed when the program is run?
def fun(num):
if num == 0:
return
else:
print(num)
fun(num-2)
fun(6)
.
.
.
.
.
Question 31: What all is printed when the program is run?
def changeme(s, n):
s="two"
n=2
x="four"
y=4
changeme(x,y)
print(x,y)
.
.
.
Question 32: Given following function, write a valid function call:
def myfun(*options):
print(options)
Question 33: Given the function and the call you wrote for question 32, what will be printed once the program is
run?
.
.
Question 34: What was the filename of one of the modules you created as part of your homework?
____________________________ You used that module in another file with this command (write full command)
______________________________________________
Question 35: Following code attempts to traverse a directory fortune1 and delete all files that end with “log”, the
program doesn’t work. Which line is causing the error?
answer:_____________________
1. import os
2. import fnmatch
3. start_dir = "fortune1"
4. for dirpath, dirs, files in os.walk(start_dir):
5.
for single_file in files:
6.
if fnmatch.fnmatch(single_file, "*log"):
7.
print("Deleting ", single_file)
8.
os.remove(single_file)
Question 36: True or false? It is possible to pickle a list of tuples. True
False
Question 37: Given following code, write 1 line demonstrating how data in the shelve can be accessed (assume any
data)
import shelve
d = shelve.open("myq")
.
.
Question 38: Modify following pattern "http://www.newhaven.edu[/\w+]*" to make sure the
URL http://www.newhaven.edu/news-events/ is matched
______________________________________________________________________________
Question 39: Write a regular expression that would match 1-800-PYTHON. You are not allowed to use: . + * ?
____________________________________________________________
Question 40: Module for working with regular expressions is _________
Question 41: An example of error HTTP code is ___________
Quesiton 42: For your last homework, how did you retrieve meaningful searchable data from UNH web pages? (just
1-2 readable lines)
.
.
.
Question 43. Following code returns JSON below, add code that will print only the value of “lat”
of the “coord” (41.27)
import urllib.request
import json
from pprint import pprint
page = urllib.request.urlopen("http://api.openweathermap.org/data/2.5/weather?q=west haven, ct")
content=page.read()
content_string = content.decode("utf-8")
json_data = json.loads(content_string)
pprint(json_data)
.
.
.
{'base': 'cmc stations',
'clouds': {'all': 90},
'cod': 200,
'coord': {'lat': 41.27, 'lon': -72.95},
'dt': 1413416435,
'id': 4845419,
'main': {'humidity': 78,
'pressure': 1015,
'temp': 295.14,
'temp_max': 296.15,
'temp_min': 294.15},
'name': 'New Haven',
'sys': {'country': 'United States of America',
'id': 626,
'message': 0.1054,
'sunrise': 1413371054,
'sunset': 1413411038,
'type': 1},
'weather': [{'description': 'light rain',
'icon': '10n',
'id': 500,
'main': 'Rain'},
{'description': 'mist',
'icon': '50n',
'id': 701,
'main': 'Mist'}],
'wind': {'deg': 130, 'speed': 4.1}}
Question 44: Consider the code below
1. start_dir = "fortune1"
2.
3.
4. for dirpath, dirs, files in _________________________________________________:
5.
for single_file in files:
6.
if fnmatch.fnmatch(single_file, “____________”) or fnmatch.fnmatch(single_file, “_______________”):
7.
8.
9.
filepath = os.path.abspath(os.path.join(____________________________________________))
print("Creating a tuple with {0} file content and {1} path".format(single_file, filepath))
f = open(filepath)
10.
s = _______________________________________
11.
t = (s, filepath)
12.
l.append(t)
13.
f.close()
14.picf = open("raw_data.pickle", “__________”)
15.pickle.dump(l, picf)
16.picf.close()
Answer following Questions:
Question 44A: There are 4 import statements missing, write 2 of the 4 missing import statements
.
.
.
Question 44B: Fill in the blank on line 4 so that the program traverses the “fortune1” directory
Question 44C: Fill in the blanks on line 6 so that the program processes only files with extension .txt and .log
Question 44D. Fill in 2 missing parameters on the line 7 that will create the path to the file
Question 44E. l is a list which holds the tuples, on line 3 write the code to create and initialize l
Quesiton 44F. Variable s holds the file content, fill in the blank on line 10 to read the file content into variable s
Question 44G. Fill in the blank on line 14 to open the pick file in binary write mode