0% found this document useful (0 votes)
612 views

Python Quiz

The document discusses decision making in programs and provides examples of code snippets with questions about their output. Decision making refers to the process of predicting conditions and specifying actions to be taken based on those conditions during program execution. Some key points made are: - Comparing string values "20" and "30" with > would return False. - Casting (data type conversion) using int() can convert a value from float to int for accurate division results. - An if statement is used to check a condition and take action based on the result. So in summary, the document discusses decision making through if/else statements and examples, and provides questions to test understanding of code snippets and outputs.

Uploaded by

Pravin Poudel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
612 views

Python Quiz

The document discusses decision making in programs and provides examples of code snippets with questions about their output. Decision making refers to the process of predicting conditions and specifying actions to be taken based on those conditions during program execution. Some key points made are: - Comparing string values "20" and "30" with > would return False. - Casting (data type conversion) using int() can convert a value from float to int for accurate division results. - An if statement is used to check a condition and take action based on the result. So in summary, the document discusses decision making through if/else statements and examples, and provides questions to test understanding of code snippets and outputs.

Uploaded by

Pravin Poudel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 99

Which of the following is prediction of the conditions and specifies the actions to be taken

according to these conditions while execution of a program?


A

Casting
B

Decision making
C

Serializing
D

Importing

You are a Python developer in a company. You are asked to work on a code based on the
comparison operator in Python and find out the output. You have the following code:

1. x = "20"
2. y = "30"
3. print(x>y)

What output will you get from the code?


A

The code will give an exception


B

False
C

True
D

2030
Which of the following are the correct rules for writing identifiers?
 
Each correct answer represents a complete solution. Choose all that apply.
 
A

Identifiers can be a combination of letters, digits, and an underscore (_).


B

Keywords cannot be used as identifiers.


C

An identifier can be of any length.


D

An identifier can start with a digit or letter.

You are a beginner in the Python language. You have learned about data type conversion in
Python. You have written a program of division of variables whose output is coming in
the int() data type but you want the output in the float() data type to get more acurrate result.
Which of the following processes will you perform to convert the int() data type to
the float() data type?
A

Casting
B

Name mangling
C

Serializing
D

Importing
The special functionality shown by the following code is the:

if z>y: print('z is greater than y')

This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

print statement.
B

comparison operator.
C

single statement suite.


D

if statement.

You are an intern in the coding team of the ABC company. You are working on the Python
language to create a commercial application. You have to create a script that asks the user for a
value which is always used as a whole number, even if the user enters a decimal value. Which
code segment should you use?
A

value = str(input("Enter the value:"))


B

value = input("Enter the value:")


C

value = int(input("Enter the value:"))


D

value = float(input("Enter the value:"))


What is the output of the following code?

1. a = 1+2j
2. print(a, "is complex number?", isinstance(1+2j,complex))

<class 'complex'>
(1+2j) is complex number? None
B

(1+2j) is complex number? <class 'complex'>


C

(1+2j) is complex number? True


D

TypeError will be generated.

You are a Python developer in a company. You are asked to develop a program which gives the
birth year of the user as an output. You have been given the following code:

1. year = 2018
2. age = 25
3. # put your line of code here
4. print(birth_year)

You have to complete the code to execute it. Which line of code will you use for this purpose?
A

birth_year = str("year") - str("age")


B

birth_year = int("year") - int("age")


C

birth_year = eval(year) - eval(age)


D
birth_year = eval("year") - eval("age")

What is the expected output of the given code?

1. a = 2
2. b = a ** 2
3. if b < a + 1:
4.    c = 1
5. elif b == 1:
6.    c = 2
7. else:
8.    c = 3
9. print(a+b+c)

9
B

The code gives an error


C

33
D

What will be the output of the following code?

1. x = (1 == True)
2. y = (1 == False)
3. a = True + 5
4. b = False + 20
5.  
6. print("x is", x)
7. print("y is", y)
8. print("a:", a)
9. print("b:", b)

1. x is 1
2. y is 1
3. a: 6
4. b: 20

1. x is 1
2. y is 1
3. a: 6
4. b: 21

1. x is True
2. y is False
3. a: 6
4. b: 21

1. x is True
2. y is False
3. a: 6
4. b: 20
Explanation: 
Answer D is correct.

The following will be the output of the given code:

x is True
y is False
a: 6
b: 20

You are a programmer in the ABC company. You are writing a program to calculate HCF
(highest common factor) of two numbers. You have the following code:

1. def HCF(x, y):


2.     if x > y:
3.         smaller = y
4.     else:
5.         smaller = x
6.     for i in range():
7.         if ():
8.             hcf = i
9.     return hcf
10. n1 = 54
11. n2 = 24
12. print("The H.C.F. of", n1,"and", n2,"is", HCF(n1, n2))

Which two conditions will you use in the range() function of the for statement and in


the if statement?
A

1, smaller+1
B

(x / i == 0) and (y / i == 0)
C
1, smaller
D

(x % i == 0) and (y % i == 0)

You are writing a program in the Python language in which you need to assign values to the
variables using the assignment operator. You have the following code:

1. x = 12
2. y = 5
3. x =+ 5
4. print(x)

You want the output value of the variable 'x' as 17, but on executing the given code, the output
value of the variable comes as 5. What is the issue in the given code?
A

The assignment operator is incorrect in the expression.


B

The value assigned to the variable y is incorrect.


C

The value assigned to the variable x is incorrect.


D

The print statement is incorrect.

What is prefixed to a string when escape sequences are not needed to be handled?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

A
'r' or 'R'
B

'f' or 'F'
C

'e' or 'E'
D

'j' or 'J'

Question 10 :_______ is the process to produce specific data types from the constructors.
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Name mangling
B

Casting
C

Slicing
D

Pickling

Which of the following are the correct rules and naming conventions for variables and constants?

Each correct answer represents a complete solution. Choose all that apply.
A

Always start the name with a digit.


B
Never use special symbols such as !, @, #, $, %.
C

Use camelCase notation to declare a variable.


D

Use capital letters where possible to declare a constant.

Which of the following is prediction of the conditions and specifies the actions to be taken
according to these conditions while execution of a program?

Decision making
B

Serializing
C

Importing
D

Casting

Which of the following escape characters represents hexadecimal notation?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

\x
B

\C-x
C
\cx
D

\xnn

What will be the output of the given code?

1. i = 250
2. while len(str(i)) > 72:
3.     i *= 2
4. else:
5.     i //= 2
6. print(i)

500
B

125
C

125.0
D

250

