0% found this document useful (0 votes)
126 views16 pages

Programming With Python (CT108-3-1-PYP) MOCK AND CLASSWORK MCQS

Programming with Python (CT108-3-1-PYP) MOCK AND CLASSWORK MCQS

Uploaded by

Rafaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views16 pages

Programming With Python (CT108-3-1-PYP) MOCK AND CLASSWORK MCQS

Programming with Python (CT108-3-1-PYP) MOCK AND CLASSWORK MCQS

Uploaded by

Rafaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

Which of the following correctly defines a function named greet that takes a name as input and
prints a greeting message?

a)
greet(name):
print("Hello, " + name + "!")

b)
def greet(name):
print("Hello, " + name + "!")

c)
function greet name:
print(f"Hello, {name}!")

d)

greet = function(name):
return "Hello, " + name + "!"

2. What is the purpose of a function in Python?(2 Points)


● To define a constant variable
● To create a reusable block of code
● To create repetition of process
● To store data permanently

3. What is the role of the return statement in a function?(3 Points)


● To terminate the function
● To define the function's purpose
● To print the function's output
● to return the control to the caller function
● Syntax in the function

4. Is it possible to define a function inside another function in Python?


(1 Point)
● Yes
● No
● Maybe
5. the keyword used to define the function(2 Points)
● function
● return
● def
● all of the above
● none of the above

6. What happens when you call a function in Python that hasn't been defined yet(2 Points)
● The code will throw an error
● Python will ignore it and continue to run the code
● The function call is ignored.
● The function call is automatically defined with default behavior.
========
7.
def square(x):
return x * x

result = square(5)
print(result)

What will be printed by the code?(2 Points)


● square
● The answer is 25
● 5
● 25

8. What is the correct way to identify a function in Python?(2 Points)


● By its name used with def keyword
● By the variable that holds the function
● By the return value
● By the number of arguments it received

9. What happens if a function doesn't explicitly return a value using return?


(2 Points)
● The function returns None by default.
● The function continues to execute indefinitely.
● The function throws an error.
● The function call has no effect.
10. A function call executes the function's code, while a definition creates the blueprint.
(1 Point)
● True
● False

11. Following are the advantages of using function in programming (2 Points)


● reusable
● modular
● readable
● maintainable
● all of the above

12. which of the following components are optional when defining a function?
(2 Points)
● default argument
● return
● function name
● arguments
● def
● body

13.
def greet(name):
result = "Hello, " + name + "!"

result = greet("Bob")
print(result)

What will be printed by the code?


(2 Points)
● Hello, Bob!
● "None" is printed.
● An error occurs.
● The function greet has been called.
=====================================================================
1. Which of the following is the purpose of a variable?(2 Points)
● To remember a value from one part of a program so that it can be used in another part of
the program
● To remember a value entered by the user
● To store value
● To reserve a place in the computer RAM
● All of the above
● None of the above

2. There are just a couple of rules to follow when naming your variables. What are those?
(1 Point)
● Variable names can contain letters, numbers, and the underscore.
● Variable names cannot contain spaces.
● Variable name cannot start with underscore
● Variable names cannot start with a number.
● Case matters—for instance, temp and Temp are different.

3. You can define a variable in python with _____ operator without declaring their type
(1 Point)
● define
● var
● =
● variable

4. Which of the variables are valid?(2 Points)


● firstname
● first name
● first_name
● first.name
● 1name
● name1

5. Which of the following are the python keywords?(2 Points)


● and
● else
● if
● def
● print
● START
● false
● not
● True
● var
● break

6. What is the value of x?


● x = 5%2(1 Point)
● 0
● 1
● 2.5
● 2

