https://www.rakeshmgs.in/search/label/Template
https://www.rakeshmgs.in
RakeshMgs

Most Important O Level Viva Questions Answer | Python Basic Interview Questions and answers

Updated:

    What are the Viva questions in Python? 

    Python Basic Interview Questions

     What is Python?

    Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modeling real-world problems and building applications to solve these problems.

    What are the benefits of using Python?

    Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse. Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.

    What are pickling and unpickling?

    The pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

    How Python is interpreted?

    Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

    What are the applications of Python?

    Python is used in various software domains some application areas are given below.

    • Web and Internet Development
    • Games
    • Scientific and computational applications
    • Language development
    • Image processing and graphic design applications
    • Enterprise and business applications development
    • Operating systems
    • GUI based desktop applications


    What are the advantages of Python?

    • Interpreted
    • Free and open source
    • Extensible
    • Object-oriented
    • Built-in data structure
    • Readability
    • High-Level Language
    • Cross-platform Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes instructions directly.
    • Free and open-source: It is an open-source project which is publicly available to reuse. It can be downloaded free of cost.
    • Portable: Python programs can run on cross platforms without affecting their performance.
    • Extensible: It is very flexible and extensible with any module.
    • Object-oriented: Python allows to implement the Object-Oriented concepts to build application solutions.
    • Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.

    Which data types are supported in Python?

    Python has five standard data types:

    • Numbers
    • Strings
    • Lists
    • Tuples
    • Dictionaries

    How memory is managed in Python?

    • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap and the interpreter takes care of this Python private heap.
    • The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.
    • Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory, and makes it available to the heap space.

    What is PEP 8 and why is it important?

    PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.

    What is namespace in Python?

    In Python, every name introduced has a place where it lives and can be hooked for. This is known as a namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.

    What is PYTHONPATH?

    It is an environment variable that is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

    What are local variables and global variables in Python?

    Global Variables:

    Variables declared outside a function or in a global space are called global variables. These variables can be accessed by any function in the program.

    Local Variables:

    Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

    Example
    1
    2
    3
    4
    5
    6
    a=2
    def add():
    b=3
    c=a+b
    print(c)
    add()
    
    Output:
    5
    

    When you try to access the local variable outside the function add(), it will throw an error.

    What is the purpose of the PYTHONSTARTUP environment variable?

    It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

    What is the purpose of the PYTHONCASEOK environment variable?

    It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

    What is the purpose of the PYTHONHOME environment variable?

    It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.


    What is the difference between lists and tuples?

    TuplesLists
    Tuples are similar to a list, but they are enclosed within parenthesis, unlike the list.The list is used to create a sequence.
    The element and size can be changed.The element and size cannot be changed.
    They cannot be updated.They can be updated.
    They act as read-only lists.They act as a changeable list.
    Tuples are surrounded by ( )Lists are surrounded by [ ]
    Example of Tuple Code is, tup = (1, "a", "string", 1+2)Example of Lists Code is, L = [1, "a" , "string" , 1+2]


    What is a string in Python?

    A string in Python is a sequence of alphanumeric characters. They are immutable objects. It means that they don’t allow modification once they get assigned a value. Python provides several methods, such as join(), replace(), or split() to alter strings. But none of these change the original object.

    What is the difference between .py and .pyc files?

    • .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after the compilation of the .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.
    • Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for the .py file. If found, compile it to a .pyc file and then the python virtual machine executes it.
    • Having a .pyc file saves you the compilation time.

    What is the difference between Python Arrays and lists?

    Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type element whereas lists can hold any data type elements.

    Example
    1
    2
    3
    4
    5
    import array as arr
    My_Array=arr.array('i',[1,2,3,4])
    My_list=[1,'abc',1.20]
    print(My_Array)
    print(My_list)
    
    Output:
    array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]



    What are functions in Python?

    A function is a block of code that is executed only when it is called. To define a Python function, the def keyword is used.

    Example
    1
    2
    3
    def Newfunc():
    print("Welcome")
    Newfunc(); #calling the function
    
    Output:
    Welcome


    What is self in Python?

    Self is an instance of an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.

    The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

    What is a function call or a callable object in Python?

    A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fit in the same category.

    What is “Call by Value” in Python?

    In call-by-value, the argument is whether an expression or a value gets bound to the respective variable in the function.

    Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.

    What is “Call by Reference” in Python?

    We use both “call-by-reference” and “pass-by-reference” interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.

    This scheme also has the advantage of bringing more time and space efficiency because it leaves the need for creating local copies.

    On the contrary, the disadvantage could be that a variable can get changed accidentally during a function call. Hence, the programmers need to handle the code to avoid such uncertainty.

    What is Python?

    An index is an integer data type that denotes a position within an ordered list or a string. In Python, strings are also lists of characters. We can access them using the index which begins from zero and goes to the length minus one.

    For example, in the string “Program,” the indexing happens like this:

    Program 0 1 2 3 4 5


    What does the *args do in Python?

    We use *args as a parameter in the function header. It gives us the ability to pass the N (variable) number of arguments.

    Please note that this type of argument syntax doesn’t allow passing a named argument to the function.

    Example
    1
    2
    3
    4
    5
    6
    7
    # Python code to demonstrate 
    # *args for dynamic arguments 
    def fn(*argList):  
        for argx in argList:  
            print (argx) 
        
    fn('I', 'am', 'Learning', 'Python')
    
    Output:
    I
    am
    Learning
    Python


    What does the continue do in Python?

    The continue is a jump statement in Python which moves the control to execute the next iteration in a loop leaving all the remaining instructions in the block unexecuted. The continue statement is applicable for both the “while” and “for” loops.


    When should you use the “break” in Python?

    Python provides a break statement to exit from a loop. Whenever the break hits in the code, the control of the program immediately exits from the body of the loop. The break statement in a nested loop causes the control to exit from the inner iterative block.


    What does the **kwargs do in Python?

    We can also use the **kwargs syntax in a Python function declaration. It let us pass N (variable) number of arguments that can be named or keyworded.

    Example
    1
    2
    3
    4
    5
    6
    7
    # Python code to demonstrate 
    # **kwargs for dynamic + named arguments 
    def fn(**kwargs):  
        for emp, age in kwargs.items(): 
            print ("%s's age is %s." %(emp, age)) 
        
    fn(John=25, Jinu=22, Tom=32)
    
    Output:
    John's age is 25.
    Jinu's age is 22.
    Tom's age is 32.


    What are unit tests in Python?

    • unit test is a unit testing framework of Python.
    • Unit testing means testing different components of software separately. Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations.
    • This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

    What are iterators in Python?

    In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items, and they can be a list, tuple, or dictionary. Python iterator implements __itr__ and next() method to iterate the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple).

    What is a generator in Python?

    In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement __itr__ and next() method and reduce other overheads as well.

    If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required.

    What is a negative index in Python?

    Python sequences are accessible using an index in positive and negative numbers. For example, 0 is the first positive index, 1 is the second positive index, and so on. For negative indexes, -1 is the last negative index, -2 is the second last negative index, and so on.

    Index traverses from left to right and increases by one until the end of the list.

    Negative index traverses from right to left and iterates one by one till the start of the list. A negative index is used to traverse the elements into reverse order.


    Differentiate between SciPy and NumPy?

    NumPySciPy
    Numerical Python is called NumPyScientific Python is called SciPy
    It is used for performing general and efficient computations on numerical data which is saved in arrays. For example, indexing, reshaping, sorting, and so onThis is an entire collection of tools in Python mainly used to perform operations like differentiation, integration, and many more.
    There are some of the linear algebraic functions present in this module but they are not fully-fledged.For performing algebraic computations this module contains some of the fully-fledged operations


    Can we make multi-line comments in Python?

    In python, there is no specific syntax to display multi-line comments like other languages. To display multi-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not used as the first statement in the present method, it will not be considered by the Python parser.

    What is the difference between pass and continue in Python?

    The continued statement makes the loop resume from the next iteration.

    On the contrary, the pass statement instructs to do nothing, and the remainder of the code executes as usual.

    What is the return value of the trunk() function?

    The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.

    What are the OOPS concepts available in Python?

    Python is also an object-oriented programming language like other programming languages. It also contains different OOPS concepts, and they are

    • Object
    • Class
    • Method
    • Encapsulation
    • Abstraction
    • Inheritance
    • Polymorphism


    What is the usage of the help() and dir() function in Python?

    Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.

    • Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
    • Dir() function: The dir() function is used to display the defined symbols.


    What makes Python object-oriented?

    Python is object-oriented because it follows the Object-Oriented programming paradigm. This is a paradigm that revolves around classes and their instances (objects). With this kind of programming, we have the following features:

    • Encapsulation
    • Abstraction
    • Inheritance
    • Polymorphism
    • Data hiding


    Explain Inheritance in Python with an example.

    Inheritance allows one class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

    They are different types of inheritance supported by Python:

    • Single Inheritance: where a derived class acquires the members of a single superclass.
    • Multi-level inheritance: a derived class d1 is inherited from base class base1, and d2 is inherited from base2.
    • Hierarchical inheritance: from one base class you can inherit any number of child classes
    • Multiple inheritances: a derived class is inherited from more than one base class.

    What is data abstraction in Python?

    In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal processes and showing only the functionality. In Python abstraction can be achieved using encapsulation.

    Define encapsulation in Python?

    Encapsulation is one of the most important aspects of object-oriented programming. The binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.


    What is polymorphism in Python?

    By using polymorphism in Python we will understand how to perform a single task in different ways. For example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle, and so on.

    Does Python make use of access specifiers?

    Python does not make use of access specifiers and also it does not provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behavior of private and protected access specifiers

    Define Constructor in Python?

    Constructor is a special type of method with a block of code to initialize the state of instance members of the class. A constructor is called only when the instance of the object is created. It is also used to verify that they are sufficient resources for objects to perform a specific task.

    There are two types of constructors in Python, and they are:

    • Parameterized constructor
    • Non-parameterized constructor

    How to remove values to a python array?

    Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.

    Example
    1
    2
    3
    4
    5
    a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
    print(a.pop())
    print(a.pop(3))
    a.remove(1.1)
    print(a)
    
    Output:
    4.6
    3.1
    array(d, [2.2, 3.8, 3.7, 1.2])


    How to add values to a python array?

    Elements can be added to an array using the append(), extend() and the insert (i,x) functions.

    Example
    1
    2
    3
    4
    5
    6
    7
    a=arr.array('d', [1.1 , 2.1 ,3.1] )
    a.append(3.4)
    print(a)
    a.extend([4.5,6.3,6.8])
    print(a)
    a.insert(2,3.8)
    print(a)
    
    Output:
    array(d, [1.1, 2.1, 3.1, 3.4])
    array(d, [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])
    array(d, [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])


    What are Errors and Exceptions in Python?

    Errors are coding issues in a program that may cause it to exit abnormally. On the contrary, exceptions happen due to the occurrence of an external event that interrupts the normal flow of the program.

    What are docstrings in Python?

    Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.

    Example
    1
    2
    3
    4
    5
    6
    7
    8
    ""
    Using docstring as a comment.
    This code divides 2 numbers
    ""
    x=8
    y=4
    z=x/y
    print(z)
    
    Output:
    2.0

    What is NumPy and how is it better than a list in Python?

    NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.

    Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.

    • NumPy arrays are more compact than lists.
    • Reading and writing items is faster with NumPy.
    • Using NumPy is more convenient than the standard list.
    • NumPy arrays are more efficient as they augment the functionality of lists in Python.

    What does the yield keyword do in Python?

    The yield keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a method can have multiple calls to the yield keyword.

    Example
    1
    2
    3
    4
    5
    6
    def testgen(index):
      weekdays = ['sun','mon','tue','wed','thu','fri','sat']
      yield weekdays[index]
      yield weekdays[index+1]
    day = testgen(0)
    print next(day), next(day)
    
    Output:
    sun mon


    What are the different methods to copy an object in Python?

    There are two ways to copy objects in Python.

    • copy.copy() function
      • It makes a copy of the file from source to destination.
      • It’ll return a shallow copy of the parameter.
    • copy.deep copy() function
      • It also produces a copy of an object from the source to the destination.
      • It’ll return a deep copy of the parameter that you can pass to the function.


    What is the difference between deep and shallow copy?

    Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

    Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

    How is Multithreading achieved in Python?

    • Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
    • Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
    • This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
    • All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.


    Mention is the difference between Django, Pyramid, and Flask?

    Flask is a "microframework" primarily built for a small application with simpler requirements. In a flask, you don't have to use external libraries. Flask is ready to use.

    Pyramids are built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style, and more. The pyramid is heavily configurable.

    Like Pyramid, Django can also be used for larger applications. It includes an ORM.

    How are range and xrange different from one another?

    The range() MethodThe xrange() Method
    In Python 3, xrange() is not supported; instead, the range() function is used to iterate in for loops.The xrange() function is used in Python 2 to iterate in for loops.
    It returns a list.It returns a generator object as it doesn’t really generate a static list at the run time.
    It takes more memory as it keeps the entire list of iterating numbers in memory.It takes less memory as it keeps only one number at a time in memory.


    What is the difference between append() and extend() methods?

    Both append() and extend() methods are methods used to add elements at the end of a list.

    • append(element): Adds the given element at the end of the list that called this append() method
    • extend(another-list): Adds the elements of another list at the end of the list that called this extend() method

    Are multiple inheritances supported in Python?

    Yes, unlike Java, Python provides users with a wide range of support in terms of inheritance and its usage. Multiple inheritances refer to a scenario where a class is instantiated from more than one individual parent class. This provides a lot of functionality and advantages to users.

    What are python modules?

    Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code. Some of the commonly used built-in modules are:

    • os
    • sys
    • math
    • random
    • data time
    • JSON

    When would you use triple quotes as a delimiter?

    Triple quotes ‘’”” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.

    What is _init_?

    The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a new object. The main role of _init_ is to initialize the values of instance members for objects.

    Example
    1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    class  Student:
    def _init_ (self, name, age, marks):
    self.name = name
    self.age = age
    self.marks = 950
    S1 = Student("ABC", 22, 950)
    # S1 is the instance of class Student.
    # _init allocates memory for S1.
    print(S1.name)
    print(S1.age)
    print(S1.marks)
    
    Output:
    ABC
    22
    950


    What is the difference between the lambda and def?

    • Def can hold multiple expressions while lambda is a uni-expression function.
    • Def generates a function and designates a name to call it later. Lambda forms a function object and returns it.
    • Def can have a return statement. Lambda can’t have return statements.
    • Lambda supports to get used inside a list and dictionary.

    What are the optional statements possible inside a try-except block in Python?

    There are two optional clauses you can use in the try-except block.

    • The “else” clause: It is useful if you want to run a piece of code when the try block doesn’t create an exception.
    • The “finally” clause: It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.

    What is slicing in Python?

    Slicing is a string operation for extracting a part of the string, or some part of a list. In Python, a string (say text) begins at index 0, and the nth character is stored at position text[n-1]. Python can also perform reverse indexing, i.e., in the backward direction, with the help of negative numbers.

    In Python, the slice() is also a constructor function that generates a slice object. The result is a set of indices mentioned by range(start, stop, step). The slice() method allows three parameters. 1. start – starting number for the slicing to begin. 2. stop – the number which indicates the end of slicing. 3. step – the value to increment after each index (default = 1).

    What is %s in Python?

    Python has support for formatting any value into a string. It may contain quite complex expressions. One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.

    Does Python have a Main() method?

    The main() is the entry point function which happens to be called first in most programming languages. Since Python is interpreter-based, so it sequentially executes the lines of the code one by one.

    Python also does have a Main() method. But it gets executed whenever we run our Python script either by directly clicking it or starting it from the command line. We can also override the Python default main() function using the Python if statement.

    Example
    1
    2
    3
    4
    5
    6
    print("Welcome")
    print("__name__ contains: ", __name__)
    def main():
        print("Testing the main function")
    if __name__ == '__main__':
        main()
    
    Output:
    Welcome
    __name__ contains:  __main__
    Testing the main function

    What does the __ Name __ do in Python?

    The __name__ is a unique variable. Since Python doesn’t expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level 0 indentation. To see whether the main() gets called, we can use the __name__ variable in an if clause compared with the value “__main__.”

    Explain split() and join() functions in Python?

    You can use the split() function to split a string based on a delimiter to a list of strings.

    You can use the join() function to join a list of strings based on a delimiter to give a single string.

    Example
    1
    2
    3
    4
    string = "This is a string."
    string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
    print(string_list)
    print(' '.join(string_list))
    
    Output:
    ['This', 'is', 'a', 'string.']
    This is a string.


    What does the Title() method do in Python?

    Python provides the title() method to convert the first letter in each word to capital format while the rest turns to Lowercase.

    Example
    1
    2
    str = 'lEaRn pYtHoN'
    print(str.title())
    
    Output:
    Learn Python

    How to create an empty class in Python?

    An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects for this class outside the class itself. IN PYTHON THE PASS command does nothing when it's executed. it’s a null statement.

    Example
    1
    2
    3
    4
    5
    class a:
        pass
    obj=a()
    obj.name="xyz"
    print("Name = ",obj.name)
    
    Output:
    Name =  xyz

    What is Class in Python?

    Python supports object-oriented programming and provides almost all OOP features to use in programs. A Python class is a blueprint for creating objects. It defines member variables and gets their behavior associated with them.

    We can make it by using the keyword “class.” An object gets created from the constructor. This object represents the instance of the class.

    How will you capitalize the first letter of string?

    In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.

    How will you convert a string to all lowercase?

    To convert a string to lowercase, the lower() function can be used.

    Example
    1
    2
    stg='WELCOME'
    print(stg.lower())
    
    Output:
    welcome

    Explain what Flask is and its benefits?

    Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of their dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.

    A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key.

    Is Django better than Flask?

    Django and Flask map the URLs or addresses typed in the web browsers to functions in Python.

    Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work. Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons.

    What is a map function in Python?

    map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 argument, then many iterables are given. #Follow the link to know more similar functions.

    Is python statically typed or dynamically typed?

    In a statically typed language, the type of variables must be known (and usually declared) at the point at which it is used. Attempting to use it will be an error. In a dynamically typed language, objects still have a type, but it is determined at runtime. You are free to bind names (variables) to different objects with different types. So long as you only perform operations valid for the type the interpreter doesn’t care what type they actually are.

    What is zip function?

    Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator, and aggregates the elements based on iterables passed. It returns an iterator of tuples.

    What is the swap case function in Python?

    It is a string’s function that converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case.

    Example
    1
    2
    string = "How Are You"
    string.swapcase()
    
    Output:
    hOW aRE yOU

    Which databases are supported by Python?

    MySQL (Structured) and MongoDB (Unstructured) are the prominent databases that are supported natively in Python. Import the module and start using the functions to interact with the database.

    How is Exceptional handling done in Python?

    There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions and handle the recovering mechanism accordingly. Try is the block of a code that is monitored for errors. Except block gets executed when an error occurs.

    The beauty of the final block is to execute the code after trying for error. This block gets executed irrespective of whether an error occurred or not. Finally block is used to do the required cleanup activities of objects/variables.

    Name mutable and immutable objects

    Immutable means the state cannot be modified after creation. Examples are int, float, bool, string, and tuple.

    Mutable means the state can be modified after creation. Examples are list, dict, and set.

    Do you know about a dictionary in Python?

    Dictionary means built-in data types available in Python. It also specifies one relationship between values and keys. Moreover, it comprises a pair of keys and even their corresponding values.

    What is a classifier?

    A classifier is used to predict the class of any data point. Classifiers are special hypotheses that are used to assign class labels to any particular data point. A classifier often uses training data to understand the relation between input variables and the class. Classification is a method used in supervised learning in Machine Learning.

    What is recursion?

    Recursion is a function calling itself one or more times in its body. One very important condition a recursive function should have to be used in a program is, it should terminate, else there would be a problem of an infinite loop.

    What is the ‘with the statement’?

    “with” statement in python is used in exception handling. A file can be opened and closed while executing a block of code, containing the “with” statement., without using the close() function. It essentially makes the code much easier to read.

    Is Python case-sensitive?

    Yes. Like most of the widely used programming languages like Java, C, C++, etc, Python is also a case-sensitive language. This means, "Hello" and "hello" are not the same. In other words, it cares about the case- lowercase or uppercase.

    What are the different types of operators in Python?

    Operators are used to performing operations on one or more operands. An operand is a variable or a value on which we perform the operation. Python supports the following types of operators.

    • Arithmetic Operators
    • Comparison (Relational) Operators
    • Assignment Operators
    • Logical Operators
    • Bitwise Operators
    • Membership Operators
    • Identity Operator

    What is the purpose of the ** operator?

    Python ** operator does exponentiation. x ** y is x raised to the y power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).

    What are membership operators?

    There are two membership operators in Python: in operator and not in operator

    • in operator - Evaluates to true if it finds a variable in the specified sequence and false otherwise.
    • not in operator- Evaluates to true if it does not find a variable in the specified sequence and false otherwise.

    What is Monkey Patching? How can you do it in Python?

    Monkey Patching is the process of making changes to a module or class while the program is running. A Monkey Patch in Python is a piece of code that extends or modifies other code at runtime (typically at startup).

    What is meant by mutex in Python?

    In Python programming, a mutex (mutual exclusion object) is a program object that is created so that multiple program threads can take turns sharing the same resource, such as access to a file.

    Explain the use of the Ternary operator in Python?

    It is used as a conditional statement, it consists of true or false values. The ternary operator evaluates the statement and stores true or false values.

    What is the input function in Python?

    Input can come in various ways, for example from a database, another computer, mouse clicks, and movements, or from the internet. Yet, in most cases, the input stems from the keyboard. For this purpose, Python provides the function input(). input has an optional parameter, which is the prompt string.

    Mention the use of the // operator in Python?

    It is a Floor Divisionoperator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

    Is indentation important in python?

    Indentation is important in Python. It indicates a block of code. Anything within loops, functions or classes, etc. is specified within an indented block. Indentation is generally done using four space characters, if the code is not properly indented, the execution will not be accurate and will also show errors.

    What does the len() function work in Python?

    In Python, the len() function is used to determine the length of an input string. It is a primary string function that can be used to calculate the number of characters present in a string.

    Example
    1
    2
    str_name = 'learning'
    len(str_name)
    
    Output:
    8

    How will you reverse a list?

    To reverse a list, use the list.reverse() − it reverses objects of the list in place. The reverse() function doesn't return any value. The elements are reversed and the lists are updated.

    Example
    1
    2
    3
    4
    5
    6
    7
    # Operating System List
    os = ['Windows', 'macOS', 'Linux']
    print('Original List:', os)
    # List Reverse
    os.reverse()
    # updated list
    print('Updated List:', os)
    
    Output:
    Original List: ['Windows', 'macOS', 'Linux']
    Updated List: ['Linux', 'macOS', 'Windows']

    How to merge one dictionary with the other?

    In python, we have a method called update() which can be used to merge one dictionary on another.

    Example
    1
    2
    3
    4
    a = {'a':3}
    b = {'b':2}
    a.update(b)
    a
    
    Output:
    {'a': 3, 'b': 2} 

    Name some standard errors that occur in Python

    • TypeError: It occurs when the expected type does not match with the given type of a variable.
    • ValueError: It occurs when an expected value is not given, suppose you are expecting 6 elements in a list and you gave 2.
    • NameError: It occurs when you are trying to access an undefined variable or a function.
    • IOError: It occurs when you are trying to access a file that does not exist.
    • IndexError: It occurs when you are trying to access an invalid index of a sequence.
    • KeyError: It occurs when you use an invalid key to access a value in the dictionary.

    Why do we need operator overloading?

    We need Python Operator Overloading to compare between two objects. For example, all kind of objects does not have a specific operation that should be done if the plus(+) operator is used in between two objects. This problem can be resolved by Python Operator Overloading. We can overload compare operator to compare between two objects of the same class using python operator overloading.


    आपको आर्टिकल कैसा लगा? अपनी राय अवश्य दें
    Please don't Add spam links,
    if you want backlinks from my blog contact me on rakeshmgs.in@gmail.com