Which of the following is used to print the letter 'P' from the string s = 'Python'?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

s[2]
B

s[-1]
C

s[1]
D

s[0]

You are a programmer in the ABC company. You are writing a Python program and want that
the program should print the output as the two asterisks in two seperate lines. Which of the
following lines of code will you use for this?
A

for i in range(1, 4, 2):


    print("*",end="**") 
B

for i in range(1, 4, 2):


    print("*", end="**")
print("***")
C

for i in range(1, 4, 2):


    print("*")
D

for i in range(1, 4, 2):


    print("*", end="")

What will be the output of the given Python arithmetic expression?

1. (4*(2+3)**3 - (3**3)*4)

-73
B

392
C

-530941
D

16

Which type of arguments are not named in the function definition?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Default arguments
B

Required arguments
C

Arbitrary arguments
D

Keyword arguments

You are learning Python. You have been taught about the packages in Python. Now, your
instructor wants to test your knowledge and asks a question about the __init__.py files which
are used in packages. Which of the following statements are true about the  __init__.py files? 
A

These files indicate that the directories are containing packages and modules.
B

These files cannot be empty.


C

These files execute the initialization code for the package.


D

These files set the __all__ variable.

What is the use of the help() function in the Python language?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

To determine the usage of docstrings


B

To determine the usage of the whole program


C

To determine the usage of the function


D

To determine the usage of the return statement

In required arguments, at least one argument should be passed otherwise it will give a
___________ error.
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

runtime
B

name
C

syntax
D

type

Which of the following is used to read all the lines of a file, whose file object is 'f', in a list?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

list(f)
B

file.readlines()
C

f.readline()
D

list(file)

Jones is working as a Python developer in an IT company. He has great skills in Python


programming. He wanted to execute a module as script on the command-line prompt. Which of
the following is needed for this purpose?
A

__name__
B

__main__
C

__file__
D

__pycache__

What will be the output of the following code?

1. a = "Python"
2. def x(a,b):
3.     s = a[0]
4.     return s
5.  
6. print(x(a))

The code will give NameError.


B

The code will give TypeError.


C

The code will print 'P'.


D

The code will print 'n'. 

You are working on a Python program. You have to sort a list of fruits in an alphabetical order
using an anonymous function. You have written the following list of fruits:

1. a = ['apple', 'mango', 'banana', 'cherry', 'kiwi', 'orange']

Which code segment will you use for this purpose?


A

sort(key = lambda a:a[0])


B
a.sort(key = lambda a[0])
C

a.sort(key lambda a:a[0])


D

a.sort(key = lambda a:a[0])

Which built-in function returns a sorted list of strings of names defined in a module?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

compileall
B

random
C

dir()
D

__all__

You are a Python programmer in a company. You are writing a program in which you have used
the from...import* statement. What is the purpose of this statement?
A

To execute the module on the command-line prompt


B

To import all names from a module into the current namespace except those


beginning with an underscore
C
To import specific attributes from a module into the current namespace
D

To indicate that the directories are containing packages and modules

What is the correct and complete syntax for a function?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

def functionname(parameters):
function_suite
return [expression]
"function_docstring"
B

def functionname(parameters):
function_suite
"function_docstring"
return [expression]
C

def functionname(parameters):
"function_docstring"
function_suite
return [expression]
D

def functionname(parameters)
"function_docstring"
function_suite
return [expression]

Question 15 :What are the symbols to define the parameter and return annotations in function
annotation?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

A
colon(:), backslash(\)
B

backslash(\), colon(:)
C

colon(:), literal(->)
D

literal(->), colon(:)

Which of the following returns the list of module names that are imported when the from
package import * statement is executed?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

random
B

compileall
C

__all__
D

dir()

Question 19 :The ______ function returns the value representations which can be read by the
interpreter.
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

A
print()
B

read()
C

repr()
D

str()

You are a Python programmer in a company. You are asked to write a program to solve
mathematical problems. You have written the following code:

1. import math
2. n = 100.7
3. print() # put the function here
4. 100

Which two math functions will you use in the print() statement to get the desired output that is
100?
A

math.trunc(n)
B

math.modf(n)
C

math.floor(n)
D

math.ceil(n)
What will be the output of the following code?

1. def double(num):
2.     """Function to double the value"""
3.     return 2*num
4.  
5. print(double.__doc__)

4
B

<function double at 0x000001F938A61E18>


C

Function to double the value


D

TypeError will be generated

Which of the following statements are true of the Python shebang?


 
Each correct answer represents a complete solution. Choose all that apply.
 
A

It is the first statement of a function.


B

It is the first line of a script file.


C

It starts with #!.


D

It is portable between Unix and Windows.


Question 25 :
Tina, an intern, has been recently hired in ASD Inc. She has great skills in the Python
programming language. Tina's trainer in the company wants to check her skills. The trainer
provides her with the following simple output and asks to print it.

1. 1#2#3#4&

Which of the following print statements will Tina use?


A

print(1,2,3,4,sep='&',end='#')
B

print(1,2,3,4,sep='#',end='&')
C

print(1,2,3,4,sep='&',end='')
D

print(1,2,3,4,sep='#',end='')

What will be the output of the following code?

1. n = float(input("Enter the number: "))


2. Enter the number: 8
3. n_sqrt = n ** 0.5
4. print('The square root of %0.3f is %0.3f'%(n ,n_sqrt))

The square root of 8.000 is 2.828.


B

The square root of 8.00 is 2.83.


C

The square root of 8.0000 is 2.8284.


D

The square root of 8.0 is 2.8.

You are a Python programmer. You are writing a program in which the day of the week should
be returned as an integer, where Monday is 0 and Sunday is 6. Which of the following functions
will you use for this purpose?
A

date.isoformat()
B

date.isocalendar()
C

date.weekday()
D

date.isoweekday()

Which of the following statements are the basic rules for a global keyword in the Python
language?
 
Each correct answer represents a complete solution. Choose all that apply.
A

A global keyword is used to read and write a global variable outside a


function.
B

A global keyword is used to read and write a global variable inside a function.
C
By default, a variable created outside a function is global.
D

By default, a variable created inside a function is local.

Roy works as a HR in a company. He wants the details of all the employees present in the
company. He has been provided with a file named employee.txt by a Python programmer
which contains the details of all the employees. Roy has opened the file with the following
Python code:

1. file = open('employee.txt','r')

Now, after opening the file, which of the following line of code should Roy use to see the details
of all the employees?
A

file.read()
B

file.tell()
C

file.seek()
D

