0% found this document useful (0 votes)
2 views

python_mock

The document provides a comprehensive overview of Python programming concepts, covering topics from basic definitions to advanced features. It includes explanations of fundamental elements such as data types, functions, and control structures, as well as practical examples. The content serves as a reference for both beginners and experienced programmers looking to understand or refresh their knowledge of Python.

Uploaded by

Yashraj Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python_mock

The document provides a comprehensive overview of Python programming concepts, covering topics from basic definitions to advanced features. It includes explanations of fundamental elements such as data types, functions, and control structures, as well as practical examples. The content serves as a reference for both beginners and experienced programmers looking to understand or refresh their knowledge of Python.

Uploaded by

Yashraj Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

These questions cover a wide range of topics in Python, from basic concepts to more advanced topics.

Here are brief answers and explanations to some of them:

1. **What is Python? What are the benefits of using Python?**


- Python is a high-level, interpreted programming language known for its readability, simplicity, and
versatility. Benefits include easy syntax, a large standard library, and a supportive community.

2. **What is an Interpreted language?**


- An interpreted language is a type of programming language where most of its implementations
execute instructions directly, without the need to compile the program into machine-language instructions
beforehand.

3. **What is Indentation in Python?**


- Indentation in Python refers to the spaces at the beginning of a code line. It is used to define the level
of nesting, such as in loops, functions, and conditionals.

4. **What is mutable and immutable in Python?**


- Mutable objects can be changed after creation (e.g., lists, dictionaries), while immutable objects
cannot be changed (e.g., tuples, strings).

5. **What is Scope in Python?**


- Scope refers to the region of the code where a variable is accessible. Python uses the LEGB rule to
determine the scope: Local, Enclosing, Global, and Built-in.

6. **What are lists and tuples? What is the key difference between the two?**
- Both are sequence data types in Python. The key difference is that lists are mutable, while tuples are
immutable.

7. **What are the common built-in data types in Python?**


- Common built-in data types include integers, floats, strings, lists, tuples, dictionaries, sets, and
booleans.

8. **What is ‘pass‘ in Python?**


- ‘pass‘ is a null operation; it does nothing when executed. It is used as a placeholder in code.

9. **What are modules and packages in Python?**


- A module is a single Python file that can be imported and used. A package is a collection of modules
in directories that give a structure to the module namespace.

10. **How do you assign multiple variables in one line in Python?**


- You can assign multiple variables in one line by separating the variable names with commas, for
example: ‘a, b, c = 1, 2, 3‘.

11. **What is the use of ‘self‘ in Python?**


- ‘self‘ is used in instance methods to refer to the instance calling the method. It allows access to the
attributes and methods of the class in Python.

12. **What is ‘__init__‘?**


- ‘__init__‘ is a special method in Python classes that is called when an object is created. It initializes
the object’s state.

13. **What is ‘break‘, ‘continue‘, and ‘pass‘ in Python?**


- ‘break‘ exits the nearest enclosing loop. ‘continue‘ skips the rest of the loop’s code and starts the next
iteration. ‘pass‘ is a no-operation statement.
14. **What does the following code do: ‘a = b = c = 5‘?**
- This code assigns the value ‘5‘ to variables ‘a‘, ‘b‘, and ‘c‘ simultaneously.

15. **What is docstring in Python?**


- A docstring is a string literal that appears as the first statement in a module, function, class, or method
definition, used to document the object.

16. **What is slicing in Python?**


- Slicing allows you to access a part of a sequence (like a list, tuple, or string) by specifying a range of
indices.

17. **Which symbol is used for single-line comments in Python?**


- The ‘#‘ symbol is used for single-line comments.

18. **How are multi-line comments written in Python?**


- Multi-line comments can be written using triple quotes ‘""" comment """‘ or ‘’’’ comment ’’’‘.

19. **How is memory managed in Python?**


- Memory in Python is managed by the Python memory manager, with the help of an inbuilt garbage
collector.

20. **What will be the result of ‘int(’10’)‘?**


- The result will be the integer ‘10‘.

21. **Which operator is used for exponentiation in Python?**


- The ‘**‘ operator is used for exponentiation.

22. **What is the output of ‘5 // 2‘?**


