0% found this document useful (0 votes)
4 views26 pages

Practice Questions

The document is a computer programming practice worksheet consisting of multiple-choice questions covering various programming concepts, including variable assignment, data types, functions, loops, and object-oriented programming. Each question tests knowledge of Python syntax and programming principles. The worksheet serves as a study tool for learners to assess their understanding of programming fundamentals.

Uploaded by

Muhammed Hussien
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)
4 views26 pages

Practice Questions

The document is a computer programming practice worksheet consisting of multiple-choice questions covering various programming concepts, including variable assignment, data types, functions, loops, and object-oriented programming. Each question tests knowledge of Python syntax and programming principles. The worksheet serves as a study tool for learners to assess their understanding of programming fundamentals.

Uploaded by

Muhammed Hussien
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/ 26

Computer Programming Practice Worksheet

Part 1: Multiple Choice Questions


1. Which of the following correctly creates a variable and assigns it a value?

(a) let x = 3
(b) x == 3
(c) x = 3
(d) 3 = x

2. Which of the following is a valid variable name in Python?

(a) 23total
(b) value
(c) data#1
(d) for

3. What will be the result of the expression 2 + 3 * 4?

(a) 20
(b) 14
(c) 24
(d) 18

4. What is the output of "spam" * 2?

(a) "spamspam"
(b) "spam spam"
(c) "spam2"
(d) "2spam"

5. Which of the following is a literal?

(a) True
(b) PI

1
(c) x
(d) value

6. Which of these would cause a TypeError?

(a) "2" + "1"


(b) int("2") + 1
(c) "hello" + 3
(d) float(5)

7. What is the role of the equal sign = in Python?

(a) It compares two values


(b) It assigns a value to a variable
(c) It checks data type
(d) It prints values to the screen

8. What is the output of the following expression: 4 / 2 * 3?

(a) 0
(b) 6.0
(c) 1.5
(d) 2.0

9. Which of the following is not a Python data type?

(a) float
(b) int
(c) word
(d) bool

10. Which one is a proper use of comments in Python?

(a) // this is a comment


(b) /* comment */
(c) # This is a comment
(d) <-- comment

11. Which of the following best describes a semantic error?

(a) Missing colon


(b) Variable used before declaration
(c) Using // instead of /

2
(d) The code runs but gives wrong result

12. What will be the result of int("3.5")?

(a) 3
(b) 4
(c) TypeError
(d) ValueError

13. Which expression correctly converts the number 3 into a string?

(a) str(3)
(b) string(3)
(c) int("3")
(d) convert("3")

14. What is the output of: "Hello" + " " + "World"?

(a) HelloWorld
(b) Hello World
(c) ”HelloWorld”
(d) Syntax Error

15. What does the expression 3 // 2 evaluate to?

(a) 1.5
(b) 1
(c) 2
(d) 0.5

16. What is an algorithm?

(a) A flowchart
(b) A step-by-step solution to a problem
(c) A programming language
(d) A data structure

17. Which of the following is a Boolean expression?

(a) 3 + 4
(b) "True"
(c) 5 > 3
(d) print("hello")

3
18. What is the result of True or False and False?

(a) True
(b) False
(c) None
(d) Error

19. Which of the following correctly uses an if-elif-else structure?

(a) if x: elif x < 5 else:


(b) if x > 0: ... elif x < 0: ... else: ...
(c) if (x > 0): else if (x < 0): else:
(d) if x > 0 then ...

20. What type of error occurs when a loop runs one time too many or too few?

(a) Syntax error


(b) Semantic error
(c) Runtime error
(d) Off-by-one error

21. What is the output of the following?


x = 5
i f x % 2 == 0 :
p r i n t ( ” Even ” )
else :
p r i n t ( ”Odd” )

(a) Even
(b) Odd
(c) Error
(d) 5

22. Which of the following loops will execute exactly 5 times?

(a) for i in range(1, 6):


(b) while i != 5:
(c) for i in range(6):
(d) for i in range(0, 10, 2):

23. Which keyword is used to skip the current iteration of a loop?

4
(a) skip
(b) pass
(c) continue
(d) break