file.flush()

You are a Python programmer in a company. You are writing a program using old string
formatting to print the following output:

1. John is 23 years old.

Which of the following will you use for the desired output?
A

print("%s is %0.3f years old." % (name, age))


B

print("%s is %0.3d years old." % (name, age))


C

print("%s is %d years old." % (name, age))


D

print("%s is %f years old." % (name, age))

You are a Python programmer. You are writing a function that works with files. You need to
ensure the following:

 If the file does not exist then the function returns None.
 If the file does exist then the function must return the first line.

Based on the above list, you have written the following incomplete code:

1. import os
2. def get_first_line(filename, mode):
3.     with open(filename, 'r') as file:
4.         if :
5.             return file.readline()
6.         else:
7.             return None

Which of the following will you use to complete the code?


A

os.readlink(path)
B

os.path.isfile(filename)
C

os.listdir(path)
D

os.read(fd, n)

What is the correct code for printing the output "My Name is John Smith" using the format fields
in the str.format() method?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

print('My {0} is {2} {1}'.format('Name', 'John', 'Smith'))


B

print('My {0} is "{1}" {2}'.format('Name', 'John', 'Smith'))


C

print('My "{0}" is {1} {2}'.format('Name', 'John', 'Smith'))


D

print('My {0} is {1} {2}'.format('Name', 'John', 'Smith'))

Which of the following methods is used to create directories in the current directory?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

rmdir()
B

getcwd()
C

mkdir()
D
chdir()

The statement used to break out of the function is:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

continue.
B

pass.
C

return.
D

break.

What will be the output of the following code?

1. import sys
2. sys.ps1

...
B

'... '
C

>>>
D

'>>> '
What will be the output of the following code?

1. drink = None
2. food = 'Available'
3. def menu(x):
4.     if x == drink:
5.         print(drink)
6.     else:
7.         print(food)
8.  
9. menu(drink)
10. menu(food)

NameError will be generated


B

None
Available
C

Not available
Available
D

Available

If there is no argument, then the dir() function returns:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

the list of names of the built-in functions and variables.


B

a syntax error.
C

the list of names from any specified module.


D

the list of names from the current module.

Smith works as a senior Python developer in the UC company. He was working on an urgent
project of the ABC application but due to some health issues, he could not continue his work.
Thus, the project gets transferred to Max, a Python developer. Now, Max wants to know the
current working directory. Which of the following methods will he use for this?
A

mkdir()
B

rmdir()
C

getcwd()
D

chdir()

Question 41 :Which switch is used on the Python command-line to reduce the size of a compiled
module?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

-d
B

-O
C

-S
D

-X

Which of the following keywords is used to declare an anonymous function?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

exec
B

func
C

def
D

lambda

Jack has been recently hired as a Python programmer in a company. He is new to Python
programming. He is asked to work with a Python program which includes docstrings but he is
unable to understand it. Which of the following functions will Jack use to determine the usage of
the docstrings?
A

help()
B

str()
C
dir()
D

format()

Consider the following Python code:

1. f = open('file.txt', 'w')
2. print("Name of the file is" ,f.name)
3. Name of the file is file.txt
4. f.close()
5. f.read()

What will be the output of the given code?


A

The numbers of characters within the file will be returned.


B

The entire content of the file will be returned in a list.


C

A ValueError will be generated.


D

The entire content of the file will be returned.

Which of the following statements is not true of the shebang?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

The shebang is the first line of a script file which starts with #.
B
Python hashbangs are also as known as shebang.
C

The shebang lines in Python scripts are allowed to be portable between Unix
and Windows.
D

The shebang lines can specify the additional options that are to be passed to
the Python interpreter.

Will is recently hired as an intern Python programmer in the UCB company. He is asked to write
a program using Intermezzo coding style guide. Which of the following points should not be
used by him while writing the program?
A

Use tabs for indentation instead of spaces.


B

Use docstrings or documentation strings.


C

Name the classes and functions consistently.


D

Wrap lines of code to avoid exceeding 79 characters.

What is the extension of byte-compiled Python files?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

.pyc
B
.py
C

pyb
D

.pyo

Smith is a Python developer in a company. He is developing an application in which he has


defined a function student_details() with parameters including the details of students. Which
of the following code segments will Smith use to define a valid function?

def student_details(name, age, ID, section="A")


B

def student_details(name= "Jack", age, ID, section="A")


C

def student_details(name, age, ID=6, section)


D

def student_details(name, age=14, ID, section)

Which of the following functions of the random module initializes the random number


generator?
A

random.getrandbits(k)
B

random.setstate(state)
C
random.getstate()
D

random.seed(a=None, version=2)

Question 56 :Which import statement is used to import all names from a module into the current
namespace?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

import module as module_func


B

import module
C

from module import *


D

from module import module_func

Rob, an HR executive of a company, wants to greet all the employees in the company. He asked
the programmer to make a Python program for him for this purpose. The programmer has written
the following code:

1. def greet(*names):
2.     for name in names:
3.         print('Hello', name)
4.  
5. greet('John', 'Jack', 'Rosy', 'Jenny')

What will be the output of the following code?


A
Hello John
Hello Jack
Hello Rosy
Hello Jenny
B

TypeError will be generated


C

Hello John
D

Hello J
Hello o
Hello h
Hello n

You are a Python programmer. You are asked to write a program to get the instructor details of
an institute. You have written the following code:

1. def ins_details(ID, name="Will", age=30, subject="Java"):


2.     print("Name of the instructor is", name)
3.     print("Identity number of the instructor is", ID)
4.     print("Age of the instructor is", age)
5.     print("Subject taught by the instructor is", subject)

Now, you have to call the function ins_details and then print the details. Which of the
following ways of calling functions should not be used for proper execution of the code?
A

ins_details(50, name='Jack')
B

ins_details(40, 'John', 40, 'Python')


C

ins_details(ID=30, name="Rosy")
D
ins_details(50, name='Jim', project="ABC")

Which of the following is defined as a process in which the code in one module is made
accessible to the code present in another module?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Casting
B

Pickling
C

Serializing
D

Importing

Question 60 :The process of converting data hierarchies to string representations is called:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

serializing.
B

name mangling.
C

casting.
D

deserializing.
Which of the following statements are true about inheritance in the Python language?
 
Each correct answer represents a complete solution. Choose all that apply.
A

issubclass(class1, class2) is an example of a function that returns True if


class2 is a subclass of class1.
B

Multiple inheritance means that a class has more than one superclass.
C

Dynamic ordering is used in single inheritance.


