Category: Python

  • modules and packages in Python?

    Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages –

    • Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.
    • Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.
    • Reusability: Functions defined in a module can be easily reused by other parts of the application.
    • Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.

    Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.

    Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.
    Creating a package is easy since it makes use of the system’s inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

  • use of self in Python?

    Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

  • Python Arrays and lists?

    • Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
    • Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.
    import array
    a = array.array('i', [1, 2, 3])
    for i in a:
    
    print(i, end=' ')    #OUTPUT: 1 2 3
    a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str) a = [1, 2, 'string'] for i in a: print(i, end=' ') #OUTPUT: 1 2 string
  • floor a number in Python?

    To floor a number in Python, you can use the math.floor() function, which returns the largest integer less than or equal to the given number.

    • floor()method in Python returns the floor of x i.e., the largest integer not greater than x. 
    • Also, The method ceil(x) in Pythonreturns a ceiling value of x i.e., the smallest integer greater than or equal to x.

    import math
    n = 3.7
    F_num = math.floor(n)
    print(F_num)

    Output

    3
  • for loop and while loop in Python?

    • For loopUsed when we know how many times to repeat, often with lists, tuples, sets, or dictionaries.
    • While loop: Used when we only have an end condition and don’t know exactly how many times it will repeat.

    for i in range(5):
        print(i)
    c = 0
    while c < 5:
        print(c)
        c += 1

    Output

    0
    1
    2
    3
    4
    0
    1
    2
    3
    4
    
  • concatenate two lists in Python?

    We can concatenate two lists in Python using the +operator or the extend() method.

    1. Using the + operator:

    This creates a new list by joining two lists together.

    a = [1, 2, 3]
    b = [4, 5, 6]
    res = a + b
    print(res)

    Output

    [1, 2, 3, 4, 5, 6]
    

    2. Using the extend() method:

    This adds all the elements of the second list to the first list in-place.

    a = [1, 2, 3]
    b = [4, 5, 6]
    a.extend(b)
    print(a)

    Output

    [1, 2, 3, 4, 5, 6]

  • What is init in Python?

    The __init__() method is known as a constructor in object-oriented programming (OOP) terminology. It is used to initialize an object’s state when it is created. This method is automatically called when a new instance of a class is instantiated.

    Purpose:

    • Assign values to object properties.
    • Perform any initialization operations.

    Example

    We have created a book_shop class and added the constructor and book() function. The constructor will store the book title name and the book() function will print the book name.

    To test our code we have initialized the b object with “Sandman” and executed the book() function. 

    class book_shop:

    # constructor
    def __init__(self, title):
    self.title = title

    # Sample method
    def book(self):
    print('The tile of the book is', self.title)


    b = book_shop('Sandman')
    b.book()
    # The tile of the book is Sandman
  • Python lists and tuples?

    Lists and tuples are fundamental Python data structures with distinct characteristics and use cases.

    List:

    • Mutable: Elements can be changed after creation.
    • Memory Usage: Consumes more memory.
    • Performance: Slower iteration compared to tuples but better for insertion and deletion operations.
    • Methods: Offers various built-in methods for manipulation.

    Example:

    a_list = ["Data", "Camp", "Tutorial"]
    a_list.append("Session")
    print(a_list)  # Output: ['Data', 'Camp', 'Tutorial', 'Session']Powered By 

    Tuple:

    • Immutable: Elements cannot be changed after creation.
    • Memory Usage: Consumes less memory.
    • Performance: Faster iteration compared to lists but lacks the flexibility of lists.
    • Methods: Limited built-in methods.

    Example:

    a_tuple = ("Data", "Camp", "Tutorial")
    print(a_tuple) # Output: ('Data', 'Camp', 'Tutorial')

  • list some of its key features?

    Python is a versatile, high-level programming language known for its easy-to-read syntax and broad applications. Here are some of Python’s key features:

    • Simple and Readable Syntax: Python’s syntax is clear and straightforward, making it accessible for beginners and efficient for experienced developers.
    • Interpreted Language: Python executes code line by line, which helps in debugging and testing.
    • Dynamic Typing: Python does not require explicit data type declarations, allowing more flexibility.
    • Extensive Libraries and Frameworks: Libraries like NumPy, Pandas, and Django expand Python’s functionality for specialized tasks in data science, web development, and more.
    • Cross-Platform Compatibility: Python can run on different operating systems, including Windows, macOS, and Linux.
  • global and local scope?

    • A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
    • A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.