Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Programming Quiz

The document contains quiz questions for a Python programming course, organized into four modules covering various topics such as comments, variable names, functions, loops, lists, tuples, strings, sets, dictionaries, regular expressions, and function definitions. Each module includes multiple-choice questions that test knowledge of Python syntax and concepts. The questions are designed for second-year students in a Cyber Security program.

Uploaded by

P.K. Gupta
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)
2 views

Python Programming Quiz

The document contains quiz questions for a Python programming course, organized into four modules covering various topics such as comments, variable names, functions, loops, lists, tuples, strings, sets, dictionaries, regular expressions, and function definitions. Each module includes multiple-choice questions that test knowledge of Python syntax and concepts. The questions are designed for second-year students in a Cyber Security program.

Uploaded by

P.K. Gupta
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/ 22

22CS102002- PYTHON PROGRAMMING

For Second Year III Semester Cyber Security


Quiz Questions

Module-I
1. What is the correct way to write a comment in Python?
A) // This is a comment
B) /* This is a comment */
C) # This is a comment
D) <!-- This is a comment -->

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


A) 1variable
B) variable_1
C) variable-1
D) variable 1

3. What is the output of the following code snippet?


print(type(3.14))
A) <class 'int'>
B) <class 'float'>
C) <class 'str'>
D) <class 'bool'>

4. Which keyword is used to define a function in Python?


A) func
B) define
C) function
D) def

5. Which operator is used for exponentiation in Python?


A) ^
B) **
C) //
D) %

6. What will be the output of the following code?


x = "Hello"
y = "World"
print(x + y)
A) HelloWorld
B) Hello World
C) Hello+World
D) Error

7. How do you indicate a block of code in Python?


A) Using curly braces {}
B) Using indentation
C) Using parentheses ()
D) Using a colon :

8. What is the result of 5 / 2 in Python 3?


A) 2.5
B) 2
C) 2.0
D) 2.5f

9. How can you convert a string '123' to an integer in Python?


A) int('123')
B) str('123')
C) float('123')
D) convert('123', int)

10. Which of the following is NOT a Python data type?


A) list
B) tuple
C) set
D) array

11. Which of the following symbols is used to denote a dictionary in Python?


A) []
B) ()
C) {}
D) <>

12. What does the input() function do in Python?


A) It reads input from the user.
B) It outputs data to the screen.
C) It converts a string to a number.
D) It creates a new variable.

13. How do you write an infinite loop in Python?


A) while True:
B) for i in range(0, -1):
C) loop forever:
D) repeat until false:

14. What is the correct way to handle exceptions in Python?


A) try...except
B) catch...error
C) begin...rescue
D) error...catch

15. Which operator is used for floor division in Python?


A) /
B) //
C) %
D) **

16. What will be the output of the following code?


x = 10
y = 20
x, y = y, x
print(x, y)
A) 10 20
B) 20 10
C) x y
D) Error

17. What is the purpose of the return statement in a Python function?


A) It prints the value to the console.
B) It terminates the function and optionally passes back a value.
C) It continues execution to the next line.
D) It defines the function.

18. Which of the following is a mutable data type in Python?


A) int
B) float
C) tuple
D) list
19. What will be the result of the following expression?
'abc' * 3
A) 'abcabcabc'
B) 'abcabc'
C) 3 * 'abc'
D) ['abc', 'abc', 'abc']

20. How can you format strings in Python using the format method?
A) "{0} {1}".format('Hello', 'World')
B) "{} {}".format('Hello', 'World')
C) "{} {}".format(Hello, World)
D) "{0} {1}".format(Hello, World)
Module-II

1. Which of the following is the correct syntax for an if statement in Python?


A) if condition then:
B) if condition:
C) if (condition) {
D) if condition;

2. What will be the output of the following code?


x = 10
if x > 5:
print("Greater")
else:
print("Smaller")
A) Greater
B) Smaller
C) Greater Smaller
D) Error

3. How do you write an if-else statement in Python?


A)
if condition:
statements
else:
statements
B)
if condition {
statements
} else {
statements
}
C)
if condition then:
statements
else:
statements
D)
if condition:
statements
elif:
statements
4. Which keyword is used to add additional conditions after the initial if in Python?
A) elif
B) elseif
C) else if
D) add if

5. What will be the output of the following code?


x=5
if x > 10:
print("High")
elif x > 0:
print("Medium")
else:
print("Low")
A) High
B) Medium
C) Low
D) Error

6. How does Python handle multiple if statements in sequence without elif?


A) Executes all if blocks regardless of conditions.
B) Executes only the first if block.
C) Executes each if block independently based on its condition.
D) Executes the if block with the highest condition value.