- The output is ‘2‘, which is the result of floor division.

23. **What are Dict and List comprehensions?**


- Comprehensions are a concise way to create dictionaries or lists. List comprehension: ‘[x for x in
range(5)]‘. Dict comprehension: ‘{x: x**2 for x in range(5)}‘.

24. **What is lambda in Python? Why is it used?**


- A lambda function is a small anonymous function defined with the ‘lambda‘ keyword. It is used for
creating small, single-use functions without defining a full function.

25. **What is the range in Python?**


- The ‘range()‘ function generates a sequence of numbers, which is often used in loops.

26. **What are keyword arguments in Python?**


- Keyword arguments are arguments passed to a function by explicitly specifying the name of the
parameter.

27. **What are generators in Python?**


- Generators are iterators that produce items on-the-fly and yield one value at a time using the ‘yield‘
keyword.

28. **What are variable arguments in Python?**


- Variable arguments allow a function to accept an arbitrary number of arguments using ‘*args‘ for
positional arguments and ‘**kwargs‘ for keyword arguments.

29. **What is the use of ‘dir()‘ function?**


- The ‘dir()‘ function returns a list of attributes and methods of an object.
30. **What is the difference between ‘.py‘ and ‘.pyc‘ files?**
- ‘.py‘ files are Python source files, while ‘.pyc‘ files are compiled Python files that Python creates to
optimize performance.

31. **How is Python interpreted?**


- Python code is executed line by line by the Python interpreter. The interpreter reads the code,
compiles it into bytecode, and then executes it.

32. **How are arguments passed by value or by reference in Python?**


- In Python, arguments are passed by reference, but the reference is passed by value. Mutable objects
can be changed inside a function, while immutable objects cannot.

33. **What are iterators in Python?**


- Iterators are objects that can be iterated over, generating one item at a time from a sequence.

34. **Explain how to make a module in Python?**


- A module is a Python file containing definitions and statements. To create a module, write Python
code in a ‘.py‘ file and import it using the ‘import‘ statement in other files.

35. **Explain ‘split()‘ and ‘join()‘ functions in Python?**


- ‘split()‘ divides a string into a list of substrings based on a delimiter. ‘join()‘ combines elements of a list
into a single string with a specified separator.

36. **What are logical operators in Python?**


- Logical operators include ‘and‘, ‘or‘, and ‘not‘, used to combine or negate Boolean expressions.

37. **What are negative indexes and why are they used?**
- Negative indexes in Python allow you to access elements from the end of a sequence, where ‘-1‘
represents the last element.

38. **How do you create a class in Python?**


- You can create a class using the ‘class‘ keyword followed by the class name and a colon. The body of
the class contains attributes and methods.

39. **How does inheritance work in Python? Explain it with an example.**


- Inheritance allows one class (child class) to inherit attributes and methods from another class (parent
class). Example:
‘‘‘python
class Parent:
def __init__(self):
self.value = "Parent"
def show(self):
print(self.value)

class Child(Parent):
def __init__(self):
super().__init__()
self.value = "Child"

c = Child()
c.show() # Output: Child
‘‘‘

40. **How do you access parent members in the child class?**


- Parent members can be accessed using the ‘super()‘ function or by referring to the parent class name
directly.

41. **What is the result of ‘5 % 2‘?**


- The result is ‘1‘, which is the remainder of the division.

42. **Is it possible to call a parent class without its instance creation?**
- Yes, using ‘super()‘ in a subclass allows you to call a parent class method without creating an
instance of the parent class.

43. **Which keyword is used to start a conditional statement in Python?**


- The ‘if‘ keyword is used to start a conditional statement.

44. **What does the ‘continue‘ statement do in a loop?**


- The ‘continue‘ statement skips the current iteration of the loop and moves to the next iteration.

45. **Why is ‘finalize‘ used?**


- ‘finalize‘ is not a standard Python keyword. It might refer to cleaning up resources or executing code
when an object is about to be destroyed (usually achieved with destructors or the ‘__del__‘ method in
Python).

46. **What is ‘__init__‘ method in Python?**


- ‘__init__‘ is the constructor method in Python classes. It is automatically called when an instance of a
class is created.

47. **Which of the following statements will convert a string ‘’123’‘ to

