Python tests, quizzes, and exams are great ways to learn and test your Python programming skills. Whether you’re a beginner or experienced, challenge and boost your confidence with our engaging online quizzes on Python basics, operators, loops, strings, lists, tuples, sets, dictionaries, functions, modules, files, and exceptions. Start the Python online test now
Trang 1Python Online Practice Test - 1
Q Python is ?
A General-purpose interpreted language
B General-purpose interpreted and interactive language
C General-purpose interpreted, interactive language and object-oriented language
D General-purpose interpreted, interactive language, object-oriented and high-level programming language
Correct Answer : OPTION D, General-purpose interpreted, interactive language, object-oriented and level programming language
high-Q Python was created by ?
Correct Answer : OPTION B, Guido van Rossum
Q Python source code is also available under which license?
Correct Answer : OPTION A, GPL
Q Which of the one is an invalid python environment variable?
Correct Answer : OPTION D, PYTHONLIBRARY
Q What is PYTHONHOME?
A It is an alternative module search path
B It contains the path of an initialization file containing Python source code
C It is used in Windows to instruct Python to find the first case-insensitive match in an import statement
D None of the above
Correct Answer : OPTION A, It is an alternative module search path
Q What is PYTHONPATH?
A It is used for installation of Python
Trang 2B It tells the Python compiler where to locate the module files imported into a program
C It tells the Python interpreter where to locate the module files imported into a program
D None of the above
Correct Answer : OPTION C, It tells the Python interpreter where to locate the module files imported into a program
Q What is PYTHONSTARTUP?
A It is executed every time you start the compiler
B It is executed every time you start the interpreter
C It is needed while booting of a particular process
D None of the above
Correct Answer : OPTION B, It is executed every time you start the interpreter
Q What is PYTHONCASEOK?
A It is used to find the first case-sensitive match in an import statement
B It is used to find the first case-insensitive match in an import statement
C It is used to find the first case-insensitive match in a package statement
D None of the above
Correct Answer : OPTION B, It is used to find the first case-insensitive match in an import statement
Q What is the use of -d command line option?
A It provides debug input
B It provides debug output
C It generates optimized bytecode
D None of the above
Correct Answer : OPTION B, It provides debug output
Q What is the extension of Python files?
Correct Answer : OPTION B, py
Q Which of these is invalid naming convention for Python identifiers?
A An identifier can start with lowercase letter B An identifier can start with uppercase letter
C An identifier can start with a number D An identifier can start with underscore(_)
Correct Answer : OPTION C, An identifier can start with a number
Trang 3Q What is the maximum possible length of an identifier?
Correct Answer : OPTION D, None of the above
Q All keywords in Python are in ?
A Lowercase
B Uppercase
C Alphanumeric
D None of the above
Correct Answer : OPTION A, Lowercase
Q Python keywords can be used as ?
Correct Answer : OPTION D, None of the above
Q Which is not a valid keyword?
Correct Answer : OPTION A, eval
Python Online Practice Test - 2
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q Which one of these is used to comment statements in Python?
Correct Answer : OPTION B, #
Q How many standard data types does Python support?
C 5 D None of the above
Trang 4Correct Answer : OPTION C, 5
Q Which one of these is not a part of standard data types in Python?
Correct Answer : OPTION B, Character
Q Reference to a number object can be deleted using which statement?
Correct Answer : OPTION A, del
Q Python does not support which of these numerical types?
Correct Answer : OPTION B, signedInt
Q Which operator is used to concatenate strings in Python?
Correct Answer : OPTION C, +
Q What is the difference between Lists and Arrays?
A Unlike array, items belonging to Lists can be of different data type
B Unlike array, list uses parentheses to store items
C There is no difference between Lists and Arrays
D None of the above
Correct Answer : OPTION A, Unlike array, items belonging to Lists can be of different data type
Q Elements in Tuples are stored using ?
C {} D None of the above
Correct Answer : OPTION B, ()
Q Dictionaries are enclosed by curly braces and values can be assigned and accessed using square braces ?
Trang 5A [] and {}
B {} and []
C () and {}
D [] and ()
Correct Answer : OPTION B, {} and []
Q Python supports which types of operators?
A Arithmetic, Relational, Assignment and Logical operators
B Arithmetic, Relational, Assignment, Logical and Bitwise operators
C Arithmetic, Relational, Assignment, Logical, Bitwise and Membership operators
D Arithmetic, Relational, Assignment, Logical, Bitwise, Membership and Identity operators
Correct Answer : OPTION D, Arithmetic, Relational, Assignment, Logical, Bitwise, Membership and Identity operators
Q Which one of these is not an Arithmetic operator?
C *** D None of the above
Correct Answer : OPTION C, ***
Q Which one of these is not Comparison operator?
Correct Answer : OPTION D, ===
Q Which one of these is not an Assignment operator?
A **=
B //=
C ***=
D None of the above
Correct Answer : OPTION C, ***=
Q Which one among these are Membership operator?
Correct Answer : OPTION B, in and not in
Q Which one among these are Identity operator?
Trang 6A is and not is B is and not if
Correct Answer : OPTION C, is and is not
Python Online Practice Test - 3
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q What is the order of precedence in python?
A Parentheses, Exponential, Division, Multiplication, Addition, Subtraction
B Parentheses, Multiplication, Division, Exponential, Addition, Subtraction
C Parentheses, Division, Multiplication, Addition, Subtraction, Exponential
D None of the above
Correct Answer : OPTION A, Parentheses, Exponential, Division, Multiplication, Addition, Subtraction
Q What is the value of following expression: 3*1**3
Correct Answer : OPTION B, 3
Q Which one of the following have the same precedence?
A Addition and Subtraction B Multiplication and Division
Correct Answer : OPTION C, Both A and B
Q What will be the output of the below program?
>>>str="studytonight"
>>>str[:5]
>>>
Trang 7A tonight B study
Correct Answer : OPTION B, study
Q What is the datatype of below statement?
L = [1, 'hello', 'studytonight', 1]
Correct Answer : OPTION C, List
Q Which datatype is used to store values in terms of key and value?
Correct Answer : OPTION D, Dictionary
Q What does ~9 evaluate to?
Correct Answer : OPTION D, -10 It is evaluated as –(9+1) = -10
Q What is the value of following expression: 24//6%3
Correct Answer : OPTION B, 1
Q What is the value of following expression: bin(0x8)
A 8
B 1000
C '0bx1000'
D '0b1000'
Correct Answer : OPTION D, '0b1000'
Q What is the output of the code shown below?
Trang 8bool()
Correct Answer : OPTION D, True False
Q What is the output of the code shown below?
['study', 'tonight'][bool('')]
Correct Answer : OPTION C, study
Q What is pass statement in Python?
A It declares variables B It defines function
C It is a null statement D None of the above
Correct Answer : OPTION C, It is a null statement
Q What is the output of the code shown below?
Trang 9C tonight
D None of the above
Correct Answer : OPTION B, study
Q What is the output of the code shown below?
X="studytonight"
print("05d"%X)
Correct Answer : OPTION C, Error
Q What is the output of the code shown below?
s='{0}, {1}, and {2}'
s.format('hello', 'good', 'morning')
A 'hello study and tonight' B 'hello, study, tonight'
Correct Answer : OPTION C, 'hello, study, and tonight'
Python Online Practice Test - 4
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q What is the output of below code?
Trang 10A <class 'tuple'> B <class 'int'>
C <class 'set'> D <class 'list'>
Correct Answer : OPTION D, <class 'list'>
Q What is the output of below code?
print(type(1/2))
A <class 'int'> B <class 'number'>
C <class 'float'> D <class 'double'>
Correct Answer : OPTION C, <class 'float'>
Q What is the output of below code?
Correct Answer : OPTION B, 24
Q If PYTHONPATH is set in the environment, which directories are searched for modules?
I) PYTHONPATH directory
II) Current directory
III) Home directory
IV) Installation dependent default path
Trang 11A I and IV B I, II and III
Correct Answer : OPTION C, I, II and IV
Q Which one of these is not a loop control statement?
Correct Answer : OPTION D, def
Q Which one of the following is a mathematical function?
Correct Answer : OPTION B, pow(x)
Q What is the output of below code?
Correct Answer : OPTION C, Syntax Error
Q What is the output of below code?
Trang 12Q What is the output of below code?
D None of the above
Correct Answer : OPTION C, Error
Q What is the output of below code?
for i in '':
print (i)
C Null D None of the above
Correct Answer : OPTION D, None of the above
Q What is the output of below code?
Correct Answer : OPTION B, 0 1 2 2
Q What is the output of below code?
Trang 13string = "study tonight"
for i in string.split():
print (i, end=", ")
Correct Answer : OPTION B, (study, tonight,)
Q What is the output of below code?
Correct Answer : OPTION C, 2
Q What is the output of below code?
for i in range(0):
print(i)
Correct Answer : OPTION B, No Output
Q What is the output of below code?
print(r"\nstudytonight")
Trang 14A studytonight B \nstudytonight
Correct Answer : OPTION B, \nstudytonight
Python Online Practice Test - 5
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q A group of developers,were discussing the various options,for interacting with websites,through code Following points were stated -
DevA - While using urllib,one can use the method urlencode,for generation of GET query strings.The
Requests module,does the encoding automatically.Urllib2 also has urlencode method
DevB - Only urllib module, has an urlencode function.Requests module,handles error very
well,whereas,the urllib2 raises an URLError,if the authentication fails
DevC - Both urllib2 and Requests module,raise an URLError,when authentication fails.The urlencode()
method,is present in urllib2 and not in urllib module
Mark the correct statement
A Dev B is correct about URLError whereas Dev A is wrong about urlencode function
B Dev C is totally wrong.
C Dev A is totally correct.
D Dev C is correct about urlencode function,whereas DevB is wrong about URLError.
Correct Answer : OPTION B, Python Requests module,encode requests automatically.For generation of GET query strings, method urlencode() present in urllib,is used No such method is present in urllib2.Urllib2 raises an URLError,if any authentication fails, whereas, Requests module simply returns a response
object,in such a scenario.Thus it handles errors well
Q A developer was debugging,a Python program,using the pdb module.Below are some descriptions,of thedebug commands:
Trang 151) List the source code.
Mark the correct output
A 1) cmp method does not exists in Python3 2) SyntaxError :invalid syntax
B 1) 1 2) {'Benguluru':30,'Delhi':40}
C 1) -1 2) SyntaxError : Key cannot be deleted individually
D 1) SyntaxError 2) SyntaxError: Delete not supported for dictionary
Trang 16Correct Answer : OPTION A, The cmp method is present in Python2 but not in Python3 It should be
implemented,by the developer,if needed The delete function,can be applied,to individual elements of Dictionary It should be used as del dict_name(key name)
Q A developer was solving a worksheet of regex problems He came across the following:
import re
print((re.split(r'\s','funday is sunday')))
print((re.split(r's','fun is sunday')))
print((re.split(r'\d','sunday 3 times a week')))
Mark the correct output of the print statements
A ['funday', 'is', 'sunday'] ['funiunday'] ['sundaytimesaweek']
B [ 'is', 'sunday'] ['s ','s'] ['3']
C ['fundayi', 'ss', 'unday'] ['fun', 'i ', 'sunday'] ['sunday','3', ' times a week']
D ['funday', 'is', 'sunday'] ['fun i', ' ', 'unday'] ['sunday ', ' times a week']
Correct Answer : OPTION D, The \s expression,is used to create a space in the string When the ' \' is removed,from the string,only alphabet 's' is removed from the output.The '\d' expression,removes the digits present in the string
Q A developer was teaching his team,about the different socket methods,found in network
programming.Below are few descriptions of the same:
1) This method,sends the User Datagram Protocol(UDP) message.
2) This method,sends a TCP message.
3) This method,receives a UDP message.
4) This method,starts the TCP listener.
Map them with the actual method names.(s is the socket object)
Trang 17Q In an interview,developers were asked to mention if the following statements,were true or false.
1) Static analysis tool, that detects bugs,present in Python code is PyChecker.
2) PyModule tool,checks if the python module,meets the coding standards
3) PyFlakes tool,parses the source files,and,points out various errors,present in the code
4) Pylint,is also a quality checker,which checks the length of each line.
Mark the statements as True or False
A False, True, True, False B True, True, True, True
C True, False, True, True D False, False, False, False.
Correct Answer : OPTION C, Python consists of various tools, that help in finding bugs and errors in the code.They also help in quality checking and static analysis
Q In an exam,following code snippets were provided:
Mark the correct output
A 1) ['pune',mumbai','delhi'] 2) False 3) SyntaxError.
B 1) ['PUNE','MUMBAI','DELHI'] 2) True 3) TypeError
C 1) TypeError 2) [] 3) Number of continents are 7.
D 1) SyntaxError 2) TypeError 3) Number of continents are 7.
Trang 18Correct Answer : OPTION B, The new lower case list,returned is not stored anywhere Hence the original mylist list is printed If any value,is passed to bool() function,it returns true.Concatenation of string and integer,is not allowed Hence the 3rd code snippet throws TypeError.
Q A developer had to mark,the following statements,related to Multithreading in Python,as True or False:
1) RLock can be acquired,by the same thread,multiple times.
2) Acquired Lock,can be released,only by the thread,that acquired it.
3) Acquired RLock,can be released by any thread.
4) If an RLock is acquired 'n' number of times, it should be released,'n' number of times.
Mark the correct output
A True, False, False, True B False, True, True, False.
C False, False, True, True D True, True, False, False.
Correct Answer : OPTION A, RLock can be acquired by the same thread multiple times It needs to be released too, the same number of times Acquired lock,can be released,by any thread,whereas,the
acquired RLock can be released only by the thread that acquired it
Q A developer was trying to parse a XML document in Python code Mark the correct steps,that, he needs
to implement:
1) The xml.dom.minidom module,should be imported, to parse a XML file.
2) The parseXML function,is used to load and parse the XML file.
3) The standard DOM function,getElementsByTagName can be used to get XML tags.
4) The firstChild.name,can be used to print,the name of the firstchild,of the document node.
Mark the correct answer
A 2nd and 3rd are correct steps 1st and 4th are incorrect.
B All steps except 4th are valid.
C 1st and 3rd are correct steps 2nd and 4th are incorrect
D Except 2nd all steps are valid.
Correct Answer : OPTION C, The xml.dom.minidom module,should be imported, to parse a XML file.The xml.dom.minidom.parse(xml name) function,is used to load and parse the XML file The
firstChild.tagname,can be used to print,the name of the firstchild of the document node
Q Below are mentioned, a few points about different Python frameworks:
1) External libraries are required for database administration and templating
2) Bootstrapping tools are not present
3) Provides flexibility,and,allows the developer, to choose right tools,for their projects.
Trang 194) It has built-in modules for routing,authentication and templating.
Guess the name of the framework from the description
A Django, Pyramid, Django, Flask B Django, Pyramid, Pyramid, Flask.
C Django, Flask, Flask, Pyramid D Pyramid, Flask, Pyramid, Django.
Correct Answer : OPTION D, Pyramid,Django and Flask are a few web frameworks built in Python Flask framework is mainly used for building small applications whereas Django and Pyramid are meant for largerones
Python Online Practice Test - 6
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q.In an exam, the developers were provided,the following statements,regarding File copying,using system shell utilities:
a) The shutil.copy2() function, is same as shutil.copy(), except that copy2(),copies the file metadata,along
with the file
b) When using copy2() function, one must specify the file buffer.
c) The copy2() function,does not copies,the permission bits,to the destination file.
d) If we want an exact duplicate copy of a file, the copy() function,should be used,instead of copy2().
Mark them if they are appropriate as Yes or No
Correct Answer : OPTION C, The shutil copy() and copy2() functions,are almost same.Copy2(),copies the file metadata,along with the file.There is no need,to specify,the file buffer.It copies the permission bits,of the destination file as well.If we want,an exact duplicate copy of a file, then, copy2() should be used
Q Below are mentioned,descriptions of Python file extensions:
a) Python script archive file.
b) Windows DLL file.
c) A python file created with optimizations.
Trang 20d) The compiled bytecode of the file.
Mark them correctly with the actual file extensions
A .pyz, pywdl, pyop, pyc B .pyr, pydl, py, py
C .pya, pyw, pyz, py D .pyz, pyd, pyo, pyc
Correct Answer : OPTION D, Python scripts can have many extensions as mentioned above
Q A developer was checking,her Python code,using Tabnanny utility tool She knew,that tool helped,in checking ambiguous code.She was given,some points to check:
1) Analyse white-space related issues.
2) Code should print verbose messages.
3) Display names of files,that contain issues,related to whitespaces.
Which methods,of the tool should she use?
Mark the correct answer
A tabnanny.checkdir(dir/file name), tabnanny.explicit, tabnanny.filename.
B tabnanny.check(dir/file name), tabnanny.verbose, tabnanny.filename_only
C tabnanny.whitepsc(),tabnanny.verbose_message,tabnanny.file_name
D tabnanny.checkfile(dir/file name), tabnanny.msgverbose, tabnanny.file_name_only.
Correct Answer : OPTION B, The tabnanny module, mentions ambiguous code It tells if any weird combination,of tabs or spaces, are found in the code
Q In an exam,students were provided following code snippets:
Trang 21Mark the correct output
A.1) 3 2) AssertionError: "This is divide by zero" B 1) 3 1 2) Just AssertionError is printed
C.1) 1 2) DivideByZero error is thrown.
D.1) Syntax Error 2) Syntax Error
Correct Answer : OPTION A, One can mention a customised message,in the Assert,by writing it after the assert syntax The elif is short form of else if.There can be an arbitrary number of elif's,followed by if's
Q In an interview,a rapid fire round was conducted,where the freshers were told,to answer the
questions,as Yes or No:
1) Atmost,only one else statement,can follow an if statement.
2) Python does not has a switch and case syntax.
3) By default,parameters are passed to its functions, using pass-by-reference.
4) Internally a namespace,is implemented as a dictionary, in Python.
Mark the correct answer
A Yes, Yes, No, No B Yes, Yes, Yes, Yes.
Correct Answer : OPTION B, Multiple Elif's can follow if statements.But only one else,can be present.Python does not have a switch-case statement,like other languages.Parameters are passed by reference,to its function by default.Only strings,tuple etc are passed by value,since they are immutable.A namespace is implemented as a dictionary internally
Q A group of developers,were involved in a debate,about methods and functions,in Python:
Dev A- A method is associated to a class object It may or may not return any data.
Dev B- A function can be called,by its name,as well as,using the class object.A method should always
return some data
Dev C- A method is associated to a class object,whereas a function is not Data parameters are passed
implicitly to a function
Mark the correct answer
A.Dev B and Dev C are totally wrong.
Trang 22B.Dev C is totally correct whereas Dev A is totally wrong
C Dev A and C are totally correct.
D.Dev A is totally correct whereas Dev B is totally wrong
Correct Answer : OPTION D, A method is associated to a class object A function is independent It has no relation to the class or its object Both, may or may not return any data.Data parameters are passed explicitly,to a function.A function is called,by its name,whereas,a method is called, using the class object
Q A developer was working,on some f-strings code snippets She was trying,to analyse,the output of the following:
#1
name="Alisa"
profession="Doctor"
regards_msg = f"Hello {name} " \
"Meet you soon {profession} "
author = "Enid Blyton"
books =f"author.lower() is amazing!"
print(books)
Mark the correct output
A 1) Hello Alisa Meet you soon Doctor 2) 34*2 3) enid blyton is amazing!
B 1) Hello Alisa Meet you soon Doctor 2) Throws an error 3) enid blyton is amazing!
Trang 23C 1) Hello Alisa Meet you soon {profession} 2) 68 3) author.lower() is amazing!
D.1) Hello Alisa Meet you soon {profession} 2) 68 3) enid blyton is amazing!
Correct Answer : OPTION C, F-strings are formatted string literals They start with a "f",in the beginning with curly braces For multiple lines, "f" should be mentioned,before the start of every line { curly
braces } should be written,while using any function such as lower() upper() etc
Q A lead was testing, his team's knowledge on lists So he gave them,the following code snippet:
Mark the correct output
A The print statements would display: ['gold', 'platinum', 'lead'] ['gold', 'platinum', 'bronze', 'tin'] ['gold', 'platinum', 'bronze',
'titanium', 'tin']
B The print statements would display: ['gold','silver','platinum', 'lead'] ['gold', 'silver','platinum','bronze', 'tin'] ['gold','silver',
'platinum','titanium','tin']
C The print statements would display: ['silver','copper','platinum', 'lead'] ['lead','bronze', 'tin'] [''titanium','lead','bronze', 'tin']
D.The print statements would display: ['copper','platinum', 'lead'] ['copper','platinum','bronze', 'tin']
two_val = lambda num1: num1 * 2
three_val = lambda num1: num1 * 3
abc = 3
abc = two_val(abc)
Trang 241) Performance wise Scala,is much better than Python.
2) Python is much simpler,than Scala.
3) For an application, which consists of a lot of concurrent processes,Python should be preferred.
4) Refactoring Scala code,is much easier,as compared to Python.
Mark them as True or False
A False, True, False, True B True, True, False, True.
C False, True, False, False D False, False, True, False.
Correct Answer : OPTION B, Since Scala uses the JVM it is much faster than Python.Python has a simpler syntax,hence easy to use.Python cannot be preferred for an application,which consists of concurrent processes running.Scala on the other hand,has multiple asynchronous libraries,which can be used for the same.Refactoring Scala code is easier as compared to Python
Trang 25Q In a language processing application,a developer was working,on the following code:
What is the output expected?
A focus, criteria, crise B focus, criterion, crisis.
C foci, criteria, crises D foci, criterion, crisis.
Correct Answer : OPTION B, Lemmatization links words, with same meanings,to one word.It displays the closest noun,of the word,by default
Q Below are a few points mentioned, about the internal working of an interpreter:
1) The breaks the line of code into tokens
2) The uses the tokens,to prepare a structure,that shows,relation between tokens.
3) The turns the token structure,in code objects.
4) The runs the code objects.
Mark the correct option
A Parser, Lexer, Compiler, Interpreter B.Lexer, Compiler, Parser, Compiler.
C Compiler, Parser, Parser, Interpreter D Lexer, Parser, Compiler, Interpreter.
Trang 26Correct Answer : OPTION D, The lexer breaks, the line of code, into tokens.These tokens,are then used,by aparser, to prepare a Abstract Syntax Tree,which gives the relation,between the tokens.The
compiler,converts the tokens,into code objects.The interpreter, then runs,these code objects
Q In an interview,code snippets of some built-in functions,were given:
B.1) [ 'a','C','E','L', 't', 'x', 'y'] 2) (1) 3) 'abc+44'
C 1) ['C', 'E', 'L', 'a', 't', 'x', 'y'] 2) (5,1) 3) 88
D 1) ['y','x','t','L','E','C','a'] 2) (5) bronze 3)SyntaxError
Correct Answer : OPTION C, The divmod function,returns a tuple, of quotient and remainder,of the
division.The sorted function,gives the sorted version, of an iterable.The eval function,takes string as an argument, that,parses an expression
Q A fresher,was given the task,of converting a few functions, in Python,to lambda expressions:
Trang 27def add_three(x,y,z):
return x+y+z
Mark the correct lambda expressions
A 1) cube_root=lambda x:math.pow(x,1/3) 2) add_three=lambda x,y,z:x+y+z
B 1) cube_root=lambda (x):math.pow(x,1/3) 2) add_three=lambda(x,y,z):x+y+z
C 1)cube_root=lambda x:return math.pow(x) 2) add_three=lambda x,y,z:return x+y+z
D 1)cube_root=lambda (x):return(math.pow(x,1/3)) 2) add_three=lambda (x,y,z):return(x+y+z)
Correct Answer : OPTION A, A lambda expression has an implicit return statement.It allows us, to define a function anonymously
Q In an exam,following code snippet was provided:
Mark the correct output of the same
A On execution,an error is thrown, saying Sum _init_ method,should be redefined, in subclass
B No error is thrown, as the inheritance code, is implemented properly.
Trang 28C On execution,an error is thrown,saying, Number object cannot access,attribute 'sum' present in superclass.
D On execution,an error is thrown,saying, Number object has no attribute 'sum'.
Correct Answer : OPTION D, Since _init_ is redefined in subclass Number, we need to explicitly call the _init_ of the super class as Sum._init_(self,sum) in the subclass _init_ method
Q In an interview,freshers were asked,to mark the following statements,as Valid or InValid:
1) The *args allows,zero number of extra arguments.
2) The *args and **kwargs, when used together, should be in the order:
def somefunc(fnargs,*args,**kwargs):
Using **kwargs before *args,will throw an error
3) **kwargs is used,to pass a keyworded,variable length argument list.
4) **kwargs can be compared,to a set object,such that,when we iterate over it,the elements are orderly printed
A Valid, InValid, Valid, Valid B Valid, Valid, Valid, InValid.
C Valid, InValid, InValid, InValid D InValid, InValid, Valid, InValid.
Correct Answer : OPTION B, The *args and **kwargs,are used to pass, variable number of arguments.*args does allows, zero number of extra arguments.The order of using them,as function arguments, should be maintained.Using **kwargs,before *args,will throw an error.The **kwargs,is used to pass a
keyworded,variable length argument list The **kwargs,can be compared, to a dict object,that maps,each key to the value,that is passed
Q.Below are a few statements made,either about xrange or range function:
1) A particular range, is shown on demand,hence,it is also called as "lazy evaluation".
2) It returns the list of numbers,created using the range() function.
3) Here,the variable,storing the range returned,takes more memory
4) Operations related to the 'list',cannot be applied,on an object here.
Mark them appropriately
A range, xrange, range, xrange B xrange, range, xrange, range.
C xrange, range, range, xrange D range, xrange, xrange, range.
Trang 29Correct Answer : OPTION C, Range() returns a list,whereas,xrange() returns a generator object,that can display numbers by looping.In xrange(), particular values can be displayed by looping.Thus it is also called
as lazy evaluation.The variable storing,the return type of range(),takes more memory, than,the one
storing,the return type of xrange().The range() function,returns a list,whereas xrange() returns an
object.Since range() returns a list,all operations of a list,can be applied,on a list.But the same,cannot be applied,on return type of xrange()
Q In a technical competition, participants had to face a rapid fire round, about Python facts:
They were supposed to answer the questions as Yes or No
1) Python does not have any data types, for characters,as they are treated as strings.
2) Try and catch, is used for exception handling.
3) A do-while loop,is present in Python.
4) Python is not a compiled language.
Mark the correct output
Correct Answer : OPTION C, Python does not have any 'char' datatypes.It is an interpreted language.A while loop is not present in Python.Try and except are used for exception handling
do-Q A developer was working,with the 'numpy' library,for performing some mathematical operations
Consider the following code
Trang 30Mark the correct answer.
from collections import Counter
cake=Counter({'vanilla':43,'chocolate':12,'coffee':23})
A 0, Counter({'t': 4, 'e': 2, 's': 1, 'x': 1}) B -1, Counter({'testtext})
C KeyError, (testtext) D KeyNotFoundError, {testtext}
Correct Answer : OPTION A, In counters,if the key is not found,then no KeyError is raised.Only 0 is
printed.Arithmetic operations, can also be performed,on counters
Trang 31Python Online Practice Test - 8
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q In an interview,following code snippets were provided The lists present were:
print ("List 3 elements")
for i in range(0,len(list3)):
print (list3[i],end=" ")
print("\r")
print ("List 4 elements - ")
for i in range(0,len( list4)):
print (list4[i],end=" ")
Mark the correct print outputs
A List 3 elements- 2 5 [777, 0] 7 List 4 elements- 3 9 1
B List 3 elements- 2 5 [777, 0] 7 List 4 elements- 3 9 888
C.List 3 elements- 2 5 [8, 0] 7 List 4 elements- 3 9 888
D.List 3 elements- 2 5 [8, 0] 7 List 4 elements- 3 9 1
Trang 32Correct Answer : OPTION A, In shallow copy,any changes made,to the copy of object, are reflected in the original copy In deep copy,changes made to the copy of object, are NOT reflected in the original copy.
Q Match the Python frameworks with their descriptions:
a It has modules for interpolation,linear algebra, image processing etc
b It is neither a mega-framework nor a micro-framework
c It relies on rapid development and follows a MVC architecture
d It does not have form validation and doesn't needs certain tools or libraries
Mark the correct answer
A 1-a, 2-c, 3-b, 4-d B 1-d, 2-a, 3-c, 4-b
C 1-b, 2-d, 3-a, 4-c D 1-c, 2-b, 3-d, 4-a
Correct Answer : OPTION C, The various Python frameworks have different features and capabilities
Q In an interview,freshers were provided with following code snippet:
Mark the correct answer
A Invalid input gets printed.
B Indentation error is thrown.
C ZeroDivisionError is thrown.
Trang 33D First ZeroDivisionError and then TypeError are thrown.
Correct Answer : OPTION C, The divide by zero is caught first Hence rest of the lines are skipped Thus the TypeError is not caught and printed
Q In a quiz, Python string was provided:
C 1) HelloWor 2) He 3) d D 1) rld 2) Hel 3) HelloWor
Correct Answer : OPTION B, [:-2] prints the characters,from start of the string,till two characters,at the end
of the string(Indexing begins at 0) [-2:] prints two characters from the end of the string(Indexing begins at0) [:1] prints the characters from the start of the string(Indexing begins at 0)
Q Below are provided a few code snippets:
Correct Answer : OPTION D, Comparing an integer,with a float,does not produce any output
Q Below are provided a few code snippets:
Trang 34string_first = "NEW CAR"
string_second = "new car"
if(string_first < string_second):
print("My cars!")
elif(string_first > string_second):
print("NOT my cars!!")
Mark the correct output of the same
print("Value of var2 outside:",var2)
Mark the correct output of the same
A The code throws an error -"global keyword incorrectly defined"
B The code throws an error -"local variable var1 referenced before assignment"
Trang 35Q In an exam following statements were provided.
1 Pickling is same as serialization
2 Pickling throws errors,when it is pickling data,that,may be insecure or malicious
3 Pickling and Unpickling,allows to send data,from one server to another easily
4 One can start pickling data,by importing the 'pickle' module
Mark the correct answer
A False, False, False, True B False, True, False, True.
Trang 36C True, False, True, True D True, False, True, False.
Correct Answer : OPTION C, Pickling is same as serialization It allows to send data,from one server to another,by serializing the object first.It helps in saving complex data.The pickle module,is not capable,of raising errors, if any corrupted or malicious data,hence the security risk.One needs to import 'pickle' module to start using it
Q A peer once asked a developer, the output of the following code snippet
Mark the correct Output
A Step1:[2,6,3,45] , Step2:[2,6,3,45,2,6,3,45] , Step3:[2,6,3]
B Step1:[3,45,2,6] , Step2:[6,90,4,12], Step3:[3,45,2,6]
C Step1:[3,45,2,6] , Step2:[3,45,2,6,3,45,2,6], Step3:[3,45,2]
D Step1:[2,6,3,45] , Step2:[4,12,6,90] , Step3:[2,6,3,45]
Correct Answer : OPTION A, Extend function appends the elements in the existing array The "*" operator repeats the elements of the array "n" number of times.The slice function array[a,b] slices,the elements of the array Here 'a' is the position to start(indexing begins with 0) and 'b' is the position to stop(indexing begins with 1)
Q A lead was explaining to his team the pros and cons of the Django framework Which of the points put forth are valid(V) or Invalid(In)
1 When a resource is requested by an user,Django takes care of the controller part and commands interaction between the view and model
2 Django doesn't works well with XML It does works easily with JSON though
3 Django stores hashed passwords in cookies
Trang 374 In django,the manage.py allows to start the server,whereas,the database.py allows syncing,to the database.
Mark the correct answer
Correct Answer : OPTION D, Django takes care of the controller part,when a resource is requested,by the user.Thus it follows a MVT pattern,where a Template is returned,to the user.Django works well with JSON , XML HTML etc all frameworks.It stores hashed passwords in cookies.The manage.py allows to start the server as well as syncing to the database
Python Online Practice Test - 9
This Test will cover complete Python with very important questions, starting off from basics to advanced level
Q In an exam,developers were provided,the following code snippets:
Correct Answer : OPTION C, Adding [::-1]besides any list, prints it in the reverse order
Q In an exam,developers were provided,the following code snippets:
import operator
Trang 38Correct Answer : OPTION C, Using inplace operators, with lists,alters the values,in both the lists.
Q A peer,was explaining to his team,the concept of partial functions,in Python He gave them the followingexample:
from functools import partial
def partial_eg(first,second,third):
return first* second* third
result = partial(partial_eg,5,8)
print(result(2))
Mark the correct answer
A The code written, by peer is wrong It will throw TypeError Wrong number of arguments.
B The code written, by peer is correct Answer printed will be 80.
C The code written, by peer is correct Answer printed will be 40.
D The code written, by peer is correct Answer printed will be 2.
Correct Answer : OPTION B, Partial functions,allow,to derive specialized functions, from general
functions,and,reuse the code.The partial function,from functools module,should be used to do the same
Trang 39Q Developers were provided,the following statements,about Caching in Python,in an interview.They were asked to mark them as True or False:
1 Using Memcached is a nice option,when the application system,is spread across a network
2 Python has a data structure lfu_cache,which uses least frequently used algorithm,to limit the cache size
3 If the memcached server goes down,the client keeps sending a request,till the time-out limit is reached.s
4 We can use memcache,as a data store,as well as,a cache
Choose the correct answer
A False, False, False, True B True, False, True, False.
C True, True, True, False D False, True, False, True.
Correct Answer : OPTION B, Memcached is an appropriate option,when the application system,is spread across a network.Python has a data structure lru_cache,least recently used,algorithm,to limit the cache size.Memcached should generally be used,only as a cache,and,not as a datastore.The client keeps sending
a request,till the time-out limit is reached,if the server goes down
Q A group of developers were involved,in a debate about Python 2 and 3 differences:
DevA- In Python3,there are two byte classes - the bytearray and byte.In Python2, there is no byte type
present.Filter() and map() return lists in Python2.Python3 raises a SyntaxError, if exception arguments are not enclosed in parentheses
DevB- In Python3, TypeError is raised as a warning,if unorderable types are compared.The same does not
happens with Python2.Filter() returns a list in Python2 and Python3 version,but, map() returns the same, only in Python2.Python3 never raises a SyntaxError, if exception arguments are not enclosed in
parentheses
DevC- Both Python versions,have a byte type present.A bytearray type,is not present in Python2.In
Python3 and Python2 version,map() returns a list,wheres filter() returns a list only in Python2
Mark the correct output of the same
A DevA is wrong, while DevC is correct about byte classes,DevB is correct about SyntaxError.
B DevA is correct about Syntax error , DevB is wrong about filter() function and DevC is wrong about
map() function
C DevA is wrong about SyntaxError raised,DevB is wrong about TypeError and DevC is correct about
Trang 40map() and filter() functions.
D DevA is correct about byte classes , DevC is totally wrong and DevB is correct about map() and filter()
functions
Correct Answer : OPTION B, In Python3,there are two byte classes - the bytearray and byte Python2 has
no such byte types.Python3 raises a SyntaxError, if exception arguments are not enclosed in
parentheses.Filter() and map() functions, return lists in Python2,but,not in Python3.In Python3, TypeError israised,as a warning,if unorderable types are compared(eg list is compared with string)
Q Consider the following code snippets:
Mark the correct output of the same
A HELLONAMASTE and -45 are printed B Both the code snippets throw SYNTAXERROR.
C NAMASTE and 45 are printed D HELLO and -45 are the outputs.
Correct Answer : OPTION D, Functions can be passed as arguments to other functions.We can assign
function to a variable A function can return another function
Q A developer was working with Numpy library He was told,to create the following types of arrays:
1 Create an 2x3 array, of complex type, with real value number 3