24. Which of the following causes a loop to terminate early?

(a) break
(b) continue
(c) pass
(d) return

25. What is the purpose of a sentinel value in a loop?

(a) To store data


(b) To indicate when to stop looping
(c) To initialize variables
(d) To ensure the loop runs exactly once

26. Which of the following correctly defines a function in Python?

(a) function myFunc():


(b) define myFunc():
(c) def myFunc():
(d) func myFunc():

27. What will be the output of this code?


def greet ( ) :
p r i n t (” Hello ”)
result = greet ()
print ( result )

(a) Hello
None
(b) Hello
Hello
(c) None
(d) Error

28. Which function type does NOT return a value?

(a) Fruitful function

5
(b) Recursive function
(c) Void function
(d) Boolean function

29. Which of the following is used to accept a variable number of positional arguments?

(a) def func(args*):


(b) def func(args):
(c) def func(args):
(d) def func():

30. What is the role of the return statement in a function?

(a) Exits the program


(b) Returns control to the operating system
(c) Returns a value from the function
(d) Prints a value to the screen

31. Which of the following would cause a recursive function to run forever?

(a) Using a loop


(b) Forgetting a base case
(c) Using print instead of return
(d) Declaring global variables

32. What does the following function return?


def is even (n ) :
r e t u r n n % 2 == 0

(a) Nothing
(b) A string
(c) A boolean value
(d) An integer

33. What is the output of this code?


d e f add ( x=2, y =3):
return x + y
p r i n t ( add ( 4 ) )

(a) 7
(b) 5

6
(c) Error
(d) 6

34. What will happen if a function is called with fewer arguments than required (and no
default values)?

(a) The program will run with default values


(b) The function will return None
(c) An error will occur
(d) The extra parameters will be ignored

35. Which statement about local and global variables is correct?

(a) Local variables can be used outside the function


(b) Global variables cannot be accessed inside functions
(c) Local variables exist only inside the function where they are declared
(d) Global variables must always be declared with global

36. Which of the following is a property of a Python string?

(a) Mutable
(b) Unordered
(c) Immutable
(d) Numeric only

37. What is the output of "Python"[1:4]?

(a) yth
(b) Pyt
(c) ytho
(d) ythn

38. Which method is used to remove and return the last item in a list?

(a) remove()
(b) pop()
(c) discard()
(d) delete()

39. What is the result of len((1, 2, 3, 4))?

(a) 3
(b) 4

7
(c) Error
(d) 5

40. Which of the following statements is true about tuples?

(a) They can be modified after creation


(b) They are unordered
(c) They are immutable
(d) They only store strings

41. Which of the following is a valid way to create a dictionary?

(a) dict = (1: "one", 2: "two")


(b) dict = [1, "one", 2, "two"]
(c) dict = {1: "one", 2: "two"}
(d) dict = 1 = "one", 2 = "two"

42. What does the update() method do in a dictionary?

(a) Removes a key


(b) Adds or modifies key-value pairs
(c) Clears the dictionary
(d) Sorts the keys

43. Which of the following creates a set with three elements?

(a) set = (1, 2, 3)


(b) set = [1, 2, 3]
(c) set = {1, 2, 3}
(d) set = {1: 2, 3: 4}

44. Which operation returns a new set with items common to both sets?

(a) union
(b) difference
(c) intersection
(d) symmetric difference

45. What is the result of [x**2 for x in range(3)]?

(a) [1, 2, 3]
(b) [0, 1, 4]
(c) [2, 3, 4]

8
(d) [0, 2, 4]

46. What does the open() function return?

(a) A string
(b) A list
(c) A file object
(d) A Boolean

47. Which file mode opens a file for appending?

(a) "r"
(b) "w"
(c) "a"
(d) "r+"

48. What is the main advantage of using the with statement to open a file?

(a) It creates a backup of the file


(b) It automatically closes the file
(c) It opens the file in binary mode
(d) It deletes the file after closing

49. Which module is used for working with file paths?

(a) sys
(b) pathlib
(c) os
(d) fileio

50. What does the following code do?


f i l e = open ( ” data . t x t ” , ”w” )
f i l e . write (” Hello ”)
f i l e . close ()