an integer?**
- ‘int(’123’)‘ will convert the string ‘’123’‘ to the integer ‘123‘.

48. **What do you know about Pandas?**


- Pandas is a Python library used for data manipulation and analysis, offering data structures like
Series and DataFrame to handle and analyze structured data.

49. **What does the ‘pass‘ statement do in Python?**


- The ‘pass‘ statement is a null operation; nothing happens when it executes.

50. **How do you declare a dictionary in Python?**


- A dictionary can be declared using curly braces ‘{}‘ with key-value pairs, for example: ‘my_dict =
{"key1": "value1", "key2": "value2"}‘.

51. **Which method can be used to add an element to a list?**


- The ‘append()‘ method adds an element to the end of a list.

52. **How will you identify and deal with missing values in a DataFrame?**
- You can identify missing values using methods like ‘isnull()‘ or ‘notnull()‘. To deal with them, you can
either fill them using ‘fillna()‘ or drop them using ‘dropna()‘.

53. **What is the result of ‘3 ** 2‘?**


- The result is ‘9‘, as ‘**‘ is the exponentiation operator.

54. **How can you check the type of a variable in Python?**


- You can check the type of a variable using the ‘type()‘ function.

55. **What is the purpose of the ‘range()‘ function in a for loop?**


- The ‘range()‘ function generates a sequence of numbers, often used to iterate over with a ‘for‘ loop.

56. **Which symbol is used for floor division in Python?**


- The ‘//‘ symbol is used for floor division.

57. **How would you convert a float ‘3.14‘ to an integer?**


- Use the ‘int()‘ function: ‘int(3.14)‘ will return ‘3‘.

58. **Which operator is used for string concatenation?**


- The ‘+‘ operator is used for string concatenation.

59. **What do you understand by NumPy?**


- NumPy is a Python library used for numerical computing, offering support for large, multi-dimensional
arrays and matrices, along with a collection of mathematical functions.

60. **How are NumPy arrays advantageous over Python lists?**


- NumPy arrays are more memory-efficient, faster, and support more mathematical operations than
Python lists.

61. **What is the output of ‘"hello" * 3‘?**


- The output is ‘"hellohellohello"‘.

62. **How do you define a function in Python?**


- A function is defined using the ‘def‘ keyword, followed by the function name and parentheses.
Example:
‘‘‘python
def my_function():
print("Hello, World!")
‘‘‘

63. **What does the ‘len()‘ function do?**


- The ‘len()‘ function returns the length (number of items) of an object such as a string, list, tuple, etc.

64. **Which function is used to read input from the user in Python?**
- The ‘input()‘ function is used to read input from the user.

65. **What is the result of the following expression: ‘2 + 3 * 4‘?**


- The result is ‘14‘ because multiplication has higher precedence than addition.

66. **How do you include a comment in Python code?**


- You include a comment by using the ‘#‘ symbol at the beginning of the comment.

67. **How do you define a tuple in Python?**


- A tuple is defined using parentheses ‘()‘ with elements separated by commas, for example: ‘my_tuple
= (1, 2, 3)‘.

68. **What does the ‘break‘ statement do in a loop?**


- The ‘break‘ statement exits the nearest enclosing loop.

69. **Differentiate between a package and a module in Python.**


- A module is a single file of Python code, whereas a package is a directory containing multiple
modules, along with a special ‘__init__.py‘ file.

70. **What are some of the most commonly used built-in modules in Python?**
- Common built-in modules include ‘os‘, ‘sys‘, ‘math‘, ‘datetime‘, and ‘re‘.
71. **What are lambda functions?**
- Lambda functions are small, anonymous functions defined using the ‘lambda‘ keyword, used for
creating quick, throwaway functions.

72. **How can you generate random numbers?**


- You can generate random numbers using the ‘random‘ module in Python.

73. **Can you easily check if all characters in the given string are alphanumeric?**
- Yes, using the ‘isalnum()‘ method of a string.

74. **Which method would you use to remove a specific item from a list?**
- The ‘remove()‘ method can be used to remove a specific item from a list.

75. **How can you merge two dictionaries in Python?**


- You can merge two dictionaries using the ‘update()‘ method or the ‘{**dict1, **dict2}‘ syntax.

