Python: Quiz

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

(nhấn nút 'Result' để biết kết quả)

Q1. When Python is running in the interactive mode and displaying the chevron prompt (>>>) - what question is Python asking you?
What is the next machine language instruction to run?
What is your favourite color?
What Python statement would you like me to run?
What Python script would you like me to run?

Q2. What will the following program print out:
>>> x = 15
>>> x = x + 5
>>> print(x)
20
5
15
"print x"
x + 5

Q3. Python scripts (files) have names that end with:
.png
.doc
.exe
.py

Q4. Which of these words are reserved words in Python ?
concat
break
todo
if
make

Q5. What is the proper way to say “good-bye” to Python?
#EXIT
// stop
while
quit()

Q6. Which of the parts of a computer actually executes the program instructions?
Input/Output Devices
Secondary Memory
Main Memory
Central Processing Unit

Q7. What is "code" in the context of this course?
A set of rules that govern the style of programs
A sequence of instructions in a programming language
A way to encrypt data during World War II
A password we use to unlock Python features

Q8. A USB memory stick is an example of which of the following components of computer architecture?
Secondary Memory
Output Device
Main Memory
Central Processing Unit

Q9. What is the best way to think about a "Syntax Error" while programming?
The computer is overheating and just wants you to stop to let it cool down
The computer did not understand the statement that you entered
The computer has used GPS to find your location and hates everyone from your town
The computer needs to have its software upgraded

Q10. Which of the following is not one of the programming patterns?
Random steps
Conditional Steps
Sequential Steps
Repeated Steps

Q11. In the following code:
  print(98.6)
What is "98.6"?
An iteration / loop statement
A variable
A conditional statement
A constant

Q12. In the following code:
  x = 42
What is "x"?
A Central Processing Unit
A constant
A variable
A function

Q13. Which of the following is a bad Python variable name?
spam.23
spam_23
Spam
spam23

Q14. Which of the following is not a Python reserved word?
speed
else
for
if

Q15. Assume the variable x has been initialized to an integer value (e.g., x = 3). What does the following statement do?
x = x + 2
This would fail as it is a syntax error
Retrieve the current value for x, add two to it, and put the sum back into x
Exit the program
Increase the speed of the program by a factor of 2

Q16. Which of the following elements of a mathematical expression in Python is evaluated first?
Addition +
Subtraction -
Parentheses ( )
Multiplication *

Q17. What is the value of the following expression
42 % 10
Hint - the "%" is the remainder operator
420
1042
10
2

Q18. What will be the value of x after the following statement executes:
x = 1 + 2 * 3 - 8 / 4
15
5.0
3.0
4

Q19. What will be the value of x when the following statement is executed:
x = int(98.6)
100
98
99
6

Q20. What does the Python input() function do?
Pause the program and read data from the user
Connect to the network and retrieve a web page.
Read the memory of the running program
Take a screen shot from an area of the screen