(a) Appends ”Hello” to data.txt


(b) Reads contents of data.txt
(c) Overwrites data.txt with ”Hello”
(d) Does nothing since mode is incorrect

51. What is pickling in Python?

(a) Saving code to a text file

9
(b) Encrypting Python programs
(c) Serializing Python objects into byte streams
(d) Compressing large files

52. Which file mode is required for pickling data to a file?

(a) "w"
(b) "r"
(c) "wb"
(d) "a"

53. Which statement is true about try-except-finally?

(a) The finally block only runs if there is no error.


(b) The finally block runs only when the program crashes.
(c) The finally block always runs.
(d) The except block runs before try.

54. What will happen if the file you try to open in "r" mode doesn’t exist?

(a) It creates a new file


(b) It raises a FileNotFoundError
(c) It creates a directory
(d) It returns None

55. Which method is used to read a file line-by-line into a list?

(a) file.read()
(b) file.readline()
(c) file.readlines()
(d) file.split()

56. Which of the following is the correct way to define a class?

(a) define class Dog:


(b) class Dog():
(c) class Dog:
(d) Both (b) and (c)

57. What is the role of the self keyword?

(a) It refers to the parent class


(b) It defines a static method

10
(c) It refers to the current object
(d) It is optional in instance methods

58. Which of the following best describes the difference between a class variable and an
instance variable?

(a) Class variables are shared among all instances, while instance variables are unique
to each object.
(b) Class variables are always integers, while instance variables can be any type.
(c) Instance variables can be accessed without using self.
(d) Instance variables must be declared outside the init method.

59. What is the main difference between a method and a function in Python?

(a) A method is defined outside any class, while a function is defined inside a class.
(b) A function does not take parameters, but a method always does.
(c) A method is a function defined inside a class and is associated with objects.
(d) There is no difference; method and function are interchangeable.

60. Which of the following best describes encapsulation?

(a) Inheriting from multiple classes


(b) Grouping data and methods in a class
(c) Modifying class variables outside the class
(d) Reusing methods from another class

61. What is the output of this code?


c l a s s Dog :
def i n i t ( s e l f , name ) :
s e l f . name = name

dog = Dog ( ”Max” )


p r i n t ( dog . name )

(a) name
(b) self.name
(c) Max
(d) Error

62. Which keyword is used to create a subclass?

(a) super

11
(b) class Sub inherits Base
(c) class Sub(Base)
(d) extends

63. Which of the following statements about inheritance is correct?

(a) A subclass can access attributes and methods of its superclass


(b) Inheritance breaks encapsulation
(c) A class can inherit from multiple instances
(d) Inheritance is only possible with primitive data types

64. What is polymorphism in OOP?

(a) A function that calls itself


(b) A loop inside a function
(c) The ability of different objects to respond differently to the same method call
(d) A method that cannot be overridden

65. Which method is automatically called when an object is created?

(a) str ()
(b) init ()
(c) constructor()
(d) create()

66. What is the output of the following code?


c l a s s Animal :
d e f speak ( s e l f ) :
p r i n t ( ” Animal s p e a k s ” )

c l a s s Dog ( Animal ) :
d e f speak ( s e l f ) :
p r i n t ( ” Dog b a r k s ” )

p e t = Dog ( )
p e t . speak ( )

(a) Animal speaks


(b) Dog barks
(c) Error
(d) Nothing

12
Part 2: What is the output of the following snippets?
1. x = 5
y = 2
z = x ∗∗ y // 3
print ( z )

2. a = ”5”
b = 3
print (a ∗ b)

3. a = ” h e l l o ”
b = 5
print (a + str (b))

4. x = 4 + 3 ∗ 2 − 1
print (x)

5. v a l u e = ” 3 . 1 4 ”
r e s u l t = f l o a t ( value ) + 1
print ( result )

