FREE Core Python Batch Starts in Enroll Now | +91-7780122379 | +91-7989593536

Core Python

  • Q1: What is Python?
    A: Python is a high-level, interpreted programming language known for its simplicity and readability. It emphasizes code readability and uses indentation rather than brackets or braces for block structure.
  • Q2: What are the key features of Python?
    A: The key features of Python include its simplicity, readability, extensive standard library, dynamic typing, automatic memory management, and support for multiple programming paradigms (procedural, object-oriented, and functional).
  • Q3: What is PEP 8?
    A: PEP 8 is the official style guide for Python code. It provides guidelines on how to format Python code to enhance its readability and maintainability.
  • Q4: What is the difference between Python 2 and Python 3?
    A: Python 2 and Python 3 are two major versions of Python that have some differences. Python 3 introduced several backward-incompatible changes to improve the language's design and fix some inconsistencies. Python 2 is no longer maintained, and it is recommended to use Python 3 for new projects.
  • Q5: How do you comment in Python?
    A: In Python, you can use the "#" character to write a single-line comment. For multi-line comments, you can enclose the text within triple quotes ('''comment''').
  • Q6: How do you declare and initialize variables in Python?
    A: In Python, you can declare and initialize variables in a single line. For example: makefile Copy code name = "John" age = 25 What are the different data types in Python? Python supports several data types, including integers, floats, strings, booleans, lists, tuples, dictionaries, and sets.
  • Q7: What is the difference between a list and a tuple?
    A: Lists and tuples are both used to store multiple items in Python, but the main difference is that lists are mutable (can be modified), while tuples are immutable (cannot be modified).
  • Q8: How do you access elements in a list or a tuple?
    A: Elements in a list or a tuple can be accessed using indexing. The index starts at 0, so the first element can be accessed with index 0. For example, my_list[0] will access the first element of the list.
  • Q9: What is slicing in Python?
    A: Slicing is a way to extract a portion of a list, tuple, or string in Python. It is done by specifying the start and end indices, separated by a colon, inside square brackets. For example, my_list[1:4] will return a new list with elements from index 1 to index 3.
  • Q10: What is a dictionary in Python?
    A: A dictionary in Python is an unordered collection of key-value pairs. It is mutable and can be accessed, modified, and deleted using the key. The keys in a dictionary must be unique.
  • Q11: How do you iterate over a dictionary in Python?
    A: You can iterate over a dictionary using a for loop. By default, the loop variable will represent the keys of the dictionary. For example: bash Copy code my_dict = {'name': 'John', 'age': 25} for key in my_dict: print(key, my_dict[key])
  • Q12: What is a module in Python?
    A: A module in Python is a file containing Python code that defines functions, classes, and variables. It allows code reuse and organization.
  • Q13: How do you import modules in Python?
    A: In Python, you can import modules using the import statement. For example, import math imports the math module, and you can then use functions and variables defined in the math module by prefixing them with math..
  • Q14: What is a package in Python?
    A: A package in Python is a way to organize related modules into a directory hierarchy. It allows for better code organization and reusability.
  • Q15: How do you handle exceptions in Python?
    A: Exceptions in Python can be handled using try-except blocks. The code that might raise an exception is placed inside the try block, and if an exception occurs, the corresponding except block is executed to handle the exception.
  • Q16: What is the difference between append() and extend() methods in Python?
    A: The append() method is used to add a single element to the end of a list, while the extend() method is used to append multiple elements from an iterable (such as a list or tuple) to the end of a list.
  • Q17: How do you read input from the user in Python?
    A: You can use the input() function in Python to read input from the user. The function prompts the user for input and returns the entered value as a string.
  • Q18: What are lambda functions in Python?
    A: Lambda functions, also known as anonymous functions, are functions without a name. They are defined using the lambda keyword and are typically used when a small function is needed for a short period of time.
  • Q19: What is the difference between shallow copy and deep copy in Python?
    A: A shallow copy creates a new object that references the original object, while a deep copy creates a new object with a completely independent copy of the original object and all its nested objects.
  • Q20: How do you handle file operations in Python?
    A: File operations in Python can be performed using the built-in open() function. It allows you to open files for reading, writing, or appending data.
  • Q21: What is the __init__() method in Python?
    A: The __init__() method is a special method in Python classes that is automatically called when an object of the class is created. It is used to initialize the object's attributes.
  • Q22: What is the difference between instance methods and class methods in Python?
    A: Instance methods are methods that operate on an instance of a class and can access and modify the instance's attributes. Class methods are methods that operate on the class itself and can access and modify class-level attributes.
  • Q23: What is the purpose of the self parameter in Python?
    A: The self parameter in Python represents the instance of the class. It is used to access and modify the instance's attributes and methods.
  • Q24: What is the difference between == and is operators in Python?
    A: The == operator compares the values of two objects for equality, while the is operator checks if two objects refer to the same memory location, i.e., if they are the same object.
  • Q25: How do you reverse a list in Python?
    A: You can reverse a list in Python using the reverse() method, which modifies the original list in place. Alternatively, you can use the slicing technique my_list[::-1] to create a reversed copy of the list.
  • Q26: What are decorators in Python?
    A: Decorators in Python are a way to modify the behavior of functions or classes without changing their source code. They are defined using the @decorator_name syntax and are placed before the function or class definition.
  • Q27: What is a generator in Python?
    A: A generator in Python is a special type of iterator that generates values on the fly rather than storing them in memory. It allows you to iterate over a sequence of values without creating the entire sequence upfront.
  • Q28: What is the yield keyword used for in Python?
    A: The yield keyword is used in generator functions to define a generator. It is used to yield a value from the generator and temporarily suspend the execution of the function.
  • Q29: What is the Global Interpreter Lock (GIL) in Python?
    A: The Global Interpreter Lock (GIL) is a mechanism used in CPython (the reference implementation of Python) to ensure that only one thread executes Python bytecode at a time. It prevents multiple threads from executing Python code in parallel, but it does not prevent multiple threads from running concurrently in native code or performing I/O operations.
  • Q30: What is the purpose of the pass statement in Python?
    A: The pass statement in Python is a placeholder statement that does nothing. It is used when a statement is required syntactically, but no action is needed.
  • Q31: What are the built-in data structures in Python?
    A: The built-in data structures in Python include lists, tuples, dictionaries, sets, and strings.
  • Q32: What is the difference between mutable and immutable objects in Python?
    A: Mutable objects can be modified after they are created, while immutable objects cannot be modified. For example, lists are mutable, while tuples are immutable.
  • Q33: What is a namespace in Python?
    A: A namespace in Python is a mapping from names to objects. It allows you to organize and differentiate between different names and avoid naming conflicts.
  • Q34: What is the __name__ variable in Python?
    A: The __name__ variable is a built-in variable in Python that represents the name of the current module. When a module is run directly, its __name__ variable is set to "__main__". When a module is imported, its __name__ variable is set to the module's name.
  • Q35: How do you handle circular imports in Python?
    A: Circular imports occur when two or more modules depend on each other. To handle circular imports in Python, you can use techniques like importing inside functions or methods, using importlib or importlib.reload() to dynamically import modules, or refactoring the code to eliminate circular dependencies.
  • Q36: How do you generate random numbers in Python?
    A: You can generate random numbers in Python using the random module. The module provides functions like random(), randint(), and choice() to generate random numbers or select random elements from a sequence.
  • Q37: What is the difference between is and == operators in Python?
    A: The is operator checks if two objects refer to the same memory location, while the == operator checks if two objects have the same value. In other words, is tests for object identity, and == tests for object equality.
  • Q38: What is the purpose of the super() function in Python?
    A: The super() function in Python is used to call a method from the parent class. It is typically used in the child class's method to invoke the parent class's method and perform additional operations.
  • Q39: What is the purpose of the __str__() method in Python?
    A: The __str__() method is a special method in Python classes that is used to represent an object as a string. It is called by the built-in str() function and the print() function.
  • Q40: How do you handle multiple exceptions in Python?
    A: You can handle multiple exceptions in Python using multiple except blocks or by specifying multiple exception types in a single except block separated by commas.
  • Q41: What is the difference between a shallow copy and a deep copy in Python?
    A: A shallow copy creates a new object that references the original object, while a deep copy creates a new object with a completely independent copy of the original object and all its nested objects.
  • Q42: How do you convert a string to an integer in Python?
    A: You can convert a string to an integer in Python using the int() function. For example, int("10") will convert the string "10" to the integer 10.
  • Q43: How do you convert a string to a float in Python?
    A: You can convert a string to a float in Python using the float() function. For example, float("3.14") will convert the string "3.14" to the float 3.14.
  • Q44: How do you convert a number to a string in Python?
    A: You can convert a number to a string in Python using the str() function. For example, str(10) will convert the integer 10 to the string "10".
  • Q45: What is the purpose of the join() method in Python?
    A: The join() method is used to concatenate a list of strings into a single string, using a specified delimiter. For example, ' '.join(['Hello', 'World']) will return the string 'Hello World'.
  • Q46: What is a set comprehension in Python?
    A: A set comprehension is a concise way to create a new set by specifying an expression and an iterable. For example, {x for x in range(10) if x % 2 == 0} will create a set containing even numbers from 0 to 8.
  • Q47: How do you remove duplicates from a list in Python?
    A: You can remove duplicates from a list in Python by converting it to a set using the set() function and then converting it back to a list. For example, list(set(my_list)) will remove duplicates from the list my_list.
  • Q48: What is the purpose of the with statement in Python?
    A: The with statement in Python is used for context management. It ensures that a context manager is properly initialized and cleaned up. It is commonly used with file operations to automatically close files after use.
  • Q49: How do you find the length of a string in Python?
    A: You can find the length of a string in Python using the len() function. For example, len("Hello") will return the integer 5.
  • Q50: What is the purpose of the enumerate() function in Python?
    A: The enumerate() function is used to iterate over a sequence while keeping track of the index of each item. It returns an iterator of tuples, where each tuple contains the index and the corresponding item.
  • Q51: How do you check if a string contains a substring in Python?
    A: You can use the in operator to check if a string contains a substring in Python. For example, "Hello" in "Hello World" will return True.
  • Q52: What is the difference between a generator function and a normal function in Python?
    A: A generator function is a special type of function that returns an iterator (a generator) when called. It uses the yield keyword to yield values one at a time, rather than returning a single value.
  • Q53: What is the purpose of the map() function in Python?
    A: The map() function is used to apply a given function to each item of an iterable and return an iterator of the results. It allows for concise and efficient data transformations.
  • Q54: How do you remove whitespace from the beginning and end of a string in Python?
    A: You can remove whitespace from the beginning and end of a string in Python using the strip() method. For example, " Hello ".strip() will return the string "Hello".
  • Q55: How do you check if a list is empty in Python?
    A: You can check if a list is empty in Python by using the if statement. For example: css Copy code my_list = [] if not my_list: print("The list is empty")
  • Q56: What is the purpose of the any() function in Python?
    A: The any() function is used to check if any element in an iterable is True. It returns True if at least one element is True, and False otherwise.
  • Q57: What is the purpose of the all() function in Python?
    A: The all() function is used to check if all elements in an iterable are True. It returns True if all elements are True, and False if at least one element is False.
  • Q58: How do you convert a list of strings to a single string in Python?
    A: You can convert a list of strings to a single string in Python using the join() method. For example, ' '.join(['Hello', 'World']) will return the string 'Hello World'.
  • Q59: What is the purpose of the format() method in Python?
    A: The format() method is used to format strings in Python. It allows you to insert values into placeholders in a string, specify formatting options, and create dynamic strings.
  • Q60: How do you find the maximum and minimum values in a list in Python?
    A: You can find the maximum and minimum values in a list in Python using the max() and min() functions, respectively. For example, max([1, 2, 3]) will return 3, and min([1, 2, 3]) will return 1.
  • Q61: What is the purpose of the zip() function in Python?
    A: The zip() function is used to combine multiple iterables (such as lists, tuples, or strings) into a single iterator of tuples. It returns an iterator that generates tuples containing elements from the input iterables, paired together based on their indices.
  • Q62: How do you sort a list in Python?
    A: You can sort a list in Python using the sort() method, which modifies the original list in place, or using the sorted() function, which returns a new sorted list without modifying the original list. For example: makefile Copy code my_list = [3, 1, 2] my_list.sort() # Modifies the original list sorted_list = sorted(my_list) # Returns a new sorted list What is the purpose of the del statement in Python? The del statement is used to delete objects or items from a list or dictionary. It can also be used to delete variables or attributes.
  • Q63: How do you check if a file exists in Python?
    A: You can check if a file exists in Python using the os.path.exists() function. It returns True if the specified file or directory path exists, and False otherwise.
  • Q64: What is the purpose of the *args and **kwargs in Python function definitions?
    A: *args and **kwargs are used in function definitions to allow for variable-length argument lists. *args is used to pass a variable number of non-keyword arguments to a function, while **kwargs is used to pass a variable number of keyword arguments.
  • Q65: How do you get the current date and time in Python?
    A: You can get the current date and time in Python using the datetime module. The datetime.now() function returns a datetime object representing the current date and time.
  • Q66: How do you format a string as a date in Python?
    A: You can format a string as a date in Python using the strftime() method of the datetime object. It allows you to specify a format string to represent the date in a desired format.
  • Q67: What is the purpose of the re module in Python?
    A: The re module in Python provides support for regular expressions. It allows you to search, match, and manipulate strings based on specified patterns.
  • Q68: How do you check if a string matches a regular expression pattern in Python?
    A: You can use the re.match() function in Python to check if a string matches a regular expression pattern. It returns a match object if there is a match, or None otherwise.
  • Q69: What is the purpose of the random module in Python?
    A: The random module in Python provides functions for generating pseudo-random numbers. It allows you to generate random integers, floats, and make random selections from sequences.
  • Q70: How do you find the index of an item in a list in Python?
    A: You can find the index of an item in a list in Python using the index() method. It returns the index of the first occurrence of the specified item.
  • Q71: What is the purpose of the isinstance() function in Python?
    A: The isinstance() function is used to check if an object belongs to a specified class or any of its subclasses. It returns True if the object is an instance of the specified class, and False otherwise.
  • Q72: How do you convert a string to uppercase or lowercase in Python?
    A: You can convert a string to uppercase or lowercase in Python using the upper() and lower() methods, respectively. For example, "Hello".upper() will return "HELLO", and "Hello".lower() will return "hello".
  • Q73: What is the purpose of the continue statement in Python?
    A: The continue statement is used in loop statements (such as for and while) to skip the remaining code in the current iteration and move to the next iteration.
  • Q74: How do you iterate over two or more lists in Python?
    A: You can iterate over two or more lists in Python using the zip() function to combine the lists into a single iterator of tuples. For example: scss Copy code list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] for item1, item2 in zip(list1, list2): print(item1, item2) This will output: css Copy code 1 a 2 b 3 c
  • Q75: What is the purpose of the sum() function in Python?
    A: The sum() function is used to calculate the sum of all elements in an iterable, such as a list or tuple. It returns the total sum as a single value.
  • Q76: How do you convert a list to a tuple in Python?
    A: You can convert a list to a tuple in Python using the tuple() function. For example, tuple([1, 2, 3]) will convert the list [1, 2, 3] to the tuple (1, 2, 3).
  • Q77: What is the purpose of the json module in Python?
    A: The json module in Python provides functions for working with JSON (JavaScript Object Notation) data. It allows you to encode Python objects into JSON strings and decode JSON strings into Python objects.
  • Q78: How do you copy an object in Python?
    A: You can copy an object in Python using the copy module. The module provides functions like copy(), deepcopy(), and copy.deepcopy() to create shallow and deep copies of objects.
  • Q79: What is the purpose of the collections module in Python?
    A: The collections module in Python provides additional data structures and utility functions compared to the built-in data structures. It includes classes like Counter, deque, and namedtuple for specialized data handling.
  • Q80: How do you find the most common element in a list in Python?
    A: You can find the most common element in a list in Python using the Counter class from the collections module. The Counter class provides a convenient way to count the occurrences of elements in an iterable.
  • Q81: What is the purpose of the itertools module in Python?
    A: The itertools module in Python provides functions for efficient looping and iteration over various data structures. It includes functions like count(), cycle(), and permutations().
  • Q82: How do you read and write CSV files in Python?
    A: You can read and write CSV files in Python using the csv module. The module provides functions for reading data from CSV files into Python data structures and writing data from Python data structures into CSV files.
  • Q83: What is the purpose of the sys module in Python?
    A: The sys module in Python provides access to system-specific parameters and functions. It allows you to interact with the interpreter, access command-line arguments, and perform various system-related operations.
  • Q84: How do you measure the execution time of a Python program?
    A: You can measure the execution time of a Python program using the time module. The module provides functions like time() and perf_counter() to measure wall-clock time and process time, respectively.
  • Q85: What is the purpose of the logging module in Python?
    A: The logging module in Python provides a flexible framework for emitting log messages from Python programs. It allows you to control the log message format, destination, and logging levels.
  • Q86: How do you check the type of an object in Python?
    A: You can check the type of an object in Python using the type() function. It returns the type of the object as a class object.
  • Q87: What is the purpose of the __init__() method in Python classes?
    A: The __init__() method is a special method in Python classes that is called when an object is created from the class. It is used to initialize the object's attributes and perform any necessary setup.
  • Q88: How do you raise an exception in Python?
    A: You can raise an exception in Python using the raise statement. It allows you to generate and handle custom exceptions or propagate built-in exceptions.
  • Q89: What is the purpose of the staticmethod decorator in Python?
    A: The staticmethod decorator is used to define a static method in a class. A static method is a method that belongs to the class rather than an instance of the class, and it can be called without creating an object.
  • Q90: How do you convert a dictionary to a JSON string in Python?
    A: You can convert a dictionary to a JSON string in Python using the json module. The json.dumps() function converts a Python object (such as a dictionary) to a JSON string.
  • Q91: What is the purpose of the __doc__ attribute in Python?
    A: The __doc__ attribute is a special attribute in Python classes and functions that stores the documentation string (docstring) associated with the object. It can be accessed using the dot notation.
  • Q92: How do you find the current working directory in Python?
    A: You can find the current working directory in Python using the os module. The os.getcwd() function returns the current working directory as a string.
  • Q93: What is the purpose of the args and kwargs in Python function calls?
    A: args and kwargs are used in function calls to pass a variable number of arguments to a function. args is used to pass a variable number of non-keyword arguments, while kwargs is used to pass a variable number of keyword arguments.
  • Q94: How do you calculate the square root of a number in Python?
    A: You can calculate the square root of a number in Python using the math module. The math.sqrt() function returns the square root of a given number.
  • Q95: What is the purpose of the os module in Python?
    A: The os module in Python provides functions for interacting with the operating system. It allows you to perform operations like file and directory manipulation, process management, and environment variable access.
  • Q96: How do you handle exceptions in Python?
    A: You can handle exceptions in Python using the try and except statements. The try block is used to enclose the code that may raise an exception, and the except block is used to handle the exception and provide alternative code to execute.
  • Q97: What is the purpose of the finally block in exception handling?
    A: The finally block is used in exception handling to specify code that will be executed regardless of whether an exception is raised or not. It is typically used to clean up resources or perform necessary finalization steps.
  • Q98: How do you open and close a file in Python?
    A: You can open and close a file in Python using the open() function and the close() method of file objects, respectively. The open() function returns a file object that can be used to read from or write to the file, and the close() method is used to close the file after you're done with it.