7. What will be the result of the following calculation 10 * (2 // 3)


● 0
● 6.67
● 6
● undefine
8. python file should end with ___ extension.(1 Point)
● .*
● .txt
● .python
● .py

9. You can determine the datatype of a variable in python using ____ function(2 Points)
● var()
● class()
● type()
● =

10. How do you convert an integer to a float value?(2 Points)


● float(x)
● (float) x
● int_float(x)
● convert(x)

11.Which of the following Python code prompt the operator for an age?(1 Point)
● age = input("Enter age:")
● age = int(input("Enter age:"))
● var age = input("Enter age:")
● age : int = input("Enter age")
12. Convert the following design into python code
CALCULATE
Price = cost + profit(1 Point)
● Price <- cost + profit
● Price = cost + profit
● cost + profit = Price
● All of the above

13. How to print the following output in the console, given total = 12.5.
The total amount is 12.5(2 Points)
● print "The total amount is 12.5"
● print("The total amount is 12.5")
● print(The total amount is 12.5)
● print("The total amount is {total}")

14. What is the result of the expression (4 + 2) * 3 / 2?


(1 Point)
● 18
● 6
● 7
● 9

15. What is the result of the following expression


True and False
● True
● False
● Error
● None of the above

16. What is the result of the following expression?


10 > 5 and (4 + 2) * 3 < 20?

● True
● False
● Error
● None

17. x = 5
y=3
z=x+y
print(z)

What is the final output of the Python code snippet above? (1 Point)
● 8
● 5
● 3
● 53
=================================================================
1. What happens when you break out of a for loop in Python?(2 Points)
● The loop continues execution.
● The loop immediately terminates.
● The current iteration finishes, then the loop stops.
● An error occurs.

2. What is the correct way to write a while loop that prints even numbers from 2 to 10
(inclusive)?
(a)
i=2
while i <= 10:
print(i)
i += 2
(b)
i=1
while i % 2 == 0 and i <= 10:
print(i)
i += 1
(c)
for i in range(2, 11):
if i % 2 == 0:
print(i)
(d) None of the above

3. What is the potential issue with the following while loop?


x=1
while x > 0:
print(x)
x=x

● It will never execute


● It will print x once and then exit.
● It will run infinitely
● It will print x multiple times with unpredictable behavior.

4. Which of the following while loops will run infinitely, given x is positive?
a)
while x > 0:
x -= 1
b)
while x != 0:
x += 2
c)
while x < 10:
x *= 2
d)
while True:
x = x**2

5. Which of the following Python code snippets will print a 3x3 grid of asterisks (*), where each
row is printed on a new line?

***
***
***

a)
for i in range(3):
print("*")

b)
for i in range(3):
for j in range(3):
print("*", end="")
print()

c)
for i in range(1, 4):
for j in range(1, 4):
print("*", end=" ")
print()

d)
x=0
while x < 3:
print("*")
x += 1

6. What is the output of the following nested loop snippet code?

for i in range(2):
for j in range(i):
print(j, end=" ")

● 01
● 012
● 0
● Errors.
7.
How many times will the following code snippet print "Hello"?
count = 0
for i in range(3):
while count < 2:
print("Hello")
count += 1

● 0
● 1
● 2
● 3
8. Which of the following statements is NOT true about nested loops in Python?(2 Points)
● The inner loop can modify variables used in the outer loop.
● The number of times the inner loop executes depends on the outer loop's current iteration.
● Nested loops can lead to infinite loops if not designed carefully.
● Nested loops are always more efficient than single loops for the same task.

9. What is the output of the following

for i in range(5):
if i % 2 == 0:
_______
print(i)

10. What keyword should be inserted to print only the odd numbers (1 and 3) from the range 0 to
4?
● break
● pass
● skip
● continue

10. What is the purpose of the pass keyword in a loop?


(2 Points)
● To exit the loop immediately
● To skip the current iteration and continue to the next
● To act as a placeholder for future code within the loop / nothing happens
● To print a blank line

11. Given the following code, how many times the program will loop?

for i in range(1, 6):


if i == 3:
print(f"Loop stopped at i = {i}")
break
print(i)

● 1
● 3
● 5
● 6

12.
for num in range(1,10):
if num % 3 == 0:
break
print(num)

How many numbers will be printed? (2 Points)


● 1
● 2
● 3
● 9
13.
while loops require a pre-defined condition to iterate.(1 Point)
● True
● False
===========================================================
1. Which of the following code snippets will correctly extract the substring "llo" from the string
"Hello, Good Morning!" given message = "Hello, Good Morning!"

● substring = message[2:5]
● substring = message.slice(2, 5)
● substring = message.getSubstring(2, 5)
● substring = message.extract("llo")

2. What is the output of the following code?

message = "Welcome to APU!"


new_message = message.upper()
print(new_message)

● welcome to APU!
● Welcome To APU!
● WELCOME TO APU!
● WELCOME TO apu!
3. How can you check if a string message starts with an "apple" word?

● if "apple" in message:
● if message.startswith("apple"):
● if message == "apple":
● if message.isStartingWith("apple"):

