Python Quiz Questions
Table of Contents:
- 1. Who created Python?
- 2. In Python strings, Unicode strings, lists, tuples, buffers, and xrange objects are called:
- 3. What is the output?
- 4. What is not a tuple?
- 5. In Python when you assign a value to a variable this would set the variable type?
- 6. In Python the function
print()
is: - 7. In Python which keyword is used to define a function?
- 8. What is used to define a block of code in Python?
- 9. Which of the following is correct about the comments?
- 10. What is the output of the following code?
- 11. What is used to take the keyboard input in Python?
- 12. What is the output when you print variable numbers?
- 13. What is the output of the following code?
- 14. In Python
type(false)
will return: - 15. Is there a
do while
loop in Python? - 16. What is the output of the following code?
- 17. A variable must assign a value before it can be used.
- 18. Can a Python list contain another list?
- 19. In Python indexing starts from:
- 20. To return the ASCII code of the character in Python you need?
- 21. What will be the result of this function?
- 22. Is there any difference in the output from these 2 lines:
- 23. In Python we use try and catch for exception handling?
- 24. Find the intruder?
- 25. What will be the output?
- 26. A string tenStr has 10 characters. What will the next code return?
- 27. Python does not have separate data types for characters - they are represented as a single character string.
- 28. What will the
id()
function return? - 29. Strings in Python are continuous series of characters delimited by single or double quotes.
- 30. Are string objects mutable?
- 31. Let
a = [1, 2, 3, 4, 5]
then which of the following is correct? - 32. What is
n
? - 33. To install Python on Windows you will typically need:
- 34. To get help on any built-in Python function you can call?
- 35. To start a Python interpreter in Windows you type?
- 36. Most Linux distributions have Python installed by default?
- 37. Can you append a string to a tuple like this?
- 38. Python can automatically convert a number from one type to another if it needs to?
- 39. What is not a standard Python data type?
- 40. What is
type(5.0)
? - 41. Find the intruder?
- 42. Complex numbers are not supported in Python by default?
- 43. Is this OK to write in Python?
- 44. Select mutable type?
- 45. In Python which is the correct method to import a module?
- 46. A function is a block of code that performs a specific task.
- 47. What is the output of the following code?
- 48. What is the output of the following code?
- 49. What is a recursive function?
- 50. What is the output of the following program?
- 51. Suppose a tuple test contains 5 elements. How can you set the 3rd element of the tuple to ‘Python’?
- 52. What is the output of the following program?
- 53. What is used to concatenate two strings in Python?
- 54. What is the output?
- 55. Which of the following statements is true?
- 56. What is the output of the following program?
- 57. How can you change:
- 58. Which operator is used in Python to import modules from packages?
- 59. Opening a file in ‘a’ mode opens a file for
- 60. What does the following code do?
- 61. What will happen if you try to open a file that is not present?
- 62. What does the following code do?
- 63. What is true?
- 64. For the following code, what is true?
- 65. Suppose you need to print the
pi
constant defined in themath
module. Which of the following code can do this task? - 66. If return statement is not used inside the function, the function will return:
- 67. Suppose a list with name test, contains 10 elements. You can get the 5th element from the test list using:
- 68. What does the
__init__()
function do in Python? - 69. If your class is derived from two different classes this is called:
- 70. What does the following code do?
- 71. What are the method(s) that an iterator object must implement?
- 72. If a function contains at least one yield statement, it becomes?
1. Who created Python?
☐ James Gosling
☑ Guido Van Rossum
☐ Dennis Ritchie
☐ Tom Cruise
Guido Van Rossum is a Dutch programmer best known as the author of the Python programming language.
2. In Python strings, Unicode strings, lists, tuples, buffers, and xrange objects are called:
☐ dictionary
☑ sequences
☐ set
☐ Something else
They are called sequences. Sequences are different from dictionaries, and sets.
Dictionary is an associative array, where keys are mapped to values. Inside sequences there are no associations of keys and values.
Sequence is different from set, because set cannot have duplicate elements while sequence can.
3. What is the output?
'abc'=="abc"
☑ True ☐ False
Strings would be a sequence of characters only.
It is irrelevant whether single or double quotes are used when creating strings. This is why 'abc'=="abc"
will return True
.
4. What is not a tuple?
☐ ()
☐ (1,2)
☐ (3,)
☑ (4)
Tuples are sequences, just like lists. However, tuples use parentheses ()
, whereas lists use square brackets []
.
In this case ()
is an empty tuple, (1,2)
is a tuple with two elements (3,)
is a tuple with a single element, but (4)
is int.
$ x = (4)
$ print(type(x))
<class 'int'>
$ x = (4,)
$ print(type(x))
<class 'tuple'>`
Note that a single element tuple must have the ending comma, else it would evaluate differently.
5. In Python when you assign a value to a variable this would set the variable type?
☑ YES ☐ NO
Unlike more rigid languages, Python will change the variable type for a variable on assignments.
6. In Python the function print()
is:
☐ user-defined
☑ built-in
Python has functions built into it that are always available. The print()
function is one of them.
Here is the list of built-in functions:
abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object () sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int () open() str() bool () exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float () iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set()
7. In Python which keyword is used to define a function?
☐ function
☑ def
☐ try
☐ import
A function in Python is defined by a def
statement. Here is the example:
def hiFunction(person):
print("Hi " + person + ".")
hiFunction('Emily')
Out:
Hi Emily.
8. What is used to define a block of code in Python?
☐ Curly braces
☐ Parenthesis
☑ Indentation
☐ Quotation
To indicate a block of code in Python, you must indent each line of the block by the same amount of space.
The amount of indentation matters: A missing or extra space in a Python block could cause an error or unexpected behavior.
Statements within the same block of code need to be indented at the same level.
9. Which of the following is correct about the comments?
☐ They help us understand the program better
☐ Python Interpreter ignores comments
☐ Multiline comments start either with '''
or """
☑ All options are correct
Comments in Python start with the hash character, #
and extend to the end of the physical line.
In certain cases, multiline comments are a better option. Multiline comments start and end with '''
or """
.
10. What is the output of the following code?
print(1, 2, 3, 4, sep='*')
☐ 1 2 3 4
☐ 1234
☑ 1*2*3*4
☐ 24
The function print
can take a parameter sep
. That would insert the sep
between values. Default separator is a space " "
.
11. What is used to take the keyboard input in Python?
☐ scanf()
☑ input()
Python provides the function input()
. That function has an optional parameter, which is the prompt string.
On input()
the program flow stops while the user is providing the input. When the user hits the return key the program flow continues.
Here is the example:
name = input("What's your name? ")
# program flow stops here
print("Hello " + name + "!")
12. What is the output when you print variable numbers?
numbers = [2, 3, 4]
☐ 2, 3, 4
☐ 2 3 4
☑ [2, 3, 4]
☐ [2 3 4]
The function print()
will print whatever we provide.
In this case we provided the variable which is simply a list. The list will be in the output including the square brackets []
.
13. What is the output of the following code?
print(3 >= 3)
☐ 3 >= 3
☑ True
☐ False
☐ None
In this example print(3 >= 3)
will return True
, because the printing function will evaluate the expression 3 >= 3
first.
14. In Python type(false)
will return:
☐ <class ‘bool’>
☑ something else
Note that Python is case sensitive language, and the False
is not the same as false
.
If we check, type(False)
would return <class 'bool'>
and type(false)
would lead to NameError:
There is no such keyword 'false'.
15. Is there a do while
loop in Python?
☐ YES ☑ NO
There are while
and for
loops in Python, but there is no do while
loop.
16. What is the output of the following code?
print(type([1,2]))
☐ <class ‘tuple’>
☐ <class ‘set’>
☐ <class ‘int’>
☑ <class ‘list’>
Lists are formed by placing a comma-separated list of expressions in square brackets []
.
17. A variable must assign a value before it can be used.
☑ YES ☐ NO
In Python unassigned variables are simply not allowed.
18. Can a Python list contain another list?
☑ True ☐ False
This is of course possible. The smallest example would be like this:
list = [[]]
19. In Python indexing starts from:
☑ 0 ☐ 1
In Python, like in almost any programming language indexing starts from 0. This is true not only for strings, but for any sequence object type.
20. To return the ASCII code of the character in Python you need?
☐ chr()
☑ ord()
The function ord()
is a built-in that returns the ASCII character for the character we ask.
$ ord('a')
97
The chr()
will do exactly the opposite.
$ chr(97)
'a'
21. What will be the result of this function?
len("Hello World")
☐ 10 ☑ 11
Since the string “Hello World” has exactly 11 characters the output is 11.
22. Is there any difference in the output from these 2 lines:
print("my string", end="\n")
print("my string")
☐ YES ☑ NO
By default print()
function prints the string with a newline at the end. We can change this behavior using the end argument.
There will be no difference.
23. In Python we use try and catch for exception handling?
☐ YES ☑ NO
Exception handling enables you to handle errors gracefully and do something meaningful about it. Like display a message to the user if the intended file is not found. Python handles exceptions using:
try:
# try block
except <ExceptionType1>:
# handler1
except <ExceptionTypeN>:
# handlerN
except:
# handlerAny
else:
# process_else
finally:
# process_finally
As you can see in the try block you need to write the code that might throw an exception. When an exception occurs code in the try block is skipped.
If there exists a matching exception type then the handler is executed for that exception, else handlerAny is executed.
If there is no exception, process_else is executed.
The process_finally is executed in any case.
24. Find the intruder?
☐ ArithmeticError
☑ GoldError
☐ RuntimeError
☐ SyntaxError
There are some different error types that may occur in Python, but not the GoldError.
25. What will be the output?
s = "Wellcome"
s[1:3]
☐ We
☑ el
☐ Wel
☐ ell
We used the string slicing in here.
The range slice s[start:end]
is the string beginning at start and extending up to but not including end.
Indexing in Python starts from 0 so the first letter is the e
and the last would be the first l
, because the other l
would be omitted.
26. A string tenStr has 10 characters. What will the next code return?
tenStr[1:1]
☐ It depends on a string
☑ ’‘
☐ second character of the string
☐ first character of the string
The return will always be the empty string.
The slice tenStr[1:1]
means we will try to get the second character from the string, but since we must not include the end of the slice the result will be the empty string.
27. Python does not have separate data types for characters - they are represented as a single character string.
☑ True ☐ False
It may be called a great feature of Python since this greatly simplifies things.
28. What will the id()
function return?
☑ memory address
☐ object identifier
Python uses the object’s memory address to provide the identity.
Since every object in Python is stored somewhere in memory, we can use id()
to get that memory address.
29. Strings in Python are continuous series of characters delimited by single or double quotes.
☑ True ☐ False
Yes, both single or double quotes are good. However, this would be wrong:
s='string"
.
Either s='string'
or s="string"
is good.
30. Are string objects mutable?
☐ YES ☑ NO
Strings are immutable objects. You can check this with the id()
function.
If we try to update the value of the string object the new string object will be created. We know this by examining the memory address.
For example:
$ s='str'
$ id(s)
50842944
$ s=s+'ing'
$ id(s)
52112389
31. Let a = [1, 2, 3, 4, 5]
then which of the following is correct?
☐ a[:] => [1,2,3,4]
☐ a[0:] => [2,3,4,5]
☑ a[:100] => [1,2,3,4,5]
☐ a[-1:] => [1,2]
There is logic behind the string range slicing for the first and for the second argument.
[1 2 3 4 5]
0 1 2 3 4 # first argument index
-5 -4 -3 -2 -1 # second argument index
If we omit the arguments [:] we will get the full list so a[:] => [1,2,3,4] is not correct - it should take the whole list.
The a[0:] => [2,3,4,5] is also not correct because a[0:] is equal to a[:].
a[:100] => [1,2,3,4,5] would be the correct answer.
32. What is n
?
n = '5'
☐ int
☑ string
☐ tuple
☐ operator
Use Python interpreter to type this:
$ n='5'
$ type(n)
Python will tell you the type of n
which is a string:
<class 'str'>
33. To install Python on Windows you will typically need:
☑ Less than 5 minutes
☐ More than 5 minutes
Typically you will search for the latest Python version, download it and start the installation process which is very quick.
34. To get help on any built-in Python function you can call?
☑ help()
☐ doc()
Calling help()
at the Python prompt starts an interactive help session.
Calling help(thing)
prints help for the python object ‘thing’.
35. To start a Python interpreter in Windows you type?
☑ Either py or python
☐ Py
☐ Python
If a Python installation sets the PATH variable in Windows either py
, python
, Py
, Python
should work. Windows is case insensitive.
Once you have the interpreter running you will get the prompt like this:
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
36. Most Linux distributions have Python installed by default?
☑ True ☐ False
Red Hat Enterprise Linux and its close relatives (Fedora, CentOS, Scientific Linux, Oracle Linux…) will always have Python installed since the installer and many core tools are written in Python.
Ubuntu has had Python installed by default since at least version 8.04
37. Can you append a string to a tuple like this?
a = ('1',)
b = '2'
c = a + b
☐ YES ☑ NO
This will not work. The output from the interpreter would be:
Can only concatenate tuple (not "str") to tuple.
This means you can only add tuple to tuple. The next would be possible.
a = ('1',)
b = ('2',)
c = a + b
38. Python can automatically convert a number from one type to another if it needs to?
☑ YES ☐ NO
Data conversion in Python can happen in two ways: either you tell the compiler to convert a data type to some other type explicitly, or the compiler understands this by itself and does it for you.
In the first case, you are performing an explicit data type conversion:
$ a = 3.14
$ a=int(a)
$ print(type(a))
<class 'int'>`
The example of the implicit conversion would be:
$ a = 3
$ a=a+.1
$ print(type(a))
<class 'float'>
39. What is not a standard Python data type?
☑ Class
☐ String
☐ List
☐ Dictionary
Most standard data types would be all the numbers (int, long, float, complex) and of course strings, list, tuple, dictionary.
Class is not a data type. There is also the ‘class’ keyword in Python used to create a new class definition.
40. What is type(5.0)
?
☐ int ☑ float
It will be float
because the notation 5.0
represents the float number. The type(5)
would return int
.
41. Find the intruder?
☐ int
☐ float
☑ tuple
☐ complex
Here int, float, and complex are Python numbers, while tuple is a serial data type.
42. Complex numbers are not supported in Python by default?
☐ YES ☑ NO
No, complex numbers are supported in Python right out of the box. Here is what Python supports:
a = 10 (int)
a = 345L (long)
a = 45.67 (float)
a = -1+3.14j (complex)
43. Is this OK to write in Python?
a=-.0+.1j+1-.0-j
☑ YES ☐ NO
Yes, the following is an expression that would eval to a complex number:
(1-0.9j)
44. Select mutable type?
☑ list ☐ tuple
Mutable means the elements in a list we are able to update after the assignment. On the other hand, tuples are not mutable. You cannot update tuple elements once you assign a tuple.
45. In Python which is the correct method to import a module?
☐ include math
☑ import math
☐ #include<math.h>
☐ using math
Different languages have different syntax. Python way to load a module would be like:
import math
.
The same keyword as in Java programming language.
46. A function is a block of code that performs a specific task.
☑ True ☐ False
Functions provide better modularity for your application and a way to reuse code.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
47. What is the output of the following code?
def printSingleTextLine(text):
print(text, 'is awesome.')
printSingleTextLine('Python')
☐ Python
☑ Python is awesome.
☐ Pythonis awesome.
☐ text is awesome.
The actual result of this would be:
Python is awesome.
Note here the default separator for the print()
function with multiple arguments is a space character.
48. What is the output of the following code?
def greetPerson(*name):
print('Hello', name)
greetPerson('Mam', 'Dad')
☐ Hello Mam
☐ Hello Mam, Dad
☑ Hello (‘Mam’, ‘Dad’)
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
When an asterisk (*) is placed before the variable name which will hold the values of all non mentioned arguments. This tuple remains empty if no additional arguments are specified during the function call.
49. What is a recursive function?
☐ There is no recursive functions in Python
☑ A function that calls itself
Python supports recursive functions.
For example, here is the sum function that will evaluate the sum of all the numbers lower or equal to n:
def sum(n):
if n == 1:
return 1
else:
return n + sum(n-1)
50. What is the output of the following program?
result = lambda x: x * x
print(result(5))
☐ lambda x: x*x
☐ 10
☑ 25
☐ 5*5
We used the anonymous or the lambda function. These functions are not declared in the standard way using the def:
keyword.
Lambda functions cannot contain commands or multiple expressions. They return just one value in the form of an expression.
51. Suppose a tuple test contains 5 elements. How can you set the 3rd element of the tuple to ‘Python’?
☐ test[2] = 'Python'
☐ test(2) = 'Python'
☐ test[3] = 'Python'
☑ Elements of tuple cannot be changed
Tuples are immutable. We cannot update them.
52. What is the output of the following program?
print((1, 2) + (3, 4))
☐ (1, 2) (3, 4)
☑ (1, 2, 3, 4)
We have created a tuple by concatenation of two tuples, not two strings.
53. What is used to concatenate two strings in Python?
☐ .
operator
☑ +
operator
☐ strcat()
function
☐ ^
operator
In order to merge two strings into a single object, we use the +
operator.
The newly created string is a completely new object, since strings are immutable.
54. What is the output?
print('cat'*3)
☐ cat3 ☑ catcatcat
The operator * on strings will multiply the strings for a number of times.
55. Which of the following statements is true?
☐ A set is an unordered collection of items
☐ Set elements are unique
☐ You can change elements of a set unlike tuple
☑ All are correct
The set is an unordered collection of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.
56. What is the output of the following program?
n = [x * x for x in range(4)]
print(n)
☐ [0, 1, 2, 3]
☑ [0, 1, 4, 9]
☐ [1, 4, 9, 16]
☐ [1, 2, 3, 4]
The range(4)
is the same as range(0, 4)
. For example:
$ for x in range(0, 4):
... print(x)
...
0
1
2
3
So the correct answer is [0, 1, 4, 9]
.
57. How can you change:
num = {'one': 1, 'two': 3}
into
num = {'one': 1, 'two': 2 }
☐ num[2] = 'two'
☐ num[1] = 'two'
☑ num['two'] = 2
☐ num['two'] = '2'
Only the num['two'] = 2
is correct since we update the dictionary element by using the key ‘two’ and we need to set the integer value 2.
58. Which operator is used in Python to import modules from packages?
☐ .
operator
☑ *
operator
☐ ->
symbol
☐ ,
operator
from my_package_name import *
is the way to import all the modules from the my_package_name package.
This allows using variables, classes, methods, … from the module without prefixing them with the module name.
59. Opening a file in ‘a’ mode opens a file for
☑ ☐ reading
☑ ☐ writing
☑ ☐ appending at the end of the file
☑ ☐ exclusive creation
Mode ‘a’ is short for the appending mode.
60. What does the following code do?
f = open('test.txt')
☐ Opens a file for both reading and writing
☑ Opens a file for reading only
☐ Opens a file for writing only
☐ Opens a file in god mode
In Python the default mode is to open a file for reading only. The file pointer is placed at the beginning of the file.
61. What will happen if you try to open a file that is not present?
☐ A new file will be created ☐ Nothing ☑ An exception is raised ☐ Something else
When we try to open a file, but a file is not present the exception FileNotFoundError
will be raised.
62. What does the following code do?
os.listdir()
☐ Prints the current working directory
☐ Prints all directories (not files) inside the given directory
☑ Prints all directories and files inside the given directory
☐ Makes a new directory
The method listdir()
returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.
import os
os.listdir('c:') # on Windows
os.listdir('/home') # on Linux or Mac
63. What is true?
☐ You cannot create custom exceptions in Python ☐ You can create a user-defined exception by deriving a class from Exception class ☑ You can create a user-defined exception by deriving a class from Error class ☐ None of the above
The standard way to create user-defined exceptions is to derive from the Exception class.
64. For the following code, what is true?
def printHello():
print("Hello")
a = printHello()
☑ printHello()
is a function and a
is a variable
☐ printHello()
and a
refer to the same object
Here the function and the variable are not pointing to the same object.
Instead type(a)
will be <class 'NoneType'>
and print(a)
will return None.
To assign a variable to the function we can write:
def printHello():
print('Hello')
a = printHello
Then a()
will return the ‘Hello’ string.
65. Suppose you need to print the pi
constant defined in the math
module. Which of the following code can do this task?
☐ print(math.pi)
☐ print(pi)
☑ from math import pi
; print(pi)
☐ from math import pi
;
☐ print(math.pi)
This would be two correct ways:
$ from math import pi
$ print(pi)
3.141592653589793
or
$ from math import *
$ print(pi)
3.141592653589793
66. If return statement is not used inside the function, the function will return:
☐ 0
☐ Null object
☑ None object
☐ Error! Functions in Python must have a return statement.
A return statement ends the execution of the function call and “returns” the result.
If there is no return statement, the special value None is returned.
67. Suppose a list with name test, contains 10 elements. You can get the 5th element from the test list using:
☐ test[5]
☑ test[4]
☐ test[‘5’]
☐ test[‘4’]
Because the list indexing starts from 0, the 5th element will be test[4].
68. What does the __init__()
function do in Python?
☐ Initializes the class for use
☑ This function is called when a new object is instantiated
☐ Initializes all the data attributes to zero when called
☐ Something else
The __init__
method represents a constructor in Python.
$ class Foo:
... pass
...
$ o1 = Foo()
When you call o1 = Foo()
Python should create an object for you.
Initializes the class for use is wrong because classes are definitions, they are not initialized.
Initializes all the data attributes to zero when called is also not true, because attributes may be initialized to non zero value.
This function is called when a new object is instantiated would be OK.
69. If your class is derived from two different classes this is called:
☐ Multilevel Inheritance
☑ Multiple Inheritance
☐ Hierarchical Inheritance
☐ Python Inheritance
In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
70. What does the following code do?
def a(b, c, d): pass
☐ defines a list and initializes it
☑ defines a function which does nothing
☐ defines a function, which passes its parameters through
☐ defines an empty class
The def
statement defines a function. The pass
statement is a null operation.
There is no return from this function so it will return the default “None” object.
71. What are the method(s) that an iterator object must implement?
☐ __iter__()
☑ __iter__()
and __next__()
An iterator is an object that implements __next__()
, which is expected to return the next element of the iterable object that returned it.
In the simplest case the iterable will implement __next__()
and return self in __iter__()
.
72. If a function contains at least one yield statement, it becomes?
☐ an iterable ☑ a generator function
Generator is basically an iterator function that uses yield
multiple times to return values.
…
tags: quiz - questions & category: python