7. What is the correct syntax for a nested if statement?


A)
if condition:
if nested_condition:
statements
B)
if condition {
if nested_condition {
statements
}
}
C)
if condition:
else:
if nested_condition:
statements
D)
if condition:
if nested_condition:
statements
else:
statements

Iterative Statements
8. Which loop in Python is best suited for iterating over a sequence?
A) while
B) for
C) repeat
D) do-while

9. What will be the output of the following code?


for i in range(3):
print(i)
A) 0 1 2 3
B) 1 2 3
C) 0 1 2
D) 0 1 2 3 4

10. What is the purpose of the break statement in a loop?


A) To skip the current iteration and continue with the next iteration.
B) To exit the loop and continue with the next statement after the loop.
C) To terminate the loop and exit the program.
D) To restart the loop from the beginning.

11. Which statement is used to skip the rest of the code inside a loop for the current
iteration?
A) skip
B) continue
C) pass
D) next

12. What does the pass statement do in Python?


A) It stops the execution of the program.
B) It performs no action; it acts as a placeholder.
C) It skips to the next iteration of the loop.
D) It exits the loop.
13. How do you write an infinite while loop in Python?
A) while True:
B) while False:
C) while 0:
D) for i in range(-1):

14. What will be the output of the following code snippet?


x=0
while x < 3:
print(x)
x += 1
else:
print("Done")
A) 0 1 2 Done
B) 0 1 2
C) Done
D) Error

15. Which statement is used to end a loop early and skip the remaining code inside the
loop?
A) continue
B) exit
C) stop
D) break

16. What will be the output of the following code?


for i in range(5):
if i == 3:
break
print(i)
A) 0 1 2 3
B) 0 1 2
C) 0 1 2 3 4
D) 0 1 2 3 4 5

17. Which keyword is used to handle code that should execute regardless of whether an
exception was raised or not?
A) finally
B) else
C) except
D) raise

18. What does the else clause in a while loop do in Python?


A) Executes only if the loop ends due to a break statement.
B) Executes after the loop completes normally (not terminated by break).
C) Is executed instead of the loop body.
D) Is not valid with while loops.

19. What will be the result of the following code?


x=1
while x <= 5:
if x == 4:
continue
print(x)
x += 1
A) 1 2 3 4 5
B) 1 2 3 5
C) 1 2 3 4
D) 2 3 4 5

20. How do you create a loop that iterates through a list in Python?
A) for item in list:
B) while item in list:
C) loop item in list:
D) for each item in list:
Module-III
1. How do you create a list in Python?
A) list = {}
B) list = ()
C) list = []
D) list = <>

2. What will be the result of the following code?


my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list)
A) [1, 2, 3, 4, 5]
B) [1, 2, 3, 4, 5, 5]
C) [1, 2, 3, 4]
D) [1, 2, 3, 4, 5, 6]

3. How do you insert an element into a list at a specific index?


A) list.add(index, element)
B) list.insert(index, element)
C) list.append(index, element)
D) list.put(index, element)

4. What does the following code do?


my_list = [1, 2, 3, 4]
del my_list[2]
print(my_list)
A) [1, 2, 4]
B) [1, 2, 3]
C) [1, 2, 3, 4]
D) [1, 2, 4, 2]

5. How can you sort a list in Python?


A) list.sort()
B) sort(list)
C) list.order()
D) list.arrange()

6. What is the output of the following list comprehension?


squares = [x**2 for x in range(5)]
print(squares)
A) [0, 1, 4, 9, 16]
B) [1, 4, 9, 16, 25]
C) [0, 1, 4, 9]
D) [1, 4, 9, 16]

7. How do you access elements in a nested list?


A) list[i][j]
B) list(i, j)
C) list[i,j]
D) list[i][j][k]

Tuples
8. How do you create a tuple in Python?
A) tuple = []
B) tuple = ()
C) tuple = {}
D) tuple = <>

9. What will be the output of the following code?


my_tuple = (1, 2, 3, 4)
print(my_tuple[2])
A) 2
B) 3
C) 4
D) Error

10. How can you check if an element exists in a tuple?


A) element in tuple
B) tuple.has(element)
C) tuple.exists(element)
D) tuple.contains(element)

11. What is the output of the following code?


my_tuple = (1, 2, 3, 4)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)
A) (1, 2, 3, 4)
B) [1, 2, 3, 4]
C) (4, 3, 2, 1)
D) [4, 3, 2, 1]

12. How do you create a nested tuple?