D

Inheritance means passing attributes and methods from a superclass to a


subclass.

Question 2 :The acquisition of the features of a main class to other subclasses that are derived
from it is called as:
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Data hiding
B

Polymorphism
C

Inheritance
D
Instantiation

What will be the output of the following code?

1. list = ["apple", "banana", "cherry"]


2. mylist = iter(list)
3.  
4. print(next(mylist))
5. print(next(mylist))
6. print(next(mylist))

['apple', 'banana', 'cherry']


B

a
p
p
C

apple
banana
cherry
D

Traceback (most recent call last):


    File "<stdin>", line 1, in <module>
StopIteration

Consider the following two Python codes:

Example 1:

1. class Person:
2.     def __init__(abc, name, age):
3.         abc.name = name
4.         abc.age = age
5.     def func(abc):
6.         print("My name is",abc.name)
7.         print("My age is",abc.age)
8.  
9. p1 = Person('Jack', 40)
10. p1.func()

Example 2:

1. class Person:
2.     def __init__(self, name, age):
3.         self.name = name
4.         self.age = age
5.     def func(abc):
6.         print("My name is",self.name)
7.         print("My age is",self.age)
8.  
9. p1 = Person('Jack', 40)
10. p1.func()

What will be the output of the given code examples?


A

Only example 1 will give two lines of output.


B

Only example 2 will give two lines of output.


C

Both examples will give same output.


D

Both examples will give an AttributeError.

What will be the output of the following code?


1. def gen():
2.     list = range(5)
3.     for i in list:
4.         yield i*i
5.  
6. for i in gen():
7.     print(i, end="")

0
1
4
9
16
B

0
1
4
9
C

014916
D

0149

Which statement is used by the generators for returning the data?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

pass
B

try
C
return
D

yield

Which of the following is not supported by the Python language?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Private variables
B

Instance variables
C

Object variables
D

Class variables

Jim, a Python developer, is developing an application. He has written the following program
based on Inheritance:

1. class Person:
2.     def __init__(self):
3.         print("Person is ready")
4.     def who(self):
5.         print("Person")
6.     def work(self):
7.         print("Works faster")
8.  
9. class Jack(Person):
10.     def __init__(self):
11.         super().__init__()
12.     def who(self):
13.         print("Jack")
14.     def run(self):
15.         print("Runs faster")
16.  
17. p = Jack()
18. p.who()
19. p.work()
20. p.run()

What will be the output of the given code?


A

Person is ready
Works faster
Runs faster
B

A NameError will be generated.


C

Person is ready
Jack
Works faster
Runs faster
D

Person is ready
Jack is ready
Jack
Works faster
Runs faster

Explanation: 
Answer C is correct.

Question 9 :The optional documentation string of a class can be accessed by what?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

className._doc_
B

className__doc__
C

class.__doc__
D

className.__doc__

Which of the following statements are true of the classes and objects in the Python language?
 
Each correct answer represents a complete solution. Choose all that apply.
A

The class keyword marks the beginning of the class definition.


B

An object cannot contain any references to other objects.


C

A class may define an object.


D

A constructor is used to instantiate an object.

Smith, a Python developer in a company, has written a code for an application based on classes.
He has written the following incomplete code and wants the output of it:

1. class Person:
2.     def __init__(self, name, age):
3.         self.name = name
4.         self.age = age
5.  
6. p1 = Person("Jack", 40)
7. # put the line of code here
8. Jack
9. 40

Which of the following print statements will Smith use to get the output?

Each correct answer represents a complete solution. Choose two.


A

print(p1.age)
B

print(p1.self)
C

print(p1.Person)
D

print(p1.name)

William works as an intern in UC Inc. He has been trained on the Python


language and has asked to write a program based on iterators in which all the
elements of the container must be accessed and reached to the end. He has
written the following incomplete code:

1. n = 'Python'
2. i = iter(n)
3. next(i)

How many times should William write the next(i) method to terminate the


iteration?
A

Five
B

Six
C

Seven
D

Eight
Explanation: 
Answer C is correct.

William should write the next(i) method seven times to terminate the iteration,


as the string n has 6 letters in it. Thus, after writing the
seventh next(i) method, the iteration terminates because it reaches the end
and then no letters were left.

Answers A, B, and D are incorrect. William will write the next(i) method five,


six, or eight times, when the string is different, that is, the string has 4, 5, and
7 letters, respectively.
Lesson: Object Oriented Programming
Objective: Iterator and Generator

The operation in which more than one function is assigned to a particular operator is called as:
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

name mangling.
B

serializing.
C

overloading.
D

pickling.

Which of the following overriding methods is described as a constructor with optional arguments
in Python?
A

__cmp__
B

__init__
C

__del__
D

__str__

Which function is used to access the attribute of an object?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

getattr()
B

hasattr()
C

delattr()
D
setattr()

Consider the following Python code:

1. class MyClass:
2.     """This is my class."""
3.     n = 10
4.     def f(self):
5.         print("Hello World!")
6.  
7. print(MyClass.n)
8.  
9. print(MyClass.f)
10.  
11. print(MyClass.__doc__)
12.  

Which of the following will be the output of the three print statements in the given code?
 
Each correct answer represents a complete solution. Choose three.
 
A

This is my class.
B

Hello World!
C

10
D

<function MyClass.f at 0x000001E704D6B488>


Which of the following statements are true of the Python language?
 
Each correct answer represents a complete solution. Choose three.
A

The __next__() method raises an OverflowError exception.


B

The __iter__() method returns an object.


C

The __init__() function is a class constructor or initialization method.


D

The __doc__ attribute is a valid attribute to return the docstring.

The attributes in a class are prefixed with:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