76. **What is the output of ‘"hello".upper()‘?**


- The output is ‘"HELLO"‘.

77. **Define PIP.**


- PIP stands for "Pip Installs Packages" and is the package manager for Python, used to install and
manage Python packages.

78. **Which data type is mutable in Python?**


- Lists, dictionaries, and sets are mutable data types in Python.

79. **How do you access the last element of a list in Python?**


- You can access the last element of a list using the index ‘-1‘, for example: ‘my_list[-1]‘.

80. **How can you update an element at index 2 in a list named ‘my_list‘?**
- You can update the element using assignment: ‘my_list[2] = new_value‘.

81. **Write a Python function that takes a variable number of arguments.**


- Example:
‘‘‘python
def my_function(*args):
for arg in args:
print(arg)
‘‘‘

82. **Write a program that takes a sequence of numbers and checks if all numbers are unique.**
- Example:
‘‘‘python
def all_unique(numbers):
return len(numbers) == len(set(numbers))
‘‘‘

83. **How do you delete an item from a list by index?**


- You can delete an item by index using the ‘del‘ statement: ‘del my_list[index]‘.

84. **Write a program to check and return the pairs of a given array ‘A‘ whose sum value is equal to a
target value ‘N‘.**
- Example:
‘‘‘python
def find_pairs(A, N):
pairs = []
for i in range(len(A)):
for j in range(i+1, len(A)):
if A[i] + A[j] == N:
pairs.append((A[i], A[j]))
return pairs
‘‘‘

85. **How do you access a value in a dictionary using a key?**


- You access a value using the key: ‘my_dict[key]‘.

86. **What will be the result of slicing the list ‘[10, 20, 30, 40, 50]‘ with ‘list[1:4]‘?**
- The result will be ‘[20, 30, 40]‘.

87. **Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 ’b’s.**
- Example using regular expressions:
‘‘‘python
import re
def match_string(s):
pattern = r’a(b{4,8})’
return re.match(pattern, s)
‘‘‘

88. **Which method would you use to get the number of elements in a tuple?**
- The ‘len()‘ function is used to get the number of elements in a tuple.

89. **Write a Program to combine two different dictionaries. While combining, if you find the same keys,
you can add the values of these same keys. Output the new dictionary.**
- Example:
‘‘‘python
def combine_dicts(dict1, dict2):
combined = dict1.copy()
for key, value in dict2.items():
if key in combined:
combined[key] += value
else:
combined[key] = value
return combined
‘‘‘

90. **How do you concatenate two lists ‘list1‘ and ‘list2‘?**


- You can concatenate two lists using the ‘+‘ operator: ‘list1 + list2‘.

91. **What will ‘len([1, 2, 3])‘ return?**


- It will return ‘3‘.

92. **How do you convert a tuple to a list?**


- You can convert a tuple to a list using the ‘list()‘ function: ‘list(my_tuple)‘.

93. **What does the ‘pop()‘ method do in a list?**


- The ‘pop()‘ method removes and returns the last item of a list or an item at a specified index.

94. **What will be the result of ‘list[::2]‘ if ‘list = [10, 20, 30, 40, 50]‘?**
- The result will be ‘[10, 30, 50]‘.
95. **How do you remove all elements from a list?**
- You can remove all elements using the ‘clear()‘ method: ‘my_list.clear

()‘.

96. **What will ‘list[::-1]‘ return if ‘list = [1, 2, 3]‘?**


- It will return the reversed list ‘[3, 2, 1]‘.

97. **What is the result of ‘list[1:4]‘ if ‘list = [1, 2, 3, 4, 5]‘?**


- The result will be ‘[2, 3, 4]‘.

98. **How do you slice a tuple from index 1 to index 3?**


- You slice a tuple using the slicing syntax: ‘my_tuple[1:4]‘.

99. **How do you find the maximum value in a list?**


- You can find the maximum value using the ‘max()‘ function: ‘max(my_list)‘.
100.

‘‘‘python
my_list = [10, 20, 30, 40, 50]
max_value = max(my_list)
print(max_value)
‘‘‘

In this example, ‘max_value‘ will be ‘50‘, as it is the highest number in the list.

You might also like