A) nested_tuple = ((1, 2), (3, 4))
B) nested_tuple = (1, 2, (3, 4))
C) nested_tuple = [1, (2, 3), 4]
D) nested_tuple = ((1, 2), [3, 4])

Strings
13. How do you initialize a string in Python?
A) string = ''
B) string = ""
C) string = '' or ""
D) Both A and B

14. What will be the output of the following string operation?


text = "Hello, World!"
print(text.upper())
A) HELLO, WORLD!
B) Hello, World!
C) HELLO, world!
D) hello, world!

15. How do you format a string using the format() method?


A) "{0} {1}".format('Hello', 'World')
B) "{} {}".format('Hello', 'World')
C) "Hello {} World".format('World')
D) "{Hello} {World}".format()

16. What method is used to remove whitespace from both ends of a string?
A) strip()
B) trim()
C) remove()
D) delete()

Sets
17. How do you create a set in Python?
A) my_set = []
B) my_set = ()
C) my_set = {}
D) my_set = set()

18. What is the output of the following code?


my_set = {1, 2, 2, 3, 4}
print(my_set)
A) {1, 2, 2, 3, 4}
B) {1, 2, 3, 4}
C) [1, 2, 3, 4]
D) Error

19. What is the result of the union of two sets in Python?


A) The intersection of the sets.
B) The difference of the sets.
C) A new set containing all unique elements from both sets.
D) A new set containing only common elements from both sets.

Dictionaries
20. How do you create a dictionary in Python?
A) my_dict = ()
B) my_dict = {key: value}
C) my_dict = []
D) my_dict = {}

21. How do you access a value in a dictionary?


A) dict[key]
B) dict.get(key)
C) dict(key)
D) Both A and B

22. Which method is used to sort the keys of a dictionary in Python?


A) sorted(dict.keys())
B) dict.sort()
C) dict.keys().sort()
D) dict.sort_keys()

Regular Expressions
23. What symbol is used to denote zero or more occurrences of the preceding element in a
regular expression?
A) *
B) +
C) ?
D) .

24. What does the regular expression \d match?


A) Any digit
B) Any non-digit character
C) Any whitespace character
D) Any alphanumeric character

25. How do you match a literal dot (.) in a regular expression?


A) .
B) \.
C) \\.
D) []

26. Which quantifier matches exactly one or more occurrences of the preceding element?
A) *
B) +
C) ?
D) {n}

27. What does the special character ^ signify in a regular expression when used at the
beginning of a pattern?
A) End of the string
B) Start of the string
C) Any character
D) Grouping
Answer: B) Start of the string
Module-IV
1. What is the primary purpose of using functions in Python?
A) To reuse code and avoid repetition.
B) To store data permanently.
C) To define variables.
D) To create user interfaces.

2. How do you define a function in Python?


A) def function_name()
B) function function_name()
C) create function_name()
D) define function_name()

3. What is the syntax for calling a function named my_function?


A) call my_function()
B) my_function()
C) execute my_function()
D) run my_function()

4. What will be the output of the following code?


def greet():
return "Hello, World!"
print(greet())
A) Hello, World!
B) greet()
C) Hello
D) World!

5. What is the scope of a variable defined inside a function?


A) Global
B) Local to that function
C) Shared across all functions
D) Permanent until the program ends

6. What does the return statement do in a function?


A) It exits the function and optionally returns a value.
B) It restarts the function execution.
C) It prints a value to the console.
D) It pauses the function execution.

7. How do you specify default arguments in a function?


A) def function_name(arg1, arg2=default_value):
B) def function_name(arg1, arg2: default_value):
C) def function_name(arg1, arg2->default_value):
D) def function_name(arg1, arg2, default_value):

8. Which of the following is true about keyword arguments?


A) They must be passed in the order they are defined.
B) They are specified by name and can be passed in any order.
C) They cannot be used with default arguments.
D) They must always be used with positional arguments.

9. What is the purpose of the *args and **kwargs syntax in a function definition?
A) To define optional and keyword arguments, respectively.
B) To define default arguments and positional arguments.
C) To handle variable-length arguments and keyword arguments.
D) To define multiple return values.

10. How does a recursive function work?


A) It calls itself in its definition.
B) It uses loops to repeat tasks.
C) It calls another function to perform tasks.
D) It creates new functions dynamically.

11. What is the output of the following code?


def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
A) 120
B) 60
C) 24
D) 5

12. What does a lambda function do?


A) It defines a simple function without a name.
B) It creates a new module in Python.
C) It initializes variables with default values.
D) It handles exception handling.
13. How do you create a generator function?
A) By using the return statement to yield values.
B) By using the yield statement to return values.
C) By defining a function with def and return statements.
D) By using the def keyword with a generate keyword.

