Python Reference

Links : Learn     Interview Questions     IDE
            

Python Interview Questions - Page 3

< Previous Page              Next Page >
Question: What is the difference between '__str__()' and '__repr__()' methods in Python?
Answer: The '__str__()' method is called when the 'str()' function is used or when an object is printed using 'print()'. It should return a human-readable string representation of the object.

The '__repr__()' method is called when the 'repr()' function is used or when an object is evaluated in the interpreter. It should return an unambiguous string representation of the object that can be used to recreate the object.

Question: What is the '*args' and '**kwargs' syntax in Python function definitions?
Answer: The *args is used to pass a variable number of positional arguments to a function. Inside the function, args will be a tuple containing all the positional arguments.
The **kwargs is used to pass a variable number of keyword arguments to a function. Inside the function, kwargs will be a dictionary containing all the keyword arguments.

Question: How do you sort a list in Python?
Answer: You can sort a list in Python using the sorted() function or by calling the sort() method on the list object. For example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
my_list.sort()  # Sorts the list in place

Question: What is the purpose of the '__doc__' attribute in Python?
Answer: The '__doc__' attribute is a special attribute in Python that holds the docstring (documentation string) of a module, class, function, or method.
It can be accessed using the dot notation (object.__doc__) or the help() function.

Question: How do you check if a key exists in a dictionary in Python?
Answer: You can check if a key exists in a dictionary using the 'in' operator or the get() method. For example:
my_dict = {'a': 1, 'b': 2}
if 'a' in my_dict:
    print('Key "a" exists')

Question: What is the purpose of the '__name__' variable in Python?
Answer: The '__name__' variable is a special variable in Python that holds the name of the current module. When a Python script is run directly, '__name__' is set to '__main__'.

It can be used to distinguish between code that should be executed when the script is run directly versus when it is imported as a module.

< Previous Page Next Page >