4. Review the following code,

message = " Testing 123! "


message1 = message.strip()
print(message1)

What does the strip() function do to the code?(1 Point)


● Reverses the order of words in the string.
● Converts the string to uppercase.
● Strip the characters from the string.
● Removes leading and trailing whitespace characters.

5. How can you join two strings (msg1 and msg2) together?
● message = msg1 + msg2
● message = msg1.concat(msg2)
● message = msg1 & msg2
● message = msg1.join(msg2)

6. Which of the following methods will add an element to the end of a list called 'col'?
● col.insert(0, element)
● col.append(element)
● col.insert(end,element)
● col.add(element)

7. What is the output of the following code?


num = [1, 2, 3, 4, 5]
numbers = [n * n for n in num]
print(numbers)

● [1, 2, 3, 4, 5]
● [1, 4, 9, 16, 25]
● 120
● An error occurs

8. How can you remove duplicate elements from a list?

● list.removeDuplicates()
● list = tuple(list)
● list = set(list)
● There's no built-in way to remove duplicates from lists

9. How can you check if a specific element exists in a list?

● element in list
● list.contains(element)
● find(element, list)
● There's no built-in way to check for element existence

10. Which of the following code snippets able to reverse the order of elements in a list given
following collection.(select more than 1)
numbers = [1,2,3,4,5]

● numbers.reverse()
● reverse = numbers[::-1]
● numbers.backwards()
● numbers = [num[n] for n in range(len(num)-1,-1,-1)]
● numbers.sort(False)

11. What is the key difference between tuples and lists?(2 Points)
● Tuples can hold different data types, while lists can only hold one type.
● Tuples are mutable (changeable), while lists are immutable (unchangeable).
● Tuples are ordered collections, while lists are unordered.
● Tuples are immutable (unchangeable), while lists are mutable (changeable).
● Both tuple and list are ordered collection

12. How can you access elements within a tuple?


● tuple.getElement(index)
● tuple[index]
● tuple.get(index)
● There's no way to access elements by index in tuples
13. What is the main difference between accessing elements in a dictionary and a list?
● Dictionaries can only hold strings as keys, while lists can hold any data type.
● Dictionaries are sorted, while lists are not.
● Lists use square brackets [] for indexing, while dictionaries use keys.
● There's no difference; both use indexing.

14. How can you check if a specific key exists in a dictionary?


● key in dictionary
● dictionary.hasKey(key)
● dictionary.find(key)
● There's no built-in way to check for key existence

15. Which of the following code snippets will correctly print the second element ("banana") from
the fruits tuple?
● print(fruits(1))
● print(fruits[1])
● print(fruits.get(1))
● print(fruits.index(2))

16. How can you add a new key-value pair to the my_dict dictionary?
● Given my_dict = {'a':1, 'b':2, 'c':3,'d':4, 'e':5}(2 Points)
● my_dict.insert("key", value)
● my_dict["key"] = value
● my_dict.append({"key", value})
● my_dict.add("key", value)
=====================================================================
The program will saves data into a file named "abc.txt".
data = "This is the data to be written to the file."
# Open the file
with __a)__("abc.txt", "__b)_") as file:
# Write the data to the file
file.write(___c)_)
print("Data saved successfully to abc.txt")

Given the following python code, Trace the program execution and show the output of the
program.
def calculate_average(numbers):
total = 0
for number in numbers:
if number > 0:
total += number
if len(numbers) > 0:
average = total / len(numbers)
else:
average = 0
return average
numbers = [1, 2, 3, 4, 5]
result = calculate_average(numbers)
print(result)

Write a Python code for the following statement.


a)Takes two inputs (v1, v2) [2]
b) Check if the number is positive, negative, or zero. [5]
c) Use a loop to iterate through the list called numbers and print the square of each number.
[5]
d) Print element by element from a vector called v1. [3]

v1= int(input(“Enter first number=”)


v2= int(input(“Enter second number=”)
=======
def check_number(value):
if num > 0:
print (“Number is positive”)
elif num < 0:
print (“Number is negative”)
else:
print (“Number is equal to zero”)
print(f“ v1 is {check_number(v1)}”)
print(f“ v2 is {check_number(v2)}”)
list = [1, 2, 3, 4, 5]

for num in list:


print (num ** 2)
===========
v1_vector = [1, 2, 3, 4, 5]

for num in v1_vector:


print (num)

You might also like