14. What will be the output of the following code?


def simple_gen():
yield 1
yield 2
yield 3

gen = simple_gen()
print(next(gen))
print(next(gen))
A) 1 2
B) 1 2 3
C) 1 1
D) 1 2 3

File Handling
15. What is the correct way to open a file for reading in Python?
A) open('file.txt', 'w')
B) open('file.txt', 'r')
C) open('file.txt', 'a')
D) open('file.txt', 'x')

16. How do you write data to a file in Python?


A) file.write('data')
B) file.append('data')
C) file.add('data')
D) file.insert('data')

17. Which method is used to read the entire content of a file?


A) file.read()
B) file.readlines()
C) file.get()
D) file.fetch()

18. How do you close a file after performing operations?


A) file.stop()
B) file.close()
C) file.end()
D) file.exit()

19. What will be the output of the following code if data.txt contains "Hello, World!"?
with open('data.txt', 'r') as file:
content = file.read()
print(content)
A) Hello, World!
B) data.txt
C) None
D) Error

20. How do you append data to an existing file?


A) open('file.txt', 'r+')
B) open('file.txt', 'a')
C) open('file.txt', 'w')
D) open('file.txt', 'x')
Module-V
1. What is the main concept of Object-Oriented Programming?
A) Writing functions that are reusable.
B) Storing data in a structured format.
C) Organizing code into classes and objects.
D) Creating a procedural sequence of commands.

2. How do you define a class in Python?


A) class MyClass():
B) define class MyClass:
C) class MyClass
D) create class MyClass()

3. What is an object in Python?


A) A function defined inside a class.
B) An instance of a class.
C) A type of variable.
D) A method that returns a value.

4. How do you create an object of a class named Person?


A) person = Person()
B) person = new Person()
C) person = create Person()
D) person = Person.new()

5. What keyword is used to create a subclass in Python?


A) extends
B) inherits
C) class
D) super

6. How do you call a method from a superclass in a subclass?


A) super().method_name()
B) parent.method_name()
C) base.method_name()
D) self.method_name()

7. Which of the following is an example of polymorphism?


A) Using the same method name in different classes.
B) Using the same class in different modules.
C) Inheriting from multiple classes.
D) Overloading operators.

8. What is the purpose of an abstract class in Python?


A) To create instances directly.
B) To define methods that must be implemented by subclasses.
C) To provide default method implementations.
D) To prevent subclassing.

9. How do you define an abstract method in Python?


A) def method_name(self): pass
B) @abstractmethod def method_name(self):
C) def method_name(self) abstract:
D) def method_name(self): raise NotImplementedError

10. What is an interface in Python?


A) A class that defines abstract methods.
B) A class that cannot be instantiated.
C) A special type of class used for GUI design.
D) A class that implements only static methods.

Exception Handling
11. What is an error in Python?
A) A type of variable that stores error messages.
B) An issue that occurs during the execution of a program.
C) A warning message for debugging purposes.
D) A syntax issue detected during coding.

12. What is an exception in Python?


A) A type of error that can be handled in the code.
B) A syntax error in the code.
C) A function that catches errors.
D) An error that stops the execution of the program.

13. Which keyword is used to handle exceptions in Python?


A) catch
B) try
C) except
D) throw

14. How do you handle exceptions in Python?


A) Using the try and except blocks.
B) Using the catch block.
C) Using throw and catch statements.
D) Using the finally block only.

15. What is the purpose of the finally block in exception handling?


A) To execute code only if no exceptions are raised.
B) To execute code regardless of whether an exception was raised or not.
C) To define custom exceptions.
D) To log exception details.

16. What will be the result of the following code?


try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution finished")
A) Cannot divide by zero
B) Execution finished
C) Cannot divide by zero Execution finished
D) Error

17. How do you create a user-defined exception in Python?


A) class MyException(Exception): pass
B) def MyException(Exception): pass
C) exception MyException(Exception): pass
D) class MyException: Exception

18. Which of the following is NOT a built-in exception in Python?


A) ValueError
B) TypeError
C) FileNotFoundError
D) UserDefinedException

19. What is the purpose of the assert statement in Python?


A) To handle exceptions gracefully.
B) To assert conditions and raise an AssertionError if the condition is False.
C) To create assertions for debugging purposes.
D) To define custom exceptions.

20. What will be the output of the following code?


try:
assert 2 + 2 == 5
except AssertionError:
print("Assertion failed")
A) Assertion failed
B) 2 + 2 == 5
C) Assertion successful
D) Error

You might also like