6. x = 9
y = 2
print (x / y)
p r i n t ( x // y )
print (x % y)

7. message = ” H e l l o , World ! ”
p r i n t ( message [ 7 : 1 2 ] )

8. p r i n t ( ”Spam” ∗ 3 )
p r i n t ( ” Egg” + ” s ” )

9. num = ”5”
p r i n t (num + 1 )

10. x = 10
x = x + 5
print (x)

13
11. x = 10
i f x % 2 == 0 :
p r i n t ( ” Even ” )
else :
p r i n t ( ”Odd” )

12. y = −5
i f y > 0:
p r i n t (” P o s i t i v e ”)
e l i f y == 0 :
p r i n t ( ” Zero ” )
else :
p r i n t (” Negative ”)

13. f o r i i n range ( 3 ) :
print ( i )

14. count = 0
w h i l e count < 4 :
p r i n t ( count )
count += 1

15. x = 7
i f x > 5:
i f x < 10:
p r i n t ( ” Between 5 and 10” )

16. f o r i i n range ( 3 ) :
f o r j i n range ( 2 ) :
print ( i + j )

17. x = 0
while x < 3:
p r i n t ( ” Looping ” )
x += 1

18. f o r i i n range ( 5 ) :
i f i == 3 :
break
print ( i )

19. f o r i i n range ( 5 ) :
i f i % 2 == 0 :
continue
print ( i )

14
20. num = 4
i f num % 2 == 0 :
p r i n t ( ” Even ” )
p r i n t ( ” Done ” )

21. d e f c h e c k v a l u e ( n ) :
r e t u r n n > 10

print ( check value (12))

22. d e f mystery ( x , y =3):


return x + y

p r i n t ( mystery ( 4 ) )

23. d e f g r e e t ( name=”S t r a n g e r ” ) :
r e t u r n f ” H e l l o , {name } ! ”

print ( greet ())


p r i n t ( g r e e t (” Alice ”))

24. d e f loop sum ( n ) :


total = 0
f o r i i n range ( n ) :
t o t a l += i
return total

p r i n t ( loop sum ( 5 ) )

25. d e f example ( ) :
r e t u r n ”Done”
p r i n t ( ” This l i n e won ’ t run ” )

p r i n t ( example ( ) )

26. d e f k e y w o r d t e s t ( x , y ) :
return x − y

p r i n t ( k e y w o r d t e s t ( y=2, x =10))

27. t e x t = ”Data”
print ( text [ 1 : 3 ] )

15
28. m y l i s t = [ 1 , 2 , 3 ]
m y l i s t . append ( 4 )
print ( my list )

29. numbers = [ 1 0 , 2 0 , 3 0 , 4 0 ]
p r i n t ( numbers [ : : 2 ] )

30. my tuple = ( 1 , 2 , 3 )
p r i n t ( my tuple [ 1 ] )

31. i n f o = {”name ” : ” A l i c e ” , ” age ” : 25}


p r i n t ( i n f o [ ” age ” ] )

32. f r u i t s = [ ” a p p l e ” , ” banana ” , ” c h e r r y ” ]
f r u i t s [ 1 ] = ” blueberry ”
print ( f r u i t s )

33. my set = { 1 , 2 , 2 , 3}
p r i n t ( my set )

34. d = {”x ” : 1 , ”y ” : 2}
d[” z ”] = 3
print ( len (d))

35. nums = [ 1 , 2 , 3 ]
s q u a r e s = [ x ∗∗2 f o r x i n nums ]
print ( squares )

36. a = { 1 , 2 , 3}
b = { 3 , 4 , 5}
print (a & b)

37. t r y :
p r i n t (1 0 / 0 )
except ZeroDivisionError :
p r i n t ( ” Math e r r o r ” )
finally :
p r i n t ( ” Done ” )

38. t r y :
p r i n t ( ” Try b l o c k ” )
except :
p r i n t (” Error ”)

16
else :
p r i n t ( ”No e r r o r o c c u r r e d ” )
finally :
p r i n t ( ” Cleanup ” )

39. c l a s s Counter :
def init ( self ):
s e l f . value = 0

def increment ( s e l f ) :
s e l f . v a l u e += 1

c = Counter ( )
c . increment ( )
print ( c . value )

40. c l a s s C i r c l e :
pi = 3.14

def init ( self , r ):


s e l f . radius = r

def area ( s e l f ) :
r e t u r n C i r c l e . p i ∗ s e l f . r a d i u s ∗∗ 2

c = Circle (2)
print ( c . area ( ) )

17
Part 3: Identify and Fix Code Errors
Instructions: Each of the following code snippets contains either a syntax or logical error.
Identify the error and rewrite the corrected version of the code.

1. x = 10
y = 0
result = x / y
print ( result )

2. message = ” H e l l o ”
message [ 0 ] = ”J”
p r i n t ( message )

3. v a l u e = i n p u t ( ” Enter a number : ” )
t o t a l = v a l u e + 10
print ( total )

4. num = 3
i f num = 3 :
p r i n t ( ” Number i s 3 ”)

5. # Compute t he a v e r a g e o f two numbers


a = 5
b = 7
average = a + b / 2
p r i n t ( ” Average i s : ” , a v e r a g e )

6. p r i n t ( ” The answer i s : ” + 42 )

7. a = ”4”
b = 3
p r i n t ( a ∗ b + 2)

8. t o t a l = ( 5 + 3
print ( total )

9. i f x > 5
p r i n t ( ” G r e a t e r than 5” )

10. count = 0
w h i l e count < 3
p r i n t ( count )
count += 1

18
11. x = 4
i f x = 4:
p r i n t ( ” x i s 4” )

12. f o r i i n range ( 3 ) :
print ( i )

13. num = 10
i f num > 5 :
p r i n t (” Greater ”)
else :
p r i n t (” Lesser ”)
p r i n t (” Finished ”)
p r i n t ( ” This l i n e b e l o n g s t o e l s e ” )

14. x = 5
while x > 0:
print (x)
x −= 1

15. i = 0
while i < 3:
i f i == 1 :
continue
print ( i )
i += 1

16. f o r i i n range ( 1 , 5 ) :
i f i == 3 :
pass
print ( i )

17. d e f g r e e t ( name )
p r i n t ( ” H e l l o ” , name )

18. d e f s q u a r e ( x ) :
return x ∗ x
p r i n t ( ” The s q u a r e i s : ” , x )

19. d e f add ( x , y ) :
print (x + y)
return
return x + y

19
20. d e f i s e v e n ( n ) :
i f n % 2 = 0:
r e t u r n True
else :
return False

21. d e f message ( t e x t =”H e l l o ” , name ) :


r e t u r n f ”{ t e x t } , {name}”

22. d e f c a l c ( a , b ) :
result = a + b

print ( result )

23. d e f f ( ) :
return 2 + 3
return 4 + 5

24. d e f t e s t a r g s ( ∗ a r g s ) :
print ( args [ 2 ] )
test args (1)

25. m y l i s t = [ 1 , 2 , 3 ]
m y l i s t . i n s e r t ( 5 , ”x ” )
print ( my list [ 5 ] )

26. nums = [ 1 , 2 , 3 ]
p r i n t ( nums ( 1 ) )

27. t = ( 4 , 5 , 6 )
t [ 0 ] = 10
print ( t )

28. i n f o = {”name ” : ”Bob ” , ” age ” : 30}


p r i n t ( i n f o [ ” gender ” ] )

29. data = { 1 , 2 , [ 3 , 4 ] }
p r i n t ( data )

30. l e t t e r s = ” abcde ”
print ( l e t t e r s [ 5 ] )

20
31. my dict = {” a ” : 1 , ”b ” : 2}
my dict . add ( ” c ” , 3 )
p r i n t ( my dict )

32. my set = s e t ( )
my set . append ( 5 )

21
Part 4: Code Writing
Instructions: Write Python code to solve each of the following problems. Ensure proper
use of variables, expressions, statements, and formatting.

1. Write a function is product even(x, y) that takes two integers as arguments and
returns a string:

• "Even" if the product of the numbers is even,


• "Odd" if the product is odd.

Function Signature:

def is_product_even(x, y):


pass

2. Write a function check vowel(ch) that accepts a single alphabet character and re-
turns:

• "Vowel" if the character is a vowel (a, e, i, o, u, case insensitive),


• "Consonant" otherwise.

Assume the input is a single alphabet letter.


Function Signature:

def check_vowel(ch):
pass

3. Write a function is divisible by 3 and 5(n) that takes an integer as input and re-
turns True if it is divisible by both 3 and 5, and False otherwise.
Function Signature:

def is_divisible_by_3_and_5(n):
pass

4. Write a function log shopping() that repeatedly asks the user to enter an item they
bought during a shopping trip. After each input, the program should print "Item
recorded." When the user enters "done", the function should stop prompting and
print "Shopping log complete."
Function Signature:

def log_shopping():
pass

22
5. Write a function print triangle(n) that prints the following pattern using nested
loops, where n is the number of rows.
Example: If n = 5, the output should be:

1
22
333
4444
55555

Function Signature:

def print_triangle(n):
pass

Instructions:

• Use a nested for loop to build the pattern.


• Call the function with n = 5 to display the pattern.

6. Write a function factorial(n) that computes the factorial of a non-negative integer


n using recursion.

7. Write a function analyze numbers(*args) that accepts any number of numerical ar-
guments and returns the following:

• The total sum of the numbers


• The average of the numbers
• The minimum value
• The maximum value

Function Signature:

def analyze_numbers(*args):
pass

Instructions:

• Assume that at least one number is always passed to the function.


• Return the results as a tuple in the following order: (sum, average, min, max).

8. Write a function circle area(radius) that returns the area of a circle (use π = 3.14).

9. Write a function temperature convert(celsius) that returns the Fahrenheit equiv-


alent using the formula F = 9/5 * C + 32.

23
10. Write a function analyze string(text) that accepts a string and:

• Prints the string in uppercase.


• Prints the total number of characters.
• Prints the first and last character.
• Prints the reversed string.

Function Signature:

def analyze_string(text):
pass

11. Write a function word frequency(sentence) that takes a sentence as input and re-
turns a dictionary where:

• Each key is a unique word from the sentence.


• Each value is the number of times that word appears.

Function Signature:

def word_frequency(sentence):
pass

12. Write a function unique letters(word list) that takes a list of 5 words and returns
a set containing all unique letters used across all words.
Function Signature:

def unique_letters(word_list):
pass

13. Write a function remove vowels(text) that takes a string as input and returns a new
string with all vowels removed (both uppercase and lowercase).
Function Signature:

def remove_vowels(text):
pass

14. Write a Python program using functions to handle file creation and reading with proper
exception handling.

(a) Define a function named create file(filename) that:


• Accepts a file name as a parameter.
• Creates the file (if it doesn’t exist) and writes three lines of text into it.

24
• Handles exceptions that may occur during file writing (e.g., permission er-
rors).
(b) Define another function named read file(filename) that:
• Accepts a file name as a parameter.
• Attempts to open the file and read its contents line by line, printing each line.
• Uses a try-except block to catch and display an appropriate message if the
file does not exist or cannot be opened.

Note: You do not need to write the code for user input or the main driver code —
only define the two functions with proper signatures and exception handling.
Function Signatures:

def create_file(filename):
pass

def read_file(filename):
pass

15. Write a function in Python that reads numbers from a text file and calculates their
total sum.

• Define a function named sum from file(filename) that:


– Accepts a file name as its only parameter.
– Opens the file for reading and assumes that each line of the file contains one
number.
– Computes and returns the total sum of the numbers.
– Uses a try-except block to handle potential errors such as file not found or
invalid number format.

Note: You do not need to write code for file creation or user input — only define the
function.
Function Signature:

def sum_from_file(filename):
pass

16. Define two geometry-related classes in Python and test them by creating objects and
calling their methods.

(a) Define a class Rectangle with:


• Instance variables: length and width.
• Methods:

25
– area() — returns the area of the rectangle.
– perimeter() — returns the perimeter of the rectangle.
(b) Define a class Circle with:
• An instance variable: radius.
• A class variable: pi = 3.14.
• Methods:
– area() — returns the area of the circle.
– circumference() — returns the circumference of the circle.
(c) After defining the classes, write code to test them:
• Create a Rectangle object with length = 10 and width = 5.
• Create a Circle object with radius = 7.
• Print the area and perimeter of the rectangle.
• Print the area and circumference of the circle.

26

You might also like