0% found this document useful (0 votes)
42 views34 pages

Bindu

The document consists of a series of multiple-choice questions (MCQs) related to Python programming, covering topics such as language features, syntax, data types, and built-in functions. Each question includes several options with the correct answer indicated. The questions test knowledge on various aspects of Python, including its case sensitivity, file extensions, operators, and functions.

Uploaded by

sushmavemula991
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)
42 views34 pages

Bindu

The document consists of a series of multiple-choice questions (MCQs) related to Python programming, covering topics such as language features, syntax, data types, and built-in functions. Each question includes several options with the correct answer indicated. The questions test knowledge on various aspects of Python, including its case sensitivity, file extensions, operators, and functions.

Uploaded by

sushmavemula991
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/ 34

MCQ:

1. Who developed Python Programming Language?


●​ a) Wick van Rossum
●​ b) Rasmus Lerdorf
●​ c) Guido van Rossum
●​ d) Niene Stom
●​ Correct Answer: c) Guido van Rossum
2. Which type of Programming does Python support?
●​ a) object-oriented programming
●​ b) structured programming
●​ c) functional programming
●​ d) all of the mentioned
●​ Correct Answer: d) all of the mentioned
3. Is Python case sensitive when dealing with identifiers?
●​ a) no
●​ b) yes
●​ c) machine dependent
●​ d) none of the mentioned
●​ Correct Answer: b) yes
4. Which of the following is the correct extension of the Python file?
●​ a) .python
●​ b) .pl
●​ c) .py
●​ d) .p
●​ Correct Answer: c) .py
5. Is Python code compiled or interpreted?
●​ a) Python code is both compiled and interpreted
●​ b) Python code is neither compiled nor interpreted
●​ c) Python code is only compiled
●​ d) Python code is only interpreted
●​ Correct Answer: a) Python code is both compiled and interpreted
6. All keywords in Python are in _________
●​ a) Capitalized
●​ b) lower case
●​ c) UPPER CASE
●​ d) None of the mentioned
●​ Correct Answer: b) lower case
7. What will be the value of the following Python expression? 4 + 3 % 5
●​ a) 7
●​ b) 2
●​ c) 4
●​ d) 1
●​ Correct Answer: a) 7
8. Which of the following is used to define a block of code in Python language?
●​ a) Indentation
●​ b) Key
●​ c) Brackets
●​ d) All of the mentioned
●​ Correct Answer: a) Indentation
9. Which keyword is used for function in Python language?
●​ a) Function
●​ b) def
●​ c) Fun
●​ d) Define
●​ Correct Answer: b) def
10. Which of the following character is used to give single-line comments in Python?
●​ a) //
●​ b) #
●​ c) !
●​ d) /*
●​ Correct Answer: b) #
11. What will be the output of the following Python code? i = 1 while True: if i%3 == 0: break
print(i) i + = 1
●​ a) 1 2 3
●​ b) error
●​ c) 1 2
●​ d) none of the mentioned
●​ Correct Answer: c) 1 2
12. Which of the following functions can help us to find the version of python that we are
currently working on?
●​ a) sys.version(1)
●​ b) sys.version(0)
●​ c) sys.version()
●​ d) sys.version
●​ Correct Answer: d) sys.version
13. Python supports the creation of anonymous functions at runtime, using a construct called
__________
●​ a) pi
●​ b) anonymous
●​ c) lambda
●​ d) none of the mentioned
●​ Correct Answer: c) lambda
14. What is the order of precedence in python?
●​ a) Exponential, Parentheses, Multiplication, Division, Addition, Subtraction
●​ b) Exponential, Parentheses, Division, Multiplication, Addition, Subtraction
●​ c) Parentheses, Exponential, Multiplication, Addition, Division, Subtraction
●​ d) Parentheses, Exponential, Multiplication, Division, Addition, Subtraction
●​ Correct Answer: d) Parentheses, Exponential, Multiplication, Division, Addition,
Subtraction
15. What will be the output of the following Python code snippet if x=1? x<<2
●​ a) 4
●​ b) 2
●​ c) 1
●​ d) 8
●​ Correct Answer: a) 4
16. What does pip stand for python?
●​ a) Pip Installs Python
●​ b) Pip Installs Packages
●​ c) Preferred Installer Program
●​ d) All of the mentioned
●​ Correct Answer: c) Preferred Installer Program
17. Which of the following is true for variable names in Python?
●​ a) underscore and ampersand are the only two special characters allowed
●​ b) unlimited length
●​ c) all private members must have leading and trailing underscores
●​ d) none of the mentioned
●​ Correct Answer: b) unlimited length
18. What are the values of the following Python expressions? 2(32) (23)2 232
●​ a) 512, 64, 512
●​ b) 512, 512, 512
●​ c) 64, 512, 64
●​ d) 64, 64, 64
●​ Correct Answer: a) 512, 64, 512
19. Which of the following is the truncation division operator in Python?
●​ a) |
●​ b) //
●​ c) /
●​ d) %
●​ Correct Answer: b) //
20. What will be the output of the following Python code? l=[1, 0, 2, 0, 'hello', '', []] list(filter(bool,
l))
●​ a) [1, 0, 2, ‘hello’, ”, []]
●​ b) Error
●​ c) [1, 2, ‘hello’]
●​ d) [1, 0, 2, 0, ‘hello’, ”, []]
●​ Correct Answer: c) [1, 2, ‘hello’]
21. Which of the following functions is a built-in function in python?
●​ a) factorial()
●​ b) print()
●​ c) seed()
●​ d) sqrt()
●​ Correct Answer: b) print()
22. Which of the following is the use of id() function in python?
●​ a) Every object doesn’t have a unique id
●​ b) Id returns the identity of the object
●​ c) All of the mentioned
●​ d) None of the mentioned
●​ Correct Answer: b) Id returns the identity of the object
**23. The following python program can work with ____ parameters. def f(x): def f1(*args,
**kwargs): print("Sanfoundry") return x(*args, kwargs) return1 f1
●​ a) any number of
●​ b) 0
●​ c) 1
●​ d) 2
●​ Correct Answer: a) any number of
24. What will be the output of the following Python function? min(max(False,-3,-4), 2,7)
●​ a) -4
●​ b) -3
●​ c) 2
●​ d) False
●​ Correct Answer: d) False
25. Which of the following is not a core data type in Python programming?
●​ a) Tuples
●​ b) Lists
●​ c) Class
●​ d) Dictionary
●​ Correct Answer: c) Class
26. What will be the output of the following Python expression if x=56.236? print("%.2f"%x)
●​ a) 56.236
●​ b) 56.23
●​ c) 56.0000
●​ d) 56.24
●​ Correct Answer: b) 56.23
27. Which of these is the definition for packages in Python?
●​ a) A set of main modules
●​ b) A folder of python modules
●​ c) A number of files containing Python definitions and statements
●​ d) A set of programs making use of Python modules
●​ Correct Answer: b) A folder of python modules
28. What will be the output of the following Python function? len(["hello",2, 4, 6])
●​ a) Error
●​ b) 6
●​ c) 4
●​ d) 3
●​ Correct Answer:c
29. What will be the output of the following Python code?
Python
x = 'abcd'
for i in x:
print(i.upper())

a)​
a
B
C
D
●​
●​ b) a b c d
●​ c) error
d)​
A
B
C
D
●​
Correct Option: d)​
A
B
C
D
●​
30. What is the order of namespaces in which Python looks for an identifier?
●​ a) Python first searches the built-in namespace, then the global namespace and finally
the local namespace
●​ b) Python first searches the built-in namespace, then the local namespace and finally the
global namespace
●​ c) Python first searches the local namespace, then the global namespace and finally the
built-in namespace
●​ d) Python first searches the global namespace, then the local namespace and finally the
built-in namespace
●​ Correct Option: c) Python first searches the local namespace, then the global
namespace and finally the built-in namespace
31. What will be the output of the following Python code snippet?
Python
for i in [1, 2, 3, 4][::-1]:
print(i, end=' ')

●​ a) 4 3 2 1
●​ b) error
●​ c) 1 2 3 4
●​ d) none of the mentioned
●​ Correct Option: a) 4 3 2 1
32. What will be the output of the following Python statement?
Python
>>>"a"+"bc"

●​ a) bc
●​ b) abc
●​ c) a
●​ d) bca
●​ Correct Option: b) abc
33. Which function is called when the following Python program is executed?
Python
f = foo()
format(f)

●​ a) str()
●​ b) format()
●​ c) __str__()
●​ d) __format__()
●​ Correct Option: d) __format__()
34. Which one of the following is not a keyword in Python language?
●​ a) pass
●​ b) eval
●​ c) assert
●​ d) nonlocal
●​ Correct Option: b) eval
35. What will be the output of the following Python code?
Python
class tester:
def __init__(self, id):
self.id = str(id)
id="224"

>>>temp = tester(12)
>>>print(temp.id)

●​ a) 12
●​ b) 224
●​ c) None
●​ d) Error
●​ Correct Option: a) 12
36. What will be the output of the following Python program?
Python
def foo(x):
x[0] = ['def']
x[1] = ['abc']
return id(x)
q = ['abc', 'def']
print(id(q) == foo(q))

●​ a) Error
●​ b) None
●​ c) False
●​ d) True
●​ Correct Option: d) True
37. Which module in the python standard library parses options received from the command
line?
●​ a) getarg
●​ b) getopt
●​ c) main
●​ d) os
●​ Correct Option: b) getopt
38. What will be the output of the following Python program?
Python
z=set('abc')
z.add('san')
z.update(set(['p', 'q']))
z
●​ a) {‘a’, ‘c’, ‘c’, ‘p’, ‘q’, ‘s’, ‘a’, ‘n’}
●​ b) {‘abc’, ‘p’, ‘q’, ‘san’}
●​ c) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}
●​ d) {‘a’, ‘b’, ‘c’, [‘p’, ‘q’], ‘san}
●​ Correct Option: c) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}
39. What arithmetic operators cannot be used with strings in Python?
●​ a) *
●​ b) –
●​ c) +
●​ d) All of the mentioned
●​ Correct Option: b) –
40. What will be the output of the following Python code?
Python
print("abc. DEF".capitalize())

●​ a) Abc. def
●​ b) abc. def
●​ c) Abc. Def
●​ d) ABC. DEF
●​ Correct Option: a) Abc. def
41. Which of the following statements is used to create an empty set in Python?
●​ a) ( )
●​ b) [ ]
●​ c) { }
●​ d) set()
●​ Correct Option: d) set()
42. What will be the value of ‘result’ in following Python program?
Python
list1 = [1,2,3,4]
list2 = [2,4,5,6]
list3 = [2,6,7,8]
result = list()
result.extend(i for i in list1 if i not in (list2+list3) and i not in result)
result.extend(i for i in list2 if i not in (list1+list3) and i not in result)
result.extend(i for i in list3 if i not in (list1+list2) and i not in result)

●​ a) [1, 3, 5, 7, 8]
●​ b) [1, 7, 8]
●​ c) [1, 2, 4, 7, 8]
●​ d) error
●​ Correct Option: a) [1, 3, 5, 7, 8]
43. To add a new element to a list we use which Python command?
●​ a) list1.addEnd(5)
●​ b) list1.addLast(5)
●​ c) list1.append(5)
●​ d) list1.add(5)
●​ Correct Option: c) list1.append(5)
44. What will be the output of the following Python code?
Python
print('*', "abcde".center(6), '*', sep='')

●​ a) * abcde *
●​ b) *abcde *
●​ c) * abcde*
●​ d) * abcde *
●​ Correct Option: a) * abcde *
45. What will be the output of the following Python code?
Python
>>>list1 = [1, 3]
>>>list2 = list1
>>>list1[0] = 4
>>>print(list2)

●​ a) [1, 4]
●​ b) [1, 3, 4]
●​ c) [4, 3]
●​ d) [1, 3]
●​ Correct Option: c) [4, 3]
46. Which one of the following is the use of function in python?
●​ a) Functions don’t provide better modularity for your application
●​ b) you can’t also create your own functions
●​ c) Functions are reusable pieces of programs
●​ d) All of the mentioned
●​ Correct Option: c) Functions are reusable pieces of programs
47. Which of the following Python statements will result in the output: 6?
Python
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

●​ a) A[2][1]
●​ b) A[1][2]
●​ c) A[3][2]
●​ d) A[2][3]
●​ Correct Option: b) A[1][2]
48. What is the maximum possible length of an identifier in Python?
●​ a) 79 characters
●​ b) 31 characters
●​ c) 63 characters
●​ d) none of the mentioned
●​ Correct Option: d) none of the mentioned (There is no practical limit)
49. What will be the output of the following Python program?
Python
i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)

●​ a) error
●​ b) 0 1 2 0
●​ c) 0 1 2
●​ d) none of the mentioned
●​ Correct Option: c) 0 1 2
50. What will be the output of the following Python code?
Python
x = 'abcd'
for i in range(len(x)):
print(i)

●​ a) error
●​ b) 1 2 3 4
●​ c) a b c d
●​ d) 0 1 2 3
●​ Correct Option: d) 0 1 2 3
51. What are the two main types of functions in Python?
●​ a) System function
●​ b) Custom function
●​ c) Built-in function & User defined function
●​ d) User function
●​
●​ Correct Option: c) Built-in function & User defined function
52. What will be the output of the following Python program?
Python
def addItem(listParam):
listParam += [1]

mylist = [1, 2, 3, 4]
addItem(mylist)
print(len(mylist))

●​ a) 5
●​ b) 8
●​ c) 2
●​ d) 1
●​ Correct Option: a) 5
53. Which of the following is a Python tuple?
●​ a) {1, 2, 3}
●​ b) {}
●​ c) [1, 2, 3]
●​ d) (1, 2, 3)
●​ Correct Option: d) (1, 2, 3)
54. What will be the output of the following Python code snippet?
Python
z=set('abc$de')
'a' in z

●​ a) Error
●​ b) True
●​ c) False
●​ d) No output
●​ Correct Option: b) True
55. What will be the output of the following Python expression?
Python
round(4.576)

●​ a) 4
●​ b) 4.6
●​ c) 5
●​ d) 4.5
●​ Correct Option: c) 5
56. Which of the following is a feature of Python DocString?
●​ a) In Python all functions should have a docstring
●​ b) Docstrings can be accessed by the __doc__ attribute on objects
●​
●​ c) It provides a convenient way of associating documentation with Python modules,
functions, classes, and methods
●​ d) All of the mentioned
●​
●​ Correct Option: d) All of the mentioned
57. What will be the output of the following Python code?
Python
print("Hello {0[0]} and {0[1]}".format(('foo', 'bin')))
●​ a) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
●​ b) Error
●​ c) Hello foo and bin
●​ d) None of the mentioned
●​ Correct Option: c) Hello foo and bin
58. What is output of print(math.pow(3, 2))?
●​ a) 9.0
●​ b) None
●​ c) 9
●​ d) None of the mentioned
●​ Correct Option: a) 9.0
59. Which of the following is the use of id() function in python?
●​ a) Every object in Python doesn’t have a unique id
●​ b) In Python Id function returns the identity of the object
●​
●​ c) None of the mentioned
●​ d) All of the mentioned
●​
●​ Correct Option: b) In Python Id function returns the identity of the object
60. What will be the output of the following Python code?
Python
x = [[0], [1]]
print((' '.join(list(map(str, x))),))

●​ a) 01
●​ b) [0] [1]
●​ c) (’01’)
●​ d) (‘[0] [1]’,)
●​ Correct Option: d) (‘[0] [1]’,)
61. The process of pickling in Python includes ____________
●​ a) conversion of a Python object hierarchy into byte stream
●​ b) conversion of a datatable into a list
●​ c) conversion of a byte stream into Python object hierarchy
●​
●​ d) conversion of a list into a datatable
●​
●​ Correct Option: a) conversion of a Python object hierarchy into byte stream
62. What will be the output of the following Python code?
Python
def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)

●​ a) error, there is more than one return statement in a single try-finally block
●​ b) 3
●​ c) 2
●​ d) 1
●​ Correct Option: c) 2

Q 1 - What is output for − 'search'.find('S') ?


●​ A - s
●​ B - -1
●​ C - ‘ ‘
●​ D - None of the above
●​ Correct Answer: B - -1
○​ Explanation: The find() method is case-sensitive. Since 'S' is not in 'search', it
returns -1.
Q 2 - What is the output of following code − [ (a,b) for a in range(3) for b in range(a) ]
●​ A - [ (1,0),(2,1),(3,2)]
●​ B - [ (0,0),(1,1),(2,2)]
●​ C - [(1,0),(2,1),(2,1)]
●​ D - [ (1,0),(2,0),(2,1)]
●​ Correct Answer: D - [ (1,0),(2,0),(2,1)]
○​ Explanation: The nested loop generates pairs where 'b' ranges from 0 up to (but
not including) 'a'.
Q 3 - Which operator is right-associative
●​ A - *
●​ B - =
●​ C - +
●​ D - %
●​ Correct Answer: B - =
○​ Explanation: The assignment operator (=) is right-associative, meaning the right
side is evaluated first.
Q 4 - What is output for − min('hello world')
●​ A - e
●​ B - a blank space character
●​ C - w
●​ D - None of the above
●​ Correct Answer: B - a blank space character
○​ Explanation: The min() function returns the lexicographically smallest character,
and a space comes before any letters.
Q 5 - What is output of following code − l = [1,2,6,5,7,8] l.insert(9)
●​ A - l=[9,1,2,6,5,7,8]
●​ B - l=[1,2,6,5,9.7,8] (insert randomly at any position)
●​ C - l=[1,2,6,5,7,8,9]
●​ D - Type Error
●​ Correct Answer: D - Type Error
○​ Explanation: the insert function needs two arguments, the index, and the object
to insert.
Q 6 - What is the output of the code? try: list = 5[0]+5[10] x = list[9] print('Done!') except
IndexError: print('Index out of Bond! ') else: print('Nothing is wrong!') finally: print('Finally
block!')**
●​ A - ‘Finally Block!'
●​ B - ‘Done!' follow by ‘Nothing is wrong!'
●​ C - ‘Nothing is wrong!' followed by ‘Finally block!'
●​ D - ‘Done!' follow by ‘Nothing is wrong!' followed by ‘Finally block'.
●​ Correct Answer: D - ‘Done!' follow by ‘Nothing is wrong!' followed by ‘Finally block'.
○​ Explanation: the list has 10 elements, the index 9 is the last element, so the try
block runs completely, then the else block runs, and the finally block always runs.
Q 7 - Analyze the code − print('Recursive Function') def factorial(n): return(n*factorial(n-1))
factorial(4)
●​ A - Recursive Function 24.
●​ B - Recursive Function.
●​ C - Function runs infinitely and causes a StackOverflowError.
●​ D - Syntax Error.
●​ Correct Answer: C - Function runs infinitely and causes a StackOverflowError.
○​ Explanation: There's no base case in the recursive function, so it never stops.
Q 8 - Choose the correct syntax for reading from a text file stored in ‘‘c:\scores.txt'' ?
●​ A - Infile = open(''c:\scores.txt'',''r'')
●​ B - Infile = open(file=''c:\\scores.txt'', ''r'')
●​ C - Infile = open.file(''c:\scores.txt'',''r'')
●​ D - Infile = open(''c:\scores.txt'', ''r'')
●​ Correct Answer: D - Infile = open(''c:\scores.txt'', ''r'')
○​ Explanation: Python needs double backslashes or raw strings to represent
Windows file paths.
Q 9 - Using the pack manager, how you can you put the components in a container in the same
row?
●​ A - Component.pack(side= ''LEFT'')
●​ B - Component.pack(''Left '')
●​ C - Component.pack(side=LEFT)
●​ D - Component.pack(Left-side)
●​ Correct Answer: A - Component.pack(side= ''LEFT'')
○​ Explanation: The side parameter with the string value 'LEFT' (or 'RIGHT') is used
to arrange components horizontally.
Q 10 - What is the value of a, b, c in the given below code? a, b = c = 2 + 2, ''TutorialsPoint''
●​ A - a=4, 'TutorialsPoint' b= 4, 'TutorialsPoint' c= 4, 'TutorialsPoint'
●​ B - a=2 b= 'TutorialsPoint' c=4, 'TutorialsPoint'
●​ C - a=4 b= 'TutorialsPoint' c=4, 'TutorialsPoint'
●​ D - a=4 b= 'TutorialsPoint' c= NULL.
●​ Correct Answer: C - a=4 b= 'TutorialsPoint' c=4, 'TutorialsPoint'
○​ Explanation: The comma operator creates a tuple. The tuple is unpacked to a
and b. c is assigned the entire tuple.

Python MCQ Practice links:

https://www.geeksforgeeks.org/python-multiple-choice-questions

https://www.geeksforgeeks.org/python-multiple-choice-questions

https://www.ccbp.in/blog/articles/python-mcqs

https://www.placementpreparation.io/mcq/python

https://www.tpointtech.com/python-mcq

https://www.examveda.com/mcq-question-on-python-program

https://www.interviewbit.com/python-mcq

https://www.indiabix.com/python-programming/questions-and-answ

Python Debugging:
1. Bug: Incorrect loop range

Python

# Buggy
for i in range(1, 5):
print(i)

# Corrected
for i in range(1, 6):
print(i)
2. Bug: String concatenation error

Python

# Buggy
name = "Alice"
age = 30
print("My name is " + name + " and I am " + age)

# Corrected
name = "Alice"
age = 30
print("My name is " + name + " and I am " + str(age))
3. Bug: Incorrect comparison

Python

# Buggy
x = 10
if x = 5:
print("x is 5")

# Corrected
x = 10
if x == 5:
print("x is 5")
4. Bug: Missing colon in if statement

Python

# Buggy
x=5
if x > 0
print("Positive")

# Corrected
x=5
if x > 0:
print("Positive")
5. Bug: Indentation error

Python
# Buggy
def my_func():
print("Hello")

# Corrected
def my_func():
print("Hello")
6. Bug: Using undefined variable

Python

# Buggy
print(y)

# Corrected
y = 10
print(y)
7. Bug: Incorrect list indexing

Python

# Buggy
my_list = [1, 2, 3]
print(my_list[3])

# Corrected
my_list = [1, 2, 3]
print(my_list[2])
8. Bug: Division by zero

Python

# Buggy
x = 10
y=0
result = x / y
print(result)

# Corrected
x = 10
y=0
if y != 0:
result = x / y
print(result)
else:
print("Division by zero error")
9. Bug: Incorrect function call

Python

# Buggy
def add(a, b):
return a + b

result = add(10)
print(result)

# Corrected
def add(a, b):
return a + b

result = add(10, 5)
print(result)
10. Bug: Incorrect tuple unpacking

Python

# Buggy
my_tuple = (1, 2)
a, b, c = my_tuple
print(a, b, c)

# Corrected
my_tuple = (1, 2)
a, b = my_tuple
print(a, b)
11. Bug: Incorrect loop condition

Python

# Buggy
i=0
while i < 5:
i += 1

# Corrected
i=0
while i < 5:
print(i)
i += 1
12. Bug: Incorrect file opening mode

Python

# Buggy
file = open("myfile.txt", "r")
file.write("Hello")
file.close()

# Corrected
file = open("myfile.txt", "w")
file.write("Hello")
file.close()
13. Bug: Incorrect dictionary access

Python

# Buggy
my_dict = {"a": 1, "b": 2}
print(my_dict["c"])

# Corrected
my_dict = {"a": 1, "b": 2}
print(my_dict.get("c")) #or print(my_dict["a"])
14. Bug: Incorrect type conversion

Python

# Buggy
x = "10"
y=5
result = x + y

# Corrected
x = "10"
y=5
result = int(x) + y
15. Bug: Missing return statement

Python

# Buggy
def multiply(a, b):
a*b

result = multiply(2, 3)
print(result)

# Corrected
def multiply(a, b):
return a * b

result = multiply(2, 3)
print(result)
16. Bug: Incorrect string formatting

Python

# Buggy
name = "Bob"
print("Hello, %s")

# Corrected
name = "Bob"
print("Hello, %s" % name)
17. Bug: Incorrect use of break

Python

# Buggy
for i in range(5):
if i == 3:
break
print(i)
print("Finished") #This is outside the loop and will always run

# Corrected
for i in range(5):
if i == 3:
break
print(i)
18. Bug: Incorrect use of continue

Python

# Buggy
for i in range(5):
continue
print(i)

# Corrected
for i in range(5):
if i == 2:
continue
print(i)
19. Bug: Incorrect use of try-except

Python

# Buggy
try:
x = 10 / 0
except:
print("Error")

# Corrected
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero error")
20. Bug: Incorrect list modification during iteration

Python

# Buggy
my_list = [1, 2, 3, 4]
for item in my_list:
if item % 2 == 0:
my_list.remove(item)
print(my_list)

# Corrected
my_list = [1, 2, 3, 4]
new_list = [item for item in my_list if item % 2 != 0]
print(new_list)
21. Bug: Incorrect use of global keyword

Python

# Buggy
x = 10
def modify():
x=5

modify()
print(x)

# Corrected
x = 10
def modify():
global x
x=5

modify()
print(x)
22. Bug: Incorrect use of lambda

Python

# Buggy
add = lambda x, y: x + y
print(add(10))

# Corrected
add = lambda x, y: x + y
print(add(10, 5))
23. Bug: Incorrect use of map

Python

# Buggy
my_list = [1, 2, 3]
result = map(lambda x: x * 2, my_list)
print(result)

# Corrected
my_list = [1, 2, 3]
result = list(map(lambda x: x * 2, my_list))
print(result)
24. Bug: Incorrect use of filter

Python

# Buggy
my_list = [1, 2, 3, 4]
result = filter(lambda x: x % 2 == 0, my_list)
print(result)

# Corrected
my_list = [1, 2, 3, 4]
result = list(filter(lambda x: x % 2 == 0, my_list))
print(result)
25. Bug: Incorrect use of reduce (Python 3)

Python

# Buggy
from functools import reduce
my_list = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, my_list)
print(result)

# Corrected
from functools import reduce
my_list = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, my_list)
print(result) #In this case it was just a reminder that reduce needs import in python 3.
26. Bug: Incorrect use of zip

Python

# Buggy
list1 = [1, 2, 3]
list2 = ["a", "b"]
result = zip(list1, list2)
print(result)

# Corrected

Python

# Corrected
list1 = [1, 2, 3]
list2 = ["a", "b"]
result = list(zip(list1, list2))
print(result)

27. Bug: Incorrect use of enumerate


Python

# Buggy
my_list = ["a", "b", "c"]
for item in enumerate(my_list):
print(item)

# Corrected
my_list = ["a", "b", "c"]
for index, item in enumerate(my_list):
print(index, item)
28. Bug: Incorrect use of sorted

Python

# Buggy
my_list = [3, 1, 4, 2]
sorted(my_list)
print(my_list)

# Corrected
my_list = [3, 1, 4, 2]
my_list = sorted(my_list)
print(my_list)
29. Bug: Incorrect use of reversed

Python

# Buggy
my_list = [1, 2, 3]
reversed(my_list)
print(my_list)

# Corrected
my_list = [1, 2, 3]
my_list = list(reversed(my_list))
print(my_list)
30. Bug: Incorrect string slicing

Python

# Buggy
my_string = "hello"
print(my_string[5])

# Corrected
my_string = "hello"
print(my_string[4])
31. Bug: Incorrect list comprehension

Python

# Buggy
my_list = [i for i in range(5) if i % 2]
print(my_list)

# Corrected
my_list = [i for i in range(5) if i % 2 != 0] # or [i for i in range(5) if i % 2 == 1]
print(my_list)
32. Bug: Incorrect set comprehension

Python

# Buggy
my_set = {i for i in [1, 2, 2, 3]}
print(my_list)

# Corrected
my_set = {i for i in [1, 2, 2, 3]}
print(my_set)
33. Bug: Incorrect dictionary comprehension

Python

# Buggy
my_dict = {i: i * 2 for i in range(3)}
print(my_set)

# Corrected
my_dict = {i: i * 2 for i in range(3)}
print(my_dict)
34. Bug: Incorrect use of is operator

Python

# Buggy
a = [1, 2, 3]
b = a[:]
print(a is b)

# Corrected
a = [1, 2, 3]
b = a[:]
print(a == b) # Use == to check for equality of content, 'is' checks for identity.
35. Bug: Incorrect use of in operator with strings

Python

# Buggy
my_string = "hello"
if "H" in my_string:
print("Found")

# Corrected
my_string = "hello"
if "h" in my_string:
print("Found")
36. Bug: Incorrect use of in operator with lists

Python

# Buggy
my_list = [1, 2, 3]
if "1" in my_list:
print("Found")

# Corrected
my_list = [1, 2, 3]
if 1 in my_list:
print("Found")
37. Bug: Incorrect use of in operator with dictionaries

Python

# Buggy
my_dict = {"a": 1, "b": 2}
if 1 in my_dict:
print("Found")

# Corrected
my_dict = {"a": 1, "b": 2}
if "a" in my_dict:
print("Found") # or if 1 in my_dict.values():
38. Bug: Incorrect use of assert

Python

# Buggy
x=5
assert x > 10

# Corrected
x=5
assert x < 10
39. Bug: Incorrect use of with statement

Python

# Buggy
file = open("myfile.txt", "w")
with file:
file.write("Hello")

# Corrected
with open("myfile.txt", "w") as file:
file.write("Hello")
40. Bug: Incorrect use of try-finally

Python

# Buggy
try:
x = 10 / 0
finally:
print("Cleanup")

# Corrected
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Cleanup")
41. Bug: Incorrect use of class inheritance
Python

# Buggy
class Animal:
def speak(self):
print("Animal sound")

class Dog:
def speak(self):
print("Woof")

dog = Dog()
dog.speak()

# Corrected
class Animal:
def speak(self):
print("Animal sound")

class Dog(Animal):
def speak(self):
print("Woof")

dog = Dog()
dog.speak()
42. Bug: Incorrect use of super()

Python

# Buggy
class Parent:
def __init__(self, name):
self.name = name

class Child(Parent):
def __init__(self, name, age):
self.age = age

child = Child("Bob", 10)


print(child.name)

# Corrected
class Parent:
def __init__(self, name):
self.name = name

class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age

child = Child("Bob", 10)


print(child.name)
43. Bug: Incorrect use of default arguments

Python

# Buggy
def append_item(my_list, item=[]):
my_list.append(item)
return my_list

print(append_item([1], 2))
print(append_item([3], 4))

# Corrected
def append_item(my_list, item=None):
if item is None:
item = []
my_list.append(item)
return my_list

print(append_item([1], 2))
print(append_item([3], 4))
44. Bug: Incorrect use of variable scope within loops

Python

# Buggy
for i in range(3):
x=i

print(x)

# Corrected
x = None # or x = 0 or x = -1 or whatever you want the default to be.
for i in range(3):
x=i
print(x)
45. Bug: Incorrect use of format with positional arguments

Python

# Buggy
print("{}, {}".format(1))

# Corrected
print("{}, {}".format(1, 2))
46. Bug: Incorrect use of format with keyword arguments

Python

# Buggy
print("{name}".format(age=30))

# Corrected
print("{name}".format(name="Alice"))
47. Bug: Incorrect use of join with non-string elements

Python

# Buggy
my_list = [1, 2, 3]
print(", ".join(my_list))

# Corrected
my_list = [1, 2, 3]
print(", ".join(map(str, my_list)))
48. Bug: Incorrect use of split with incorrect delimiter

Python

# Buggy
my_string = "apple,banana;orange"
print(my_string.split(","))

# Corrected
my_string = "apple,banana;orange"
print(my_string.split(";")) #or split(",") or split(";") depending on the intended
Coding:
Right Triangle (90 degrees):
*
**
***
****
*****

Inverted Right Triangle (90 degrees):


*****
****
***
**
*

Normal Triangle:
*
***
*****
*******
*********

Inverted Normal Triangle:


*********
*******
*****
***
*

Diamond:
*
***
*****
*******
*****
***
*
Hollow Right Triangle
*
**
**
* *
*****

Hollow Pyramid
*
**
* *
* *
*********

Increasing Number Triangle:


1
12
123
1234

Repeating Number Triangle:


1
22
333
4444

Pyramid of Numbers:
1
212
32123
4321234

Pascal's Triangle:
1
11
121
1331
14641

Number Diamond:
1
212
32123
212
1

Floyd’s Triangle
1
23
456
7 8 9 10

Alphabet Triangle:
A
AB
ABC
ABCD

Alphabet Pyramid:
A
ABA
ABCBA
ABCDCB
Pattern with alternating 0 and 1
1
01
101
0101

Matrix:
1.​ Write a program to add two matrices of the same dimensions.
2.​ Write a program to multiply two matrices.
3.​ Write a program to check if a matrix is a square matrix.
4.​ Write a program to check if a matrix is an identity matrix.
5.​ Write a program to check if a matrix is a symmetric matrix.
6.​ Write a program to find the sum of each row in a matrix.
7.​ Write a program to find the sum of each column in a matrix.
8.​ Write a program to find the largest element in a matrix.
9.​ Write a program to find the smallest element in a matrix.
10.​Write a program to check if two matrices are equal.
DS:

1.​ Linked List Questions: Implement,Append,Add,Delete,Pop


2.​ Stack Questions :Implement a Stack,Push,Pop,Stack Size
3.​ Queue Questions: Implement a Queue,Enqueue,Dequeue
4.​ Binary Tree Questions :Implementation

You might also like