hash character ( # ).
B

backslash ( \ ).
C

underscore ( _ ).
D

double underscore ( __ ).

Which of the following statements are true of name mangling in Python?


 
Each correct answer represents a complete solution. Choose all that apply.
A

It considers the position of the identifier in the syntax as long as it occurs


within the definition of a class.
B

It allows subclasses to override methods without breaking intraclass method


calls.
C

It is a mechanism of avoiding name clashes in a class with the names defined


by the subclasses.
D

It replaces any identifier of the form __idt with at least two leading
underscores and at most one trailing underscore with _classname__idt, where
classname is the current class name with leading underscores stripped.

Generators are a powerful tool used for creating:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

functions.
B

lists.
C

dictionaries.
D

iterators.
Which of the following statements are true of the built-in issubclass() function in the Python
language?
 
Each correct answer represents a complete solution. Choose two.
A

issubclass(class1, class2) is an example of a function that returns True if


class1 is a subclass of class2.
B

issubclass(class1, class2) is an example of a function that returns True if


class2 is a subclass of class1.
C

It is used to check class inheritance.


D

 It is used to check an instance type.

When there are no elements left in the container, the __next__() method raises __________
exception.
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

SystemExit
B

KeyboardInterrupt
C

RuntimeError
D

StopIteration
Which of the following is the class constructor or initialization method?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

__name__
B

__init__()
C

__main__
D

__doc__

Which of the following built-in functions is used to check class inheritance?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

hasattr()
B

issubclass()
C

isinstance()
D

getattr()

The ______ object is a function without parameters which returns a new instance of the class.
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

empty
B

method
C

instance
D

class

An empty set is created by a:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

parentheses ( () ).
B

curly braces ( {} ).
C

set() function.
D

square brackets ( [] ).
Which of the following is defined as a process in which the code in one module is made
accessible to the code present in another module?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Pickling
B

Casting
C

Importing
D

Serializing

You are a Python programmer. You have to create a program with a function that manipulates a
number. The function should have the following:

 A float can be passed into the function


 The function must take the absolute value of the float
 Any decimal points after the integer must be removed

Based on the given list, which two math functions should you use?
A

math.fabs(x)
B

math.ceil(x)
C

math.frexp(x)
D

math.floor(x)
Jack has been recently hired as a Python programmer in a company. He is new to Python
programming. He is asked to work with a Python program which includes docstrings but he is
unable to understand it. Which of the following functions will Jack use to determine the usage of
the docstrings?
A

format()
B

dir()
C

str()
D

help()

What is the first step for executing modules as scripts?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Execute the module using the import statement at the command-line prompt.
B

Set the __name__ to "__main__".


C

Set the "__main__" to __name__.


D

Execute the module using the import statement at the interpreter.


What is the correct and complete syntax for a function?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

def functionname(parameters):
function_suite
return [expression]
"function_docstring"
B

def functionname(parameters):
function_suite
"function_docstring"
return [expression]
C

def functionname(parameters):
"function_docstring"
function_suite
return [expression]
D

def functionname(parameters)
"function_docstring"
function_suite
return [expression]

The statement used to break out of the function is:


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

return.
B

break.
C

continue.
D

pass.

You are a Python programmer. You are asked to write a code to print the date and time in a
prescribed format. You have written the following incomplete code: 

1. import datetime
2. d = datetime.datetime(2018, 10, 16, 10, 55, 58)
3. # put the line of code here
4. '2018-10-16 10:55:58'

Which of the following code segments will you use to get the desired output?
A

'{:%Y-%m-%d %H:%M:%S}'.format(d)
B

'{:%Y-%d-%m %H:%M:%S}'.format(d)
C

'{:%Y-%d-%m %H:%S:%M}'.format(d)
D

'{:%Y-%m-%d %H:%M:%S}'.format()

John, an HR executive of the WER company, has to create a holiday calendar for the year 2018.
He needs to calculate the number of days for the year and then add holidays. Thus, initially, he
needs to check whether the year 2018 is a leap year. He has written the following code:

1. year = int(input("Enter a year: "))


2. Enter a year: 2018
3. if (year % 4) == 0:
4.     if (year % 100) == 0:
5.         if (year % 400) == 0:
6.             print("{0} is a leap year", format(year))
7.     else:
8.             print("{0} is not a leap year", format(year))
9.     else:
10.         print("{0} is a leap year", format(year))
11. else:
12.     print("{0} is not a leap year", format(year))

The code has some issue, thus not giving the proper output. Which incorrect output will John get
from the code?
A

SyntaxError
B

{0} is not a leap year 2018


C

2018.0 is not a leap year


D

IndentationError

What will be the output of the following code?

1. i = 10
2. while i > 0:  
3.     i -=3  
4.     print("*")
5.     if i <= 3:
6.          break
7. else:
8.     print("*")
A

Three stars
B

Four stars
C

One star
D

Two stars

James is a Python developer in the UCS company. He is asked to make an application to


determine the cost that a customer will have to pay for purchasing the products of the company.
The cost is dependent on the products purchasing duration and its structure which is shown in the
following list:

 The cost of the product is $50.


 If the product is purchased for 3 months, the customer gets 30% off.
 If the product is purchased for 4 to 6 months, the customer gets 50% off.
 If the product is purchased for 7 months and more, the customer gets 80% off.

Based on the above list, he has written the following incomplete code:

1. cost = 50
2. time = int(input("Enter the months for purchasing the product: "))
3. Enter the months for purchasing the product: 6
4. if :
5.     cost = cost * 0.7
6. elif :
7.     cost = cost * 0.5
8. elif :
9.     cost = cost * 0.2
10.  
11. print(cost)
12. 25.0
Which of the following conditions will James use to complete the code?
A

(time = 3), (time > 3) and (time < 6), (time >= 6)
B

(time == 3), (time > 3) && (time <= 6), (time > 6)
C

(time == 3), (time > 3) and (time <= 6), (time > 6)


D

(time = 3), (time > 3) and (time <= 6), (time > 6)

You are a programmer in uCertify. You're working on the list data structure in Python. You have
the following code:

1. list = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b']


2. list.index('a', 4)

What will you get as the output from the given code?
A

4
B

8
C

5
D

6
Which of the following statements are the basic rules for a global keyword in the Python
language?
 
Each correct answer represents a complete solution. Choose all that apply.
A

By default, a variable created inside a function is local.


B

By default, a variable created outside a function is global.


C

A global keyword is used to read and write a global variable inside a function.
D

A global keyword is used to read and write a global variable outside a


function.

What is the method to pad a numeric string on the left with zeros?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

str.zfill()
B

str.ljust()
C

str.rjust()
D

str.center()
You are a Python programmer in a company. You are writing a program in which you have used
the from...import* statement. What is the purpose of this statement?
A

To execute the module on the command-line prompt


B

To import all names from a module into the current namespace except those


beginning with an underscore
C

To import specific attributes from a module into the current namespace


D

To indicate that the directories are containing packages and modules

Which method is used to pair the entries for looping over two or more sequences at the same
time?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

enumerate()
B

zip()
C

sorted()
D

items()

You are working as a Python programmer in a company. You are asked to write a program in
which you have to loop through the dictionaries and at the same time retrieve the key and its
corresponding value. Which of the following looping technique methods will you use for this
purpose?
A

items()
B

zip()
C

enumerate()
D

sorted()

Rob, an HR executive of a company, wants to greet all the employees in the company. He asked
the programmer to make a Python program for him for this purpose. The programmer has written
the following code:

1. def greet(*names):
2.     for name in names:
3.         print('Hello', name)
4.  
5. greet('John', 'Jack', 'Rosy', 'Jenny')

What will be the output of the following code?


A

Hello John
B

Hello J
Hello o
Hello h
Hello n
C

Hello John
Hello Jack
Hello Rosy
Hello Jenny
D

TypeError will be generated

A management executive wants to know the details of the employees. He has been provided with
a Python code by a Python programmer to get the details in desired formatting. The management
executive wants the details in the following format:

1. Name of the employee is Adam Smith.


2. Age of the employee is 40 years.

Which of the following sets of code segments will the management executive use to get the
desired output?
A

print('{1} of the employee is {2} {}.'.format('Name', 'Adam', 'Smith'))


print('{Name} of the employee is {Adam} {Smith}.'.format(Name = "Age", Adam = 40,
Smith = "years"))
B

print('{0} of the employee is {1} {2}.'.format('Name', 'Adam', 'Smith'))


print('{Name} of the employee is {Adam} {Smith}.'.format(Name = "Age", Adam = 40,
Smith = "years"))
C

print('{0} of the employee is {1} {2}.'.format('Name', 'Adam', 'Smith'))


print('{Name} of the employee is {Adam} {Smith}.'.format(Name = "age", Adam = 40,
Smith = "years")) 
D

print('{0} of the employee is {1} {2}.'.format('Name', 'Adam', 'Smith'))


print('{Name} of the employee is {Adam} {Smith}.'.format(Name = "Age", Adam = 40,
Smith = years))

Explanation: 
Answer B is correct.

The management executive will use the following set of code segment to get
the desired output:
print('{0} of the employee is {1} {2}.'.format('Name', 'Adam', 'Smith'))
print('{Name} of the employee is {Adam} {Smith}.'.format(Name = "Age", Adam = 40,
Smith = "years"))

In the above code, the first print statement is using the format fields in which a
number is mentioned in the brackets to refer to the position of the object
passed and the second print statement is using the keyword arguments in
which the values are referred by the name of the arguments in
the str.format() method.

You are a Python programmer in an inventory company. You are asked to write a program to
automate inventory. Your first task is to read a file named inventory.txt which contains the
item id, price, and quantity from the previous day. The following is the data from the file:

1. 100, 200, 5
2. 20, 100, 1

Now, the program must meet the following requirements:

 Each line of the file must be read and printed.


 If a blank line is encountered, it must be ignored.
 When all lines have been read, the file must be closed.

Based on the given list, you create the following code:

1. inventory = open("inventory.txt", 'r')


2. eof = False
3. while eof == False:
4.     line = inventory.readline()
5.     # put the lines of code here
6.  
7.             print(line)
8.     else:
9.         print("End of file")
10.         eof = True
11.         inventory.close()

Which of the following lines of code will you use?


A

if line != '\n':

    if line != "":   
B

if line != ' ':

    if line != " ":    


C
if line != '\n':

   if line != None:  


D

if line != ' ':

    if line != "\n":   

Question 29 :Which of the following is a mutable date type?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

List
B

Number
C

String
D

Tuple
Which of the following keywords is used to declare an anonymous function?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

lambda
B

def
C

func
D

exec

Question 31 :Which popular data interchange format is used in Python to save a list in a file?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

os
B

filecmp
C

io
D

JSON
What is the issue in the following code?

1. name = ['jack', 'john', 'jacob']


2. for i in name:
3.     if len(i) < 5:
4.         name.insert(0,i)

An IndentationError is generated.
B

A SyntaxError is generated.
C

An infinite list is created by inserting 'jack' over and over again.


D

An infinite list is created by inserting 'jacob' over and over again.

Which of the following statements is not true of the shebang?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Python hashbangs are also as known as shebang.


B

The shebang is the first line of a script file which starts with #.
C

The shebang lines can specify the additional options that are to be passed to
the Python interpreter.
D

The shebang lines in Python scripts are allowed to be portable between Unix
and Windows.
Which of the following data structures removes the duplicate items from it?
A

Set
B

Tuple
C

List
D

Dictionary

Which module is used to create .pyc files for all modules in a directory?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

compileall
B

__all__
C

dir
D

random

Which module is used for almost the same purpose as JSON in the Python language?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

pickle
B

winreg
C

os
D

io

Which of the following data types is a collection which is unordered and unindexed and allows
no duplicate members in the Python language?
A

Dictionary
B

Set
C

Tuple
D

List

You are an instructor of the Python language. You are teaching your students about the loops in
Python which included some important points on the infinite loop. Which of the following points
should be followed to avoid the infinite loop in a while statement?
A
Always remember to put a colon at the end of the while statement.
B

Always remember to keep one while statement inside the other.


C

Always remember an expected indentation in a while statement.


D

Always remember to increment or decrement the variable.

Smith is a Python developer in a company. He is developing an application in which he has


defined a function student_details() with parameters including the details of students. Which
of the following code segments will Smith use to define a valid function?

def student_details(name= "Jack", age, ID, section="A")


B

def student_details(name, age, ID, section="A")


C

def student_details(name, age=14, ID, section)


D

def student_details(name, age, ID=6, section)

You are a Python programmer in a company. You are writing a program using old string
formatting to print the following output:

1. John is 23 years old.

Which of the following will you use for the desired output?
A

print("%s is %f years old." % (name, age))


B

print("%s is %0.3f years old." % (name, age))


C

print("%s is %0.3d years old." % (name, age))


D

print("%s is %d years old." % (name, age))

Which of the following argument types can only be passed at the end of the parameter list?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Required arguments
B

Default arguments
C

Keyword arguments
D

Arbitrary arguments

What is the return type of the locals() function?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

A
Dictionary
B

List
C

Set
D

Tuple

You are a Python developer in your company. You are developing an application in which you
have to use some identifiers. Which of the following identifiers will you use according to the
identifer naming conventions of the Python language?
A

_myfunc
B

my func
C

my-func
D

2func

You are a student in Python programming classes at the XYZ institute. Your instructor has asked
you a question on the reserved keywords in Python. Which of the following is used as a keyword
for returning the data used by the generators?
A

import
B

yield
C

pass
D

return

Judy, a Python programmer in a company, wants to slice a string from the beginning until the
first vowel is encountered in the string. He has the following string:

1. a = 'python'

Which of the following code segments will Judy use?


 
Each correct answer represents a complete solution. Choose two.
A

a[:4]
B

a[4:]
C

a[-2:]
D

a[:-2]

You are a beginner in the Python language. You have learned about data type conversion in
Python. You have written a program of division of variables whose output is coming in
the int() data type but you want the output in the float() data type to get more acurrate result.
Which of the following processes will you perform to convert the int() data type to
the float() data type?
A

Importing
B

Casting
C

Name mangling
D

Serializing

Consider the following Python code:

1. fruit = ['apple']
2. print(len(fruit))

What will be the output of the given code?


A

NameError will be generated


B

5
C

1
D

You are a beginner in Python. You want to set the path at Unix/Linux. You have to add the
Python directory to the path for a particular session in the csh shell. Which of the following is the
correct step for setting the path?
A

Type PATH="$PATH:/usr/local/bin/python" and press Enter.


B
Type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
C

Type export ATH="$PATH:/usr/local/bin/python" and press Enter.


D

Type "C:\Python36\" and press Enter.

What is the first Unix Integrated Development Environment for Python?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

NetBeans
B

Eclipse
C

PythonWin
D

IDLE

Which of the following are the correct rules for writing identifiers?
 
Each correct answer represents a complete solution. Choose all that apply.
 
A

An identifier can be of any length.


B

Keywords cannot be used as identifiers.


C

Identifiers can be a combination of letters, digits, and an underscore (_).


D

An identifier can start with a digit or letter.

You are a Python developer in a company. You are asked to develop a program which gives the
birth year of the user as an output. You have been given the following code:

1. year = 2018
2. age = 25
3. # put your line of code here
4. print(birth_year)

You have to complete the code to execute it. Which line of code will you use for this purpose?
A

birth_year = str("year") - str("age")


B

birth_year = int("year") - int("age")


C

birth_year = eval(year) - eval(age)


D

birth_year = eval("year") - eval("age")

You are a programmer working on the Python language. You are asked to write a program in
such a way so that you can explain it in brief to the tester of the program. Which of the following
will you use to explain the program to the tester?
A
Comments
B

Quotations
C

Multi-line statements
D

Indentation

You are an intern in the coding team of the ABC company. You are working on the Python
language to create a commercial application. You have to create a script that asks the user for a
value which is always used as a whole number, even if the user enters a decimal value. Which
code segment should you use?
A

value = input("Enter the value:")


B

value = int(input("Enter the value:"))


C

value = float(input("Enter the value:"))


D

value = str(input("Enter the value:"))

Which of the following is a Python identifier name?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

2name
B
_myname
C

my name
D

my-name

You are a Python developer in a company. You are asked to work on a code based on the
comparison operator in Python and find out the output. You have the following code:

1. x = "20"
2. y = "30"
3. print(x>y)

What output will you get from the code?


A

2030
B

True
C

False
D

The code will give an exception

You are a Python programmer. You are asked to write a program to perform arithmetic
operations in such a way that the decimal points are truncated. You have declared the following
variables:
1. a = 18
2. b = 5

Which code segments will you use to print the desired result?
 
Each correct answer represents a complete solution. Choose all that apply.
A

print(float(a/b))
B

print(a/b)
C

print(a//b)
D

print(int(a/b))

You are a Python instructor at the ABC institute. You have to test the knowledge of your
students about the precedence of the operators and expressions in Python. You have provided the
following code to them and asked a question based on it:

1. def func(v, w, x, y, z):


2.     value = v + w * x - y / z
3.     return value

Which part of the expression will be evaluated first?


A

w*x
B

x-y
C

y/z
D
v+w

You are a beginner in the Python language. You have learned about the bitwise operator and
have decided to check your knowledge. You have the following code:

1. x = 12
2. y = 5
3. # Put your line of code here
4. print(result)

You want the output as 12, which is the value of the 'result' variable. Which line of code will you
use for the desired result?
A

result = (x & y)
B

result = (x & y & ~y)


C

result = (x | y & ~y)


D

result = (x ^ y)

Which of the following is not a reserved keyword in Python?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

open
B

return
C
yield
D

import

You are a Python instructor. You have to test the students on your class of identifiers in Python.
You have asked a question based on the identifier naming convention in Python. Which of the
following conventions is not applicable for creating an identifier in Python?
A

The first character of the identifier must be a digit (0-9).


B

The rest of the identifier name can consist of letters and underscores ( _ ).
C

The first character of the identifier must be an alphabet or an underscore ( _ ).


D

Identifier names are case-sensitive.


What is the correct type operation for float in Python?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

type("True")
B

type(5j)
C

type(5)
D

type(+1e10)
You are a student and learning the Python language. Your instructor has asked you a question
about a string to check your knowledge. What are the two correct ways that you will use to span
multiple lines in a string?
A

Triple quotes are used around the lines.


B

A hash character is used at the last of the line.


C

A backslash character is used at the last of the line.


D

Double quotes are used around the lines.

You are a Python programmer in a company. You are writing a program in which you are also
asked to add some notes for the reader of the program. Which of the following code segments
will you use for this purpose?
A

a = 10 // value assigned to a variable 'a'


B

a = 10 -- value assigned to a variable 'a'


C

a = 10 ! value assigned to a variable 'a'


D

a = 10  # value assigned to a variable 'a'


Which of the following commands is used to build Python libraries, while installing Python on
Unix/Linux?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

make
B

make install
C

./configure
D

mkdir

Which of the following expressions gives the output as 5?


A

eval('2+3')
B

float('2+3')
C

int('2+3')
D

str('2+3')

Which of the following are used for grouping in the Python expression?
A
Square brackets
B

Parentheses
C

Quotations
D

Curly braces

Which of the following are the correct rules and naming conventions for variables and constants?

Each correct answer represents a complete solution. Choose all that apply.
A

Use camelCase notation to declare a variable.


B

Never use special symbols such as !, @, #, $, %.


C

Always start the name with a digit.


D

Use capital letters where possible to declare a constant.

You are learning the Python language. Your instructor has asked you a question based on the
slicing of strings. You have been provided with the following string:

1. s = 'Python'

Which two code segments will you use to get the output 'Python'?
A
s[:2] + s[2:]
B

s[:3] + s[2:]
C

s[:3]
D

s[:]

You are an expert in the Python language. You are asked to explain some basic programming
concepts to the beginners. You have to introduce the concept of data types in Python. You have
created the following code segment as an example to explain the concept:

1. x = "20"
2. y = 3
3. a = x * y
4. type(a)

After executing the code segment, which of the following data types will you get as a result?
A

float
B

int
C

complex
D

str
You are a Python programmer. You are asked to write a code in a program which results 'Python'
from the string s = "This is Python language". Which of the following code segments will
you use to get the desired output?
A

s[9:14]
B

s[10:14]
C

s[8:14]
D

s[7:14]

What will be the output of the following code?

1. x = (1 == True)
2. y = (1 == False)
3. a = True + 5
4. b = False + 20
5.  
6. print("x is", x)
7. print("y is", y)
8. print("a:", a)
9. print("b:", b)

1. x is 1
2. y is 1
3. a: 6
4. b: 21
B

1. x is 1
2. y is 1
3. a: 6
4. b: 20

1. x is True
2. y is False
3. a: 6
4. b: 20

1. x is True
2. y is False
3. a: 6
4. b: 21

You are writing a program in the Python language in which you need to assign values to the
variables using the assignment operator. You have the following code:

1. x = 12
2. y = 5
3. x =+ 5
4. print(x)

You want the output value of the variable 'x' as 17, but on executing the given code, the output
value of the variable comes as 5. What is the issue in the given code?
A

The assignment operator is incorrect in the expression.


B
The print statement is incorrect.
C

The value assigned to the variable x is incorrect.


D

The value assigned to the variable y is incorrect.

Question 54 :_______ is the process to produce specific data types from the constructors.
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Pickling
B

Name mangling
C

Casting
D

Slicing

Judy, a Python programmer in a company, wants to slice a string from the beginning until the
first vowel is encountered in the string. He has the following string:

1. a = 'python'

Which of the following code segments will Judy use?


 
Each correct answer represents a complete solution. Choose two.
A
a[-2:]
B

a[:-2]
C

a[:4]
D

a[4:]

Jim is an application developer in XYZ company. He is asked to create an application based on


the Python language in which the sqrt function is used. The program must reference the
function using the name squareRoot and he has to import the function. Which code segment will
Jim use?
A

from math import sqrt as squareRoot


B

from math.sqrt as squareRoot


C

import math.sqrt as squareRoot


D

import sqrt from math as squareRoot

Question 5 :In the Python language, a function block begins with a/an:
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

documentation string.
B
def keyword.
C

identifier name.
D

func keyword.

Which module in the Python language provides methods to perform file-processing operations?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

filecmp
B

pickle
C

os
D

io

You are a Python programmer. You are asked to write a program to get the student details of a
school. You have written the following code:

1. def student_details(ID, name="Nancy", age=14,


section="A"):
2.     print("Name of the student is", name)
3.     print("Identity number of the student is", ID)
4.     print("Age of the student is", age)
5.     print("Section of the student is", section)
6.  
7. d = {'ID': 1, 'name': 'Jack', 'age': 16, 'section': 'B'}

You have to call the function student_details and then print the details. Which of the
following ways of calling functions will you use for this purpose?
A

student_details(*d)
B

student_details(**d)
C

student_details()
D

student_details(d)

Which of the following conventions does not help to avoid the generated errors, while calling the
functions?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

The keyword arguments must follow positional arguments in calling a function.


B

Each argument defined in the function must match with more than one of the
keyword arguments passed in the function.
C

The keyword arguments can also include non-optional arguments.


D

All the arguments must receive a value only once.


You are an intern Python programmer in a company. Your trainer has asked you to write a
program using arbitrary argument lists in a function. Which of the following arguments will you
use after the arbitrary arguments in a function?
A

Keyword arguments
B

Positional arguments
C

Required arguments
D

Default arguments

Question 27 :What is the advantage of using the with keyword to open a file?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

The file is properly closed after its set finishes even if an exception is raised at
some point of execution.
B

The file is properly read and executed.


C

The file is properly opened for both reading and writing automatically.
D

The file is properly opened at the beginning.

What will be the output of the following code?


1. s = 5
2. a = lambda s: 1 + 2
3. print(a(s))

3
B

5
C

6
D

What is prefixed to a string when the output is formatted using the formatted string literals?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

'r' or 'R'
B

'j' or 'J'
C

'e' or 'E'
D

'f' or 'F'

Which environment variable consists of a list of directories?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Local
B

Global
C

PATH
D

PYTHONPATH

What will the following command return on execution?

f.write("Python is an object-oriented language")

This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

Python is an object-oriented language


B

36
C

"Python is an object-oriented language"


D

37
What will be the output of the following code?

1. import math
2. print(f'The value of pi is {math.pi:.2f}.')

The value of pi is 3.14.


B

The value of pi is 3.142.


C

The value of pi is 3.1.


D

A ValueError will be generated.

Which of the following is the last step in the sequence for finding the module search path?
A

It searches the default search path which is stored in the system module sys
as the sys.path variable.
B

It searches each directory in the shell variable PYTHONPATH.


C

It searches for a file with the same name in a list of directories given by the
variable sys.path.
D

It searches for a built-in module with the same name


You are working as a Python programmer in a company. You are asked to write a program in
which you have to define a function. Which of the following will you use as the first statement in
a function which makes the program easier to understand?
A

The function suite of the function


B

The documentation string of the function


C

The def keyword followed by the function name and parentheses


D

The return statement of the function

Jack is recently hired as a Python developer in a company. His trainer in the company wants to
test his knowledge and asks a question about modules. Which of the following functions will he
use to find out the names that are defined in random module?
A

random.getrandbits(k)
B

str()
C

dir()
D

random.getstate()
Which of the following methods is used in looping through the dictionaries?
This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

enumerate()
B

zip()
C

sorted()
D

items()

As a Python developer of your company, you have to create an application in which the names of
all the employees are to be displayed excluding the management team.

You have created a list named employees which contains 200 employee names. The first 10
employee names are of the management team in the list. You need to slice the employees list to
display all employee names excluding the management team.

Which code segments will you use to accomplish the task?


 
Each correct answer represents a complete solution. Choose two.
A

employees[:10]
B

employees[:-190]
C

employees[-190:]
D

employees[10:]
John is recently hired as an intern in the Python programming team. His trainer wants to check
his basic knowledge. He has provided John with the following code and then asked a question:

1. details = 'john', 1993, 10, 'Williams'


2. print(details)

Which of the following data types will be created on printing the given details?
A

String
B

Dictionary
C

Tuple
D

List

In which of the following statements is a null operation executed?


This task contains the radio buttons and checkboxes for options. The shortcut keys to perform
this task are A to H and alt+1 to alt+9.

break
B

pass
C

continue
D

else

You might also like