Font size
Worksheetspython quizz Coding club 1
Total questions: 143
Worksheet time: 1hrs 9mins
What are the basic data types in Python?
char, float, array, dict
int, float, str, bool, array, dict
int, float, str, bool, list, tuple, set, dict
int, float, str, boolean, list, tuple
How do you declare a variable in Python?
You declare a variable in Python by using the syntax: variable_name = value.
variable_name : value
let variable_name = value
set variable_name to value
What is the difference between a list and a tuple?
A list can only contain numbers, while a tuple can contain any data type.
A list is defined with {}, while a tuple is defined with []
A list is mutable and defined with [], while a tuple is immutable and defined with ().
A list is immutable and defined with [], while a tuple is mutable and defined with ().
Explain the use of 'if', 'elif', and 'else' statements.
'if' checks a condition, 'elif' checks additional conditions, and 'else' executes if all previous conditions are false.
'if' always executes, 'elif' is optional, and 'else' is mandatory.
'if' checks for errors, 'elif' is for debugging, and 'else' is for logging.
'if' is used for loops, 'elif' is for functions, and 'else' is for imports.
What is a for loop and how is it used in Python?
A for loop is used to define functions in Python.
A for loop is a type of variable in Python.
A for loop is a method for creating classes in Python.
A for loop is a control flow statement that allows code to be executed repeatedly for each item in a sequence.
How do you define a function in Python?
function_name(parameters) =>
create function_name(parameters)
function_name: parameters()
def function_name(parameters):
What is the purpose of the 'return' statement in a function?
The purpose of the 'return' statement is to provide a value from a function to its caller.
To define the function's parameters.
To end the function execution immediately.
To create a loop within the function.
How can you import a module in Python?
Modules can be imported with 'include module_name'.
Import modules using 'load module_name'.
Use the 'import' statement, e.g., 'import module_name'.
Use the 'require' statement, e.g., 'require(module_name)'.
What is the difference between reading and writing a file in Python?
Reading creates data while writing deletes data.
Writing retrieves data from a file.
Reading and writing are the same process.
Reading retrieves data from a file, while writing modifies or creates data in a file.
How do you handle exceptions in Python?
Use try-except blocks to handle exceptions in Python.
Use print statements to debug exceptions in Python.
Ignore exceptions and continue execution.
Use if-else statements to handle exceptions in Python.
What is the purpose of the 'try' and 'except' blocks?
To define functions in Python
To create loops in Python
The purpose of 'try' and 'except' blocks is to handle exceptions and errors in a controlled manner.
To import libraries in Python
Explain the concept of classes in Object-Oriented Programming.
A class in OOP is a blueprint for creating objects, defining attributes and methods.
A class is a method used to manipulate data.
A class is a function that executes code.
A class is a type of variable that holds data.
What is inheritance in Python?
Inheritance in Python is a mechanism where a new class derives properties and behavior from an existing class.
Inheritance is a way to create multiple classes without any relationship.
Inheritance in Python is a method to delete classes from memory.
Inheritance allows a class to inherit only methods, not properties.
How do you create an instance of a class?
Use the class name followed by a semicolon, e.g., 'instance = ClassName;'
Instantiate a class by calling its method directly, e.g., 'instance = ClassName.method()'
Create an instance using the class name without parentheses, e.g., 'instance = ClassName'
Use the class name followed by parentheses, e.g., 'instance = ClassName()'.
What is the purpose of the '__init__' method?
To initialize an object's attributes when creating an instance of a class.
To define a class method for inheritance.
To create a new class in Python.
To execute code when a class is defined.
How can you read a text file line by line in Python?
Use 'open("filename.txt") as file: read(file)' to read the entire file at once.
Use 'open("filename.txt") and file.readlines()' to read lines without a loop.
Use 'file.read_lines()' to read all lines in a list.
Use 'with open("filename.txt") as file: for line in file: print(line)'.
What is the difference between 'open()' with 'r' and 'w' modes?
'w' mode is for appending data to existing files.
The difference is that 'r' mode is for reading (no write access), while 'w' mode is for writing (overwrites existing files or creates new ones).
'r' mode allows both reading and writing.
Both modes create new files if they don't exist.
How do you raise an exception in Python?
raise Exception()
raise Exception('Error message')
throw Exception('Error message')
raise 'Error message'
What is polymorphism in Object-Oriented Programming?
Polymorphism is the ability of different classes to be treated as instances of the same class through a common interface.
Polymorphism is the method of hiding the implementation details of a class.
Polymorphism is the ability to create multiple instances of a class.
Polymorphism refers to the process of combining multiple classes into one.
How can you check the type of a variable in Python?
Use the 'instance()' function.
Use 'get_type()' method.
Use the 'type()' function.
Check the variable with 'var_type()'.
What is the purpose of the 'self' parameter in class methods?
'self' is a placeholder for the class name itself.
'self' is used to create static methods in a class.
'self' is a keyword used to define global variables.
'self' refers to the instance of the class and is used to access variables that belong to the class.
What is a dictionary in Python?
A dictionary is a collection of key-value pairs, where each key is unique.
A dictionary is a type of list that can hold multiple data types.
A dictionary is a method for defining functions in Python.
A dictionary is a way to store data in a sequential manner.
How do you create a virtual environment in Python?
Virtual environments are created automatically when you install Python.
Use 'create env_name' command to set up a virtual environment.
Use 'env_name = virtual()' to create a virtual environment.
Use the command 'python -m venv env_name' to create a virtual environment.
What are the three main programming structures?
Sequence, selection, iteration
Structured, object-oriented, procedural
Java, Python, Visual Basic
Machine, assembly, high-level
Yes
In a Python program , a control structure:
directs the order of execution of the statements in the program
dictates what happens before te program starts and after it terminates
defines program-specific data structures
manages the input and output of control characters
What is the output of the above program ?
Am I here?
Or here ?
Am I here ? Or here ?
Or here ? Or over here ?
If the user inputs : 2<Enter> , what does the following code snippet print ?
Yes
No
May be
Nothing printed
Error
Function range(3) is equivalent to "
range(1,3)
range(0,3)
range(0,3,1)
range(1,3,0)
What is the output?
condition
True
Program has a syntax error.
3 > 2
What is the output?
more than 7
more than 23
spam
7
What is the output?
3
3
7
3
5
7
7
What is the output?
True
NIL
True
NIL
True
NIL
NIL
What is the output?
level 3
level 3
level 1
level 3
level 1
NIL
level 3
level 2
level 1
NIL
An If statement can be executed multiple times
FALSE
TRUE
The ‘else’ statement is optional in Python
TRUE
FALSE
It is possible to execute both the statements under if and else at the same time.
TRUE
FALSE
There can be an else statement without an if statement
FALSE
TRUE
The program generates an error message if the "else" statement is not defined
FALSE
TRUE
Python supports (a) types of loops
What is the output?
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
......(repeated continuously)
What is the output if the user types "Python"?
Why was Python (TM) developed?
To go back to the old way of programming
To create a programming language for students in grade school
To make it easier to learn Java
Python was developed by accident
Python (TM) is owned and managed by
Microsoft (c)
Sun Microsystems (c)
Python (TM) is open source and free to use
Google (c)
Python is ___________ level programming language and is ___________.
High, compiled
High, interpreted
Low, compiled
Low, interpreted
Generally speaking, a low level programming language is easier to read, write and maintain over a high level programming language
True
False
The syntax in Python (TM) is one of the main advantages over other high level programming languages.
True
False
A statement in programming
Expresses an action to be carried out
Always returns results like expressions
Rules controlling how components in a program are combined
An instruction to perform a task, usually one word
A string
carries out an action
the elements of a command
a collection of characters
how elements in a commad are arranged
A block is
a statement including elements of a command
the structure and form of the code
source code that is grouped together
meaning assigned to symbols, characters and words
What symbol comes before a comment?
$
>>
#
!
An exception is
the structure of form of the code
the meaning of the characters and words in the code
the statement that is missing from the instructions
an event occurring during execution of a program which disrupts the flow of the program's instructions
Debugging is
how characters are arranged in a statement
detecting or removing errors from a program
removing viruses from a computer
the meaning of each of the characters and symbols in the program
A disadvantage of Python is it is harder to debug than other higher level programming languages.
True
False
In programming, a (n) _______________ is a value that can change, depending on conditions or on information passed to the program
string
block
instruction
variable
Generally speaking Python (TM) would run _____________ than C++ and take ____________ time to create
faster, less
faster, more
slower, less
slower, more
Since Python (TM) is open source,
Support for using Python (TM) is easy to find
It is free
There is a large catalog of supporting documents
it is a less powerful programming languange
Predict the output of the following code:
x=3
If x>2 or x<5 and x==6:
Print(“ok”)
else:
print(“no output”)
ok
okok
no output
none of above
Which one of the following if statements will not execute successfully?
1) if (1, 2);
print(‘foo’)
2) if (1, 2):
print(‘foo’)
3) if (1):
print( ‘foo’ )
4) if (1);
print( ‘foo’ )
1,4
2
2,4
4
Find the output of the following program segments:
for i in range(20,30,2):
print(i)
20 22 24 26 28
20
22
24
26
28
20 22 24 26 28 30
20
22
24
26
28
30
Which one of the following is incorrect?
The variables used inside function are called local variables.
The local variables of a particular function can be used inside other functions, but these cannot be used in global space.
The variables used outside function are called global variables
In order to change the value of global variable inside function, keyword global is used.
Suppose a function called add() is defined in a module called adder.py. Which of the following code snippets correctly show how to import and use the add() function? Select all that apply.
from adder import add
result = adder.add(2, 3)
from adder import add
result = add(2, 3)
import add from adder
result = add(2, 3)
import adder
result = adder.add(2, 3)
What is the output of the given below program?
print("Know Program".split())
‘Know’, ‘Program’
(‘Know’, ‘Program’)
[‘Know’, ‘Program’]
{‘Know’, ‘Program’}
Find the output of the given Python program?
print(list("abcd".split('')))
[‘a’, ‘’, ‘b’, ‘’, ‘c’, ‘*’, ‘d’]
[‘a’, ‘b’, ‘c’, ‘d’]
[‘abcd’]
[‘abc*d’]
What will be the output of the following Python code?
a={1:"A",2:"B",3:"C"}
a.items()
items()
dict_items([(1,2,3)])
dict_items([(‘A’), (‘B’), (‘C’)])
dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])
Which of the following is correctly evaluated for this function?
pow(x,y,z)
(x**y) / z
(x / y) * z
(x**y) % z
(x / y) / z
Which one of the following syntaxes is the correct syntax to read from a simple text file stored in ''d:\java.txt''?
Infile = open(''d:\\java.txt'', ''r'')
Infile = open(file=''d:\\\java.txt'', ''r'')
Infile = open(''d:\java.txt'',''r'')
Infile = open.file(''d:\\java.txt'',''r'')
Your Mindset Right now
Create a variable named bike and assign the value Kawasaki H2R to it
bike= Kawasaki H2R
"bike" = Kawasaki
H2R bike= "Kawasaki H2R"
"KawasakiH2R"= bike
Create a variable named x and assign the value of integer 50 to it
x="50"
x: 50
"x"=50
x=50
Display the sum of 5 + 10, using two variables: x and y
x=y y = 10
print(x +y)
x=5 y = x
print(x +y)
x=10 y =5
print(x +y)
x=5 y =10
print(x +y)
Select the illegal variable name
2my-first_name = "John"
my-firstname = "John"
__my-first_name = "John"
my2-first_name = "John"
What is used to print the length of a string
len()
length()
type.legth()
fulllength()
What can we use to get the first character of a string txt= "Banana"
x=txt(0)
x=txt(1)
x=txt[0]
x=txt[1]
What can we use to get the characters from index 2 to index 4 (llo) in txt = "Hello, World"
Options
x= txt[2:4]
x= txt[1:4]
x= txt[2:5]
x= txt[2:6]
Select the right syntax for the if condition
a=10 b=20 if a is greater than b: print("Hello World")
a=10 b=20 if a>b: print("Hello World")
a=10 b=20 if a>b; print("Hello World")
Fill in the blank if a> b: print("True") _____: print("False")
otherwise:
then:
else:
elif:
Select the right syntax to create a function called my_function
def my_function:
define my_function:
func my_function;
create funct my_function;
Inside a function with two parameters, print the first parameter. def my_function(fname, lname): print(________)
my_function
fname
lastname
lname
What will be the output of the following program: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": print(x)
cherry
apple
apple cherry
banana
The following code will stop the loop if i is 3 Fill in the blanks to perform the same i = 1 ______ i < 6: if i == 3: break i += 1
do while
for
if
while
What will be the output for the following code: for x in range(6): print(x)
0 1 2 3 4 5 6
1 2 3 4 5 6
0 1 2 3 4 5
1 2 3 4 5
What is a library in python?
COLLECTION OF FILES
COLLECTION OF MODULES
IT IS SUBPROGRAM
NAME OF A FILE
exp(),floor()belongs which module?
cmath.py
urlib.py
math.py
statistics.py
What will be the output of the following
from import factorial
print(math.factorial(5))
25
10
120
error bcz factorial is not a module in math
Which of the statements is used to import all names from a module into the current calling module
import
from
dir()
import*
Suppose a function called add() is defined in a module called adder.py. Which of the following code snippets correctly show how to import and use the add() function? Select all that apply.
import add from adder
result = add(2, 3)
from adder import add
result = add(2, 3)
from adder import add
result = adder.add(2, 3)
import add
result = adder.add(2, 3)
This code is equivalent to
random.randint(1,11)
random.randint(1,10)
random.randrange(1,11,1)
random.randrange(1,10,1)
Name the keyword used to define a function.
define
def
function
fu
Which one is not true about function?
It breaks the large program into small modules.
It avoids repetition.
It makes code reusable.
It makes the program unorganized.
(a) which function helps to display all information including docstring ,function name and constant in a module.
random.randrange(6)
0,1,2,3,4,5,6
1,2,3,4,5,6
0,1,2,3,4,5
1,2,3,4,5
random.randint(3,8)
4,5,6,7
3,4,5,6,7
3,4,5,6,7,8
0,1,2,3,4,5,6,7,8
random.random() generates a floating point number between _____ and ______
1 and 2
1 and 0
0 and 1
0 and 10
Which function truncates the fractional part of given number and returns only the integer or whole part.
int()
round()
oct()
hex()
docstrings
single quoted comments
double quoted comments
triple quoted comments
hash tagged comments
What will be the output of the following Python code?
def cube(x):
return x * x * x
x = cube(3)
print (x)
9
3
27
30
What are the two main types of functions?
Custom function
Built-in function & User defined function
User function
System function
What is the purpose of the 'init' method in a Python class?
'init' is a built-in function for error handling.
'init' is used to initialize the attributes of a class instance.
'init' is a method that creates a new class.
'init' is used to define static variables in a class.
How do you handle exceptions in Python?
Exceptions cannot be handled in Python.
Use 'catch' to handle exceptions.
Use 'try' and 'except' blocks to catch exceptions.
Use 'error' to manage exceptions.
What is the output of the following code snippet: print(type([]))?
set
tuple
dictionary
list
What keyword is used to define a function in Python?
method
def
function
func
What symbol is used to pass an arbitrary number of arguments to a Python function?
**
++
*
&
In Python, what does the 'return' statement do in a function?
Exits the function
Deletes the function
Calls another function
Returns a value
Which of the following is a correct way to call a function named 'my_function'?
execute my_function()
call my_function()
my_function[]
my_function()
How do you define a function that takes two parameters, 'fname' and 'lname'?
function my_function(fname, lname)
my_function(fname, lname)
def my_function(fname, lname)
def my_function: fname, lname
What is the correct syntax to return the fourth element in a list named 'fruits'?
fruits[4]
return fruits[3]
fruits.get(4)
return fruits(4)
Which method would you use to add an item to the end of a list named 'items'?
list.add(items, item)
items.append(item)
items.add(item)
items.push(item)
What is the correct way to handle exceptions in Python?
error...catch
try...except
try...catch
do...while
Which of the following is a valid for loop in Python?
loop x in range(5)
for x = 0; x < 5; x++
for x to 5
for x in range(5)
What is the correct syntax for defining a class named 'Vehicle'?
class Vehicle:{}
class Vehicle()
class Vehicle:
class Vehicle[]
If list=[17,23,41,10] then list.append(32) will result
[32,17,23,41,10]
[17,23,41,10,32]
[10,17,23,32,41]
[41,32,23,17,10]
Which of the following python function can be used to add more than one element within an existing list ?
append( )
append_more( )
extend( )
more( )
Please select all correct ways to empty the following dictionary
student = {
"name": "Emma",
"class": 9,
"marks": 75
}
del student
del student[0:2]
student.clear()
Select correct ways to create an empty dictionary
sampleDict = {}
sampleDict = dict()
sampleDict = dict{}
Items are accessed by their position in a dictionary
True
False
Dictionary keys must be immutable
True
False
In Python, Dictionaries are immutable
True
False
_________________ method will not only delete the item from dictionary, but also return the deleted value.
del ( )
pop( )
Clear( )
________________method will returns number of key-value pairs in the given dictionary.
len( )
pop( )
del( )
keys( )
values( )
What is the output of the following list operation
aList = [10, 20, 30, 40, 50, 60, 70, 80]
print(aList[2:5])
print(aList[:4])
print(aList[3:])
[20, 30, 40, 50]
[10, 20, 30, 40]
[30, 40, 50, 60, 70, 80]
[30, 40, 50]
[10, 20, 30, 40]
[40, 50, 60, 70, 80]
None of these
What is the output of the following
aList = [5, 10, 15, 25]
print(aList[::-2])
[15, 10, 5]
[10, 5]
[25, 10]
In Python, list is mutable
False
True
What will be the output of below Python code?
list1=[8,0,9,5]
print(list1[::-1])
[5,9,0,8]
[8,0,9]
[8,0,9,5]
[0,9,5]
Sort () function in list by default sort the values in __________
Ascending order
Decending order
____________function can be used to insert an element/object at a specified index.
extend( )
insert ( )
append( )
___________method adds a single item to the end of the list.
extend( )
append( )
insert( )
What is the maximum length of a Python identifier?
32
16
128
No fixed length is specified
What will be the output of the following code snippet?
print(2**3 + (5 + 6)**(1 + 1))
129
8
121
None of the above
What will be the datatype of the var in the below code snippet?
var = 10
print(type(var))
var = "Hello"
print(type(var))
str and int
int and int
str and str
int and str
How is a code block indicated in Python?
Brackets
Indentation
Key
None of the above
What will be the output of the following code snippet?
print(type(5 / 2))
print(type(5 // 2))
float and int
int and float
float and float
int and int
Which of the following concepts is not a part of Python?
Pointers
Loops
Dynamic Typing
All of the above
Which of the following statements are used in Exception Handling in Python?
Try
Except
Finally
All of the above
Which of the following types of loops are not supported in Python?
For
While
Do-While
None of the above
Which of the following is the proper syntax to check if a particular element is present in a list?
If ele in list
If not ele not in list
Both A and B
None of the above
Which of the following functions converts date to corresponding time in Python?
strptime ( )
strftime ( )
Both A and B
None of the above