Q21. What do we do to a Python statement that is immediately after an if statement to indicate that the statement is to be executed only when the if statement is true?
Underline all of the conditional code
Indent the line below the if statement
Begin the statement with a curly brace {
Start the statement with a "#" character

Q22. Which of these operators is not a comparison / logical operator?
==
>=
>
=
!=

Q23. What is true about the following code segment:
if x == 5 :
  print('Is 5')
  print('Is Still 5')
  print('Third 5')
Depending on the value of x, either all three of the print statements will execute or none of the statements will execute
The string 'Is 5' will always print out regardless of the value for x.
The string 'Is 5' will never print out regardless of the value for x.
Only two of the three print statements will print out if the value of x is less than zero.

Q24. When you have multiple lines in an if block, how do you indicate the end of the if block?
You use a curly brace { after the last line of the if block
You de-indent the next line past the if block to the same level of indent as the original Qif statement
You omit the semicolon ; on the last line of the if block
You put the colon : character on a line by itself to indicate we are done with the if block

Q25. You look at the following text:
if x == 6 :
  print('Is 6')
  print('Is Still 6')
  print('Third 6')
It looks perfect but Python is giving you an 'Indentation Error' on the second print statement. What is the most likely reason?
You have mixed tabs and spaces in the file
In order to make humans feel inadequate, Python randomly emits 'Indentation Errors' on perfectly good code - after about an hour the error will just go away without any changes to your program
Python has reached its limit on the largest Python program that can be run
Python thinks 'Still' is a mis-spelled word in the string

Q26. What is the Python reserved word that we use in two-way if tests to indicate the block of code that is to be executed if the logical test is false?
except
else
iterate
break

Q27. What will the following code print out?
x = 0
if x < 2 :
  print('Small')
elif x < 10 :
  print('Medium')
else :
  print('LARGE')
print('All done')
Medium
  All done
Small
Small
  All done
Small
  Medium
  LARGE
  All done

Q28. For the following code:
if x < 2 :
  print('Below 2')
elif x >= 2 :
    print('Two or more')
else :
  print('Something else')
What value of 'x' will cause 'Something else' to print out?
This code will never print 'Something else' regardless of the value for 'x'
x = -22
x = -2.0
x = 2.0

Q29. In the following code (numbers added) - which will be the last line to execute successfully?
(1) astr = 'Hello Bob'
(2) istr = int(astr)
(3) print('First', istr)
(4) astr = '123'
(5) istr = int(astr)
(6) print('Second', istr)
1
2
5
4

Q30. For the following code:
astr = 'Hello Bob'
istr = 0
try:
  istr = int(astr)
except:
  istr = -1
What will the value be for Qistr after this code executes?
9 (the number of characters in 'Hello Bob')
It depends on the position in the collating sequence for the letter 'H'
-1
false

Q31. Which Python keyword indicates the start of a function definition?
return
def
continue
sweet

Q32. In Python, how do you indicate the end of the block of code that makes up the function?
You put the colon character (:) in the first column of a line
You add a line that has at least 10 dashes
You add the matching curly brace that was used to start the function }
You de-indent a line of code to the same indent level as the def keyword

Q33. In Python what is the input() feature best described as?
A data structure that can hold multiple values using strings as keys
A built-in function
A reserved word
A user-defined function

Q34. What does the following code print out?
def thing():
  print('Hello') 

print('There')
thing
There
def
  thing
thing
  Hello
  There

Q35. In the following Python code, which of the following is an "argument" to a function?
x = 'banana'
y = max(x)
z = y * 2
x
max
'banana'
y

Q36. What will the following Python code print out?
def func(x) :
  print(x)

func(10)
func(20)
10
  20
x
  20
x
  10
  x
  20
func
  func

Q37. Which line of the following Python program will never execute?
def stuff():
  print('Hello')
  return
  print('World')

stuff()
print('Hello')
print('World')
def stuff():
return
stuff()

Q38. What will the following Python program print out?
def greet(lang):
  if lang == 'es':
    return 'Hola'
  elif lang == 'fr':
    return 'Bonjour'
  else:
    return 'Hello'

print(greet('fr'),'Michael')
Bonjour Michael
def
  Hola
  Bonjour
  Hello
  Michael
Hola Michael
Hola
  Bonjour
  Hello
  Michael

Q39. What does the following Python code print out? (Note that this is a bit of a trick question and the code has what many would consider to be a flaw/bug - so read carefully).
def addtwo(a, b):
  added = a + b
  return a

x = addtwo(2, 7)
print(x)
14
7
9
2

Q40. What is the most important benefit of writing your own functions?
Following the rule that whenever a program is more than 10 lines you must use a function
Avoiding writing the same non-trivial code more than once in your program
Following the rule that no function can have more than 10 statements in it
To avoid having more than 10 lines of sequential code without an indent or de-indent

Q41. What is wrong with this Python loop:
n = 5
while n > 0 :
  print(n)
print('All done')
This loop will run forever
The print('All done') statement should be indented four spaces
There should be no colon on the while statement
while is not a Python reserved word

Q42. What does the break statement do?
Jumps to the "top" of the loop and starts the next iteration
Resets the iteration variable to its initial value
Exits the currently executing loop
Exits the program

Q43. What does the continue statement do?
Exits the currently executing loop
Resets the iteration variable to its initial value
Exits the program
Jumps to the "top" of the loop and starts the next iteration

Q44. What does the following Python program print out?
tot = 0 
for i in [5, 4, 3, 2, 1] :
  tot = tot + 1
print(tot)
0
15
5
10

Q45. What is the iteration variable in the following Python code:
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
   print('Happy New Year:',  friend)
print('Done!')
friend
Glenn
Sally
friends

Q46. What is a good description of the following bit of Python code?
zork = 0
for thing in [9, 41, 12, 3, 74, 15] :
  zork = zork + thing
print('After', zork)
Find the smallest item in a list
Find the largest item in a list
Count all of the elements in a list
Sum all the elements of a list

Q47. What will the following code print out?
smallest_so_far = -1
for the_num in [9, 41, 12, 3, 74, 15] :
  if the_num < smallest_so_far :
    smallest_so_far = the_num
print(smallest_so_far)
Hint: This is a trick question and most would say this code has a bug - so read carefully
-1
74
42
3

Q48. What is a good statement to describe the is operator as used in the following if statement:
if smallest is None :
  smallest = value
Looks up 'None' in the Qsmallest variable if it is a string
The if statement is a syntax error
Is true if the Qsmallest variable has a value of -1
matches both type and value

Q49. Which reserved word indicates the start of an "indefinite" loop in Python?
def
for
indef
while
break

Q50. How many times will the body of the following loop be executed?
n = 0
while n > 0 :
  print('Lather')
  print('Rinse')
print('Dry off!')
5
1
0
This is an infinite loop

Q51. What does the following Python Program print out?
str1 = "Hello"
str2 = 'there'
bob = str1 + str2
print(bob)
Hello
  there
Hello
Hello there
Hellothere

Q52. What does the following Python program print out?
x = '40'
y = int(x) + 2
print(y)
x2
int402
42
402

Q53. How would you use the index operator [] to print out the letter q from the following string?
x = 'From marquard@uct.ac.za'
print(x[8])
print(x[q])
print(x[-1])
print(x[7])
print(x[9])

Q54. How would you use string slicing [:] to print out 'uct' from the following string?
x = 'From marquard@uct.ac.za'
print(x[15:3])
print(x[15:18])
print(x[14/17])
print(x[14:3])
print(x[14:17])
print(x[14+17])

Q55. What is the iteration variable in the following Python code?
for letter in 'banana' :
  print(letter)
for
in
print
letter
'banana'

Q56. What does the following Python code print out?
print(len('banana')*7)
0
bananabananabananabananabananabananabanana
42
banana7

Q57. How would you print out the following variable in all upper case in Python?
greet = 'Hello Bob'
print(uc($greet));
print(greet.upper())
puts(greet.ucase);
console.log(greet.toUpperCase());

Q58. Which of the following is not a valid string method in Python?
shout()
split()
join()
startswith()

Q59. What will the following Python code print out?
data = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
pos = data.find('.')
print(data[pos:pos+3])
uct
mar
09:14
.ma

Q60. Which of the following string methods removes whitespace from both the beginning and end of a string?
rltrim()
strip()
wsrem()
strtrunc()

Q61. Where are files stored?
Motherboard
Main Memory
Secondary memory
Central Processor

Q62. What is stored in a "file handle" that is returned from a successful open() call?
The handle has a list of all of the files in a particular folder on the hard drive
The handle contains the first 10 lines of a file
All the data from the file is read into memory and stored in the handle
The handle is a connection to the file's data

Q63. What do we use the second parameter of the open() call to indicate?
Whether we want to read data from the file or write data to the file
The list of folders to be searched to find the file we want to open
How large we expect the file to be
What disk drive the file is stored on

Q64. What Python function would you use if you wanted to prompt the user for a file name to open?
read()
cin
input()
file_input()

Q65. What is the purpose of the newline character in text files?
It enables random movement throughout the file
It indicates the end of one line of text and the beginning of another line of text
It adds a new network connection to retrieve files from the network
It allows us to open more than one files and read them in a synchronized manner

Q66. If we open a file as follows:
  xfile = open('mbox.txt')
What statement would we use to read the file one line at a time?
for line in xfile:
while ((line = xfile.readLine()) != null) {
while (<xfile>) {
while line = xfile.gets

Q67. What is the purpose of the following Python code?
fhand = open('mbox.txt')
x = 0
for line in fhand:
  x = x + 1
print(x)
Count the lines in the file 'mbox.txt'
Remove the leading and trailing spaces from each line in mbox.txt
Convert the lines in mbox.txt to upper case
Reverse the order of the lines in mbox.txt

Q68. If you write a Python program to read a text file and you see extra blank lines in the output that are not present in the file input as shown below, what Python string function will likely solve the problem?
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
...
rstrip()
split()
trim()
ljust()

Q69. The following code sequence fails with a traceback when the user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was entered?
fname = input('Enter the file name: ')
fhand = open(fname)
signal handlers
setjmp / longjmp
try / except
begin / rescue / end

Q70. What does the following Python code do?
fhand = open('mbox-short.txt')
inp = fhand.read()
Reads the entire file into the variable inp as a string
Prompts the user for a file name
Turns the text in the file into a graphic image like a PNG or JPG
Checks to see if the file exists and can be written

Q71. How are "collection" variables different from normal variables?
Collection variables pull multiple network documents together
Collection variables can store multiple values in a single variable
Collection variables merge streams of output into a single stream
Collection variables can only store a single value

Q72. What are the Python keywords used to construct a loop to iterate through a list?
foreach / in
try / except
def / return
for / in

Q73. For the following list, how would you print out 'Sally'?
friends = [ 'Joseph', 'Glenn', 'Sally' ]
print(friends['Sally'])
print(friends[3])
print(friends[2])
print(friends[2:1])

Q74. What would the following Python code print out?
fruit = 'Banana'
fruit[0] = 'b'
print(fruit)
[0]
Banana
B
b
Nothing would print - the program fails with a traceback error
banana

Q75. Which of the following Python statements would print out the length of a list stored in the variable data?
print(data.Len)
print(length(data))
print(data.length())
print(data.length)
print(strlen(data))
print(len(data))

Q76. What type of data is produced when you call the range() function?
x = list(range(5))
A list of integers
A boolean (true/false) value
A list of words
A string
A list of characters

Q77. What does the following Python code print out?
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(len(c))
[1, 2, 3]
21
[1, 2, 3, 4, 5, 6]
6
15
[4, 5, 6]

Q78. Which of the following slicing operations will produce the list [12, 3]?
t = [9, 41, 12, 3, 74, 15]
t[1:3]
t[12:3]
t[2:2]
t[:]
t[2:4]

Q79. What list method adds a new item to the end of an existing list?
add()
push()
forward()
index()
append()
pop()

Q80. What will the following Python code print out?
friends = [ 'Joseph', 'Glenn', 'Sally' ]
friends.sort()
print(friends[0])
Glenn
friends
Joseph
Sally

Q81. How are Python dictionaries different from Python lists?
Python lists are indexed using integers and dictionaries can use strings as indexes
Python lists can store strings and dictionaries can only store words
Python dictionaries are a collection and lists are not a collection
Python lists store multiple values and dictionaries store a single value

Q82. What is a term commonly used to describe the Python dictionary feature in other programming languages?
Sequences
Lambdas
Associative arrays
Closures

Q83. What would the following Python code print out?
stuff = dict()
print(stuff['candy'])
candy
The program would fail with a traceback
-1
0

Q84. What would the following Python code print out?
stuff = dict()
print(stuff.get('candy',-1))
0
The program would fail with a traceback
-1
'candy'

Q85. (T/F) When you add items to a dictionary they remain in the order in which you added them.
False
True

Q86. What is a common use of Python dictionaries in a program?
Building a histogram counting the occurrences of various strings in a file
Computing an average of a set of numbers
Sorting a list of names into alphabetical order
Splitting a line of input into words using a space as a delimiter

Q87. Which of the following lines of Python is equivalent to the following sequence of statements assuming that counts is a dictionary?
if key in counts:
  counts[key] = counts[key] + 1
else:
  counts[key] = 1
counts[key] = counts.get(key,0) + 1
counts[key] = (key in counts) + 1
counts[key] = (counts[key] * 1) + 1
counts[key] = key + 1
counts[key] = counts.get(key,-1) + 1

Q88. In the following Python, what does the for loop iterate through?
x = dict()
...
for y in x :
  ...
It loops through the integers in the range from zero through the length of the dictionary
It loops through the keys in the dictionary
It loops through the values in the dictionary
It loops through all of the dictionaries in the program

Q89. Which method in a dictionary object gives you a list of the values in the dictionary?
items()
all()
keys()
values()
each()

Q90. What is the purpose of the second parameter of the get() method for Python dictionaries?
The value to retrieve
An alternate key to use if the first key cannot be found
The key to retrieve
To provide a default value if the key is not found

Q91. What is the difference between a Python tuple and Python list?
Lists maintain the order of the items and tuples do not maintain order
Tuples can be expanded after they are created and lists cannot
Lists are mutable and tuples are not mutable
Lists are indexed by integers and tuples are indexed by strings

Q92. Which of the following methods work both in Python lists and Python tuples?
pop()
reverse()
sort()
index()
append()

Q93. What will end up in the variable y after this code is executed?
x, y = 3, 4
3
A two item tuple
4
A dictionary with the key 3 mapped to the value 4
A two item list

Q94. In the following Python code, what will end up in the variable y?
x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
y = x.items()
A list of integers
A list of strings
A list of tuples
A tuple with three integers

Q95. Which of the following tuples is greater than x in the following Python sequence?
x = (5, 1, 3)
if ??? > x :
  ...
(5, 0, 300)
(6, 0, 0)
(0, 1000, 2000)
(4, 100, 200)

Q96. What does the following Python code accomplish, assuming the c is a non-empty dictionary?
tmp = list()
for k, v in c.items() :
  tmp.append( (v, k) )
It computes the largest of all of the values in the dictionary
It computes the average of all of the values in the dictionary
It creates a list of tuples where each tuple is a value, key pair
It sorts the dictionary based on its key values

Q97. If the variable data is a Python list, how do we sort it in reverse order?
data.sort(reverse=True)
data.sort.reverse()
data = sortrev(data)
data = data.sort(-1)

Q98. Using the following tuple, how would you print 'Wed'?
days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
print(days[1])
print(days(2))
print[days(2)]
print(days[2])
print(days{2})
print(days.get(1,-1))

Q99. In the following Python loop, why are there two iteration variables (k and v)?
c = {'a':10, 'b':1, 'c':22}
for k, v in c.items() :
  ...
Because the items() method in dictionaries returns a list of tuples
Because there are two items in the dictionary
Because for each item we want the previous and current key
Because the keys for the dictionary are strings

Q100. Given that Python lists and Python tuples are quite similar - when might you prefer to use a tuple over a list?
For a list of items that will be extended as new items are found
For a temporary variable that you will use and discard without modifying
For a list of items you intend to sort in place
For a list of items that want to use strings as key values instead of integers

Q101. Which of the following statement is true about function?
Functions do not provide better modularity for your application
Functions are reusable pieces of programs
You can not also create your own functions
None of the Above

Q102. Which of the following is a features of DocString?
All functions should have a docstring
Provide a convenient way of associating documentation with Python modules, functions, classes, and methods
Docstrings can be accessed by the __doc__ attribute on objects
All of the Above

Q103. Which are the advantages of functions in python?
Reducing duplication of code
Decomposing complex problems into simpler pieces
Reuse of code
All of the Above

Q104. Where is function defined?
Class
Module
Inside another function
All of the Above

Q105. Which of the following is the use of id() function in python?
Every object does not have a unique id
Id returns the identity of the object
All of the Above
None of the Above

Q106. Python supports the creation of anonymous functions at runtime, using a construct called?
anonymous
Lambda
pi
None of the Above

Q107. What is the type of each element in sys.argv?
string
tuple
list
set

Q108. What is the length of sys.argv?
number of arguments + 1
number of arguments 1 1
number of arguments
None of the Above

Q109. How are keyword arguments specified in the function heading?
one underscore followed by a valid identifier
two underscores followed by a valid identifier
two stars followed by a valid identifier
one star followed by a valid identifier

Q110. What is output produced by following program?
import math
print(math.floor(3.4))
3
4.0
4
3.0

Q111. What is output produced by following program?
import math
print(math.copysign(3, -1))
-3.0
-3
1.0
1

Q112. Is the function abs() is same as math.fabs()?
never
always
sometimes
None of the Above

Q113. What is the value returned by math.fact(6)?
6
720
[1, 2, 3, 6]
error

Q114. What is the result of math.factorial(5.0000000000000001)?
24
25
120
Error saying ValueError: factorial() only accepts integral values

Q115. What is equal to math.floor(0o10) in Python?
0
8
9
10

Q116. What does the function math.frexp(x) return?
a list containing of the exponent of x
a tuple containing of the mantissa of x
a list containing of the mantissa and the exponent of x
a tuple containing of the mantissa and the exponent of x

Q117. What is the result of math.fsum([.1 for i in range(20)])?
2.0000000000000004
2
20
2.0

Q118. What is the result of (2 ** 0.5)**2
2
2.0000000000000004
4.0
2.0

Q119. What is returned by math.isfinite(float('inf'))?
False
True
error
None

Q120. What is x if x = math.isfinite(float('0.0'))?
False
True
error
None

Q121. What is the value of x if x = math.ldexp(0.5, 1)?
0.5
1
2.0
None of the Above

Q122. What is returned by math.modf(1.0)?
(0.5, 1.0)
(0.5, 1)
(1.0, 0.0)
(0.0, 1.0)

Q123. What does os.name contain?
the address of the module os
the name of the operating system dependent module imported
error, it should have been os.name()
None of the Above

Q124. What does print(os.geteuid()) print?
the user id of the current process
the group id of the current process
both the group id and the user of the current process
None of the Above

Q125. What does os.fchmod(fd, mode) do?
change permission bits of the directory
change permission bits of the file
change permission bits of either the file or the directory
None of the Above

Q126. Which of the following functions can be used to read data from a file using a file descriptor?
os.scan()
os.quick_read()
os.read()
os.reader()

Q127. Which of the following returns a string that represents the present working directory?
os.pwd()
os.getpwd()
os.cwd()
os.getcwd()

Q128. What does os.link() do?
create a soft link
create a symbolic link
create a hard link
None of the Above

Q129. Which of the following can be used to create a directory?
os.make_dir()
os.create_dir()
os.creat_dir()
os.mkdir()

Q130. Which of the following can be used to create a symbolic link?
os.ln()
os.symblin()
os.symb_link()
os.symlink()

(Ghi chú: Phần câu hỏi Qi có màu Green thể hiện đáp án đúng)

(Ghi chú: Phần câu hỏi Qi có màu Green thể hiện đáp án đúng)
» Tiếp: Tính tổng các số từ 1 đến N
« Trước: Bài tập phần thuật toán
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!