Interview-Questions-Img

Python Programming - Interview Question

Interview Questions

Python is a high-level interpreted and object-oriented programming language. Because it is a general-purpose language, it can be used to create practically any application form with the right tools/libraries. 

Programmers with skills in Python programming can use it to develop websites and software and apply it for data analysis and modern technologies like machine learning and data science. 

Objects, modules, threads, exception handling, and automatic memory management are all characteristics of Python that help with real-world modeling problems and developing programs to address them.

Following are the primary advantages of Python programming language:

  • It is a multi-purpose programming language with an easy-to-understand syntax that stresses readability and lowers program maintenance costs. Furthermore, the language is scriptable, open-source, and supports third-party packages, promoting modularity and code reuse.

  • Rapid Application Development and deployment have attracted a big developer community due to its high-level data structures, as well as its dynamic type and binding.

We should learn about typing before we can understand a dynamically typed language. Typing in programming languages refers to type-checking.

Because these languages do not provide "type-coercion," "1" + 2 will produce a type error in a strongly-typed language such as Python (implicit data type conversion). A weakly-typed language, such as Javascript, will, on the other hand, return "12."

There are two steps to type-checking:

  • Data Types are checked before execution in the static model.

  • Data Types are examined while the program is running.

Python is an interpreted programming language that executes each command line by line, and type-checking happens in real-time. Python is, therefore, a Dynamically Typed Language.

In an Interpreted language, sentences are executed line by line. Python, Javascript, R, PHP, and Ruby are examples of interpreted languages. An interpreted language program runs directly from the source code without a compilation step.

PEP stands for Python Enhancement Proposal. A PEP is a Python community design document that provides information or describes a new feature for Python or its processes. 

PEP 8 is very significant because it outlines the Python code style rules. Contributing to the Python open-source community necessitates strict adherence to these style guidelines.

The Python Lists and Tuples are sequence data types that can store a collection of objects. In addition, both sequences can store objects with different data types. 

Tuples are represented by parentheses ('ansh', 5, 0.97), while lists are represented by square brackets ['sara', 6, 0.19].

But what exactly is the distinction between the two? The main difference is that lists are mutable, whereas tuples are immutable objects.

Python can be used to write scripts, but it is primarily used as a general-purpose programming language.

Python Enhancement Proposal is the acronym for PEP. It's a set of guidelines for making Python code as readable as possible.

The source code for Python is kept in.py files. Python files' bytecode is kept in .pyc files, which are formed when code from another source is imported. By converting source .py files to .pyc files, the interpreter saves time.

  • Built-in namespaces contain all of Python's built-in things and are accessible whenever Python is running.

  • Namespaces for all objects created at the main program level are called global namespaces.

  • These namespaces belong to the higher function.

  • Local namespaces are found at the local or inner function level.

Decorators in Python are used to add design patterns to functions without changing their structure. 

Decorators are typically defined before the process they are enhancing. To use a decorator, we must first define its function. The function to which it is applied is then written, with the decorator function placed directly. We use the @ symbol before the decorator for this.

Python's built-in data types include the following:

  • Numbers: Integers, floating-point-point numbers, and complex numbers are all examples of numbers. e.g. 1, 7.9,3+4i

  • List: A list is a grouping of items in a document-specific order. A list's elements could be of different data types. For example, Eg. [5,' market,' 2.4]

  • Tuple: A tuple is an ordered group of elements. Tuples, unlike lists, are immutable, meaning they cannot be changed. E.g. (3,' tool',1)

  • String: A collection of characters is called a string. Single or double quotes are used to declare them. E.g., "Sana," "She's going to the market," and so on.

  • Set: A set is a collection of unrelated items not in any particular order. E.g. {7,6,8}

  • Dictionary: A dictionary is a collection of important words and value pairs in which each value can be accessed using its key. The order of the items is irrelevant. 1: 'apple', 2: 'mango', etc.

  • Boolean: True and False are the two possible boolean values.

In Python, keywords are reserved words with special meanings.

 

They're commonly used to specify the type of variables. Variable and function names cannot contain keywords. Python has the following 33 keywords:

 

  • And

  • Or

  • Not

  • If

  • Elif

  • Else

  • For

  • While

  • Break

  •  As

  • Def

  • Lambda

  • Pass

  • Return

  • True

  • False

  • Try

  • With

  • Assert

  • Class

  • Continue

  • Del

  • Except

  • Finally

  • From

  • Global

  • Import

  • In

  • Is

  • None

  • Nonlocal

  • Raise

  • Yield

In Python, there are five different types of literal:

String literals

String literals are created by assigning text to a variable enclosed in single or double quotes. Assign the triple-quotes-enclosed multiline text to create multiline literals. 

For example:

name= “Tanya”

Character Literals

It formed by enclosing a single character in double quotations. E.g., a='t' 

Numeric literals 

These are numbers that can be integers, floating-point values, or complex numbers. For example, a=50. 

Boolean literals

These can have two values: True or False.

Literal Collections are divided into four categories:

a) List collections-Eg. a=[1,2,3,’Amit’]

b) Tuple literals- Eg. a=(5,6,7,8)

c) Dictionary literals- Eg. dict={1:' apple', 2:' mango, 3:' banana"}

d) Set literals- Eg. {"Tanya", "Rohit", "Mohan"}

Special literals

 

Python has a single particular literal, None, used to return a null variable.

The following are the new features in Python 3.9.0.0:

  • The new Dictionary features Update(|=) and Merge(|)

Prefixes and suffixes can be removed using New String Methods.

Generics in Standard Collections with Type Hinting

 

  • Instead of LL1, a new parser based on PEG is used.

  • zoneinfo and graphlib are two new modules

  • Improved Modules such as ast, asyncio, and others

  • Improvements include enhanced assignment syntax, signal handling, and Python built-ins.

  • Deprecated parser and symbol modules, and deprecated functions are examples of deprecated functions and commands

  • Erroneous methods, functions, and so on are removed

Yes. Python is a case-sensitive programming language.

It is an environment variable used for adding additional directories. When you import a module, it sets an environment variable. First, it is checked when a module is imported to see if it is present in multiple directories. Then, it is used by the interpreter to determine which module to load.

Global Variables:

These variables are declared outside of a function or in a global space. Any role in the program can access these variables.

Local Variables:

A local variable is any variable that is declared within a function.

This variable only exists in local space, not globally.

Example:

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.

Type conversion is the process of changing one data type into another.

  • int () is a function that converts any data type to an integer.

  • float() is a function that converts any data type to a float type.

  • ord() — this function converts characters to integers.

  • hex() is a function that converts integers to hexadecimal.

  • oct() transforms an integer into an octal value.

  • tuple() – To convert to a tuple, use this function.

  • set() – After converting to set, this function returns the type.

  • list() – Any data type can be converted to a list using the list() function.

  • dict() — This function creates a dictionary from a tuple of order (key, value).

  • str() – Converts an integer to a string.

Follow the instructions below to install Python on Windows:

  • Install Python by going to https://www.python.org/downloads/.

  • Install it on your computer after that. Using the command prompt, look for the directory where PYTHON is installed on your PC: cmd Python.

  • Create a new variable called PYTHON_NAME in advanced system settings and paste the copied path into it.

  • Locate the path variable, select its value, and press the 'edit' button.

Python requires indentation. It represents a coding block.

It contains all the code for loops, classes, functions, etc. Four space characters are typically utilized. If your code is not indented, it will not run correctly and throw problems.

In Python, arrays and lists both store data in the same way. On the other hand, arrays can only have a single data type element, whereas lists can contain any data type element.

A Python function is a code that only runs when called. To define a Python function, use the def keyword. 

Example:

def Newfunc():

print("Hi, Welcome to Tutorials Freak")

Newfunc(); #calling the function

Output: Hi, Welcome to Tutorials Freak

In Python, __init__ is a function or constructor. When a new class object/instance is generated, this function is automatically called to allocate memory. The __init__ method is available in all categories.

An example of how to use it:

class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)

Output:

XYZ

23

20000

An anonymous function is a lambda function. This function can accept as many parameters as it wants, but only one statement.

Example:

a = lambda x,y : x+y

print(a(5, 6))

Output: 11

The self is an instance or object of a class. The first parameter in Python is explicitly included. In Java, however, it is not required. It is easier to distinguish between a class's methods and attributes with local variables.

The self variable in the init procedure refers to the newly created object, while the thing whose method was called in other ways.

  • Python Break 

The loop is terminated when a condition is met, and control is transferred to the following statement.

  • Python Continue

When a defined condition is met, control is returned to the beginning of the loop, allowing some sections of the loop to be bypassed.

  • Python Pass

 

Use this when you need a piece of code syntactically but don't want to execute it. This is a null operation in essence. When this is run, nothing happens.

Iterators are objects that can be traversed and iterated through.

The Random module is a standard module used to generate random integers. The methodology is as follows:

  1. import random

  2. random.random

The random.random() method returns a floating-point value between 0 and 1. The function generates random float numbers. The methods used with the random class are the bound methods of the concealed instances.

Random instances can demonstrate a multi-threading program that creates several instances of individual threads. 

The following random generators are also used in this:

  • randrange(a, b): In rectangle chooses an integer and provides the range [a, b]. It returns the elements by randomly selecting them from the supplied range. A range object is not created.

  • uniform(a, b): It selects a floating-point number that falls inside the range [a,b]. The floating-point number is returned by It.

  • normal variate(mean, sdev): The normal distribution is represented by normal variate(mean, sdev), where mu denotes the mean and sdev denotes the standard deviation

The Random class is used to generate several independent random number generators.

Xrange and range are nearly identical. They both allow you to generate a list of integers to use wherever you wish.

The only distinction between range() and xrange() is that range() returns a Python list object whereas xrange() delivers an xrange object.

This means that, unlike range, xrange does not construct a static list at runtime. Instead, it uses yielding to generate the values as needed. This technique is employed with generators, a sort of object.

Generators are functions that return an iterable list of things.

In Python, comments begin with a # character. Alternatively, docstrings are sometimes used for commenting (strings enclosed within triple quotes).

Example:

<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_end"></span>

<pre><span>#Comments in Python start like this

print("Comments in Python start with a #")

Output: 

 

Comments in Python start with a #

The Pickle module turns any Python object to a string representation, dumping it into a file using the dump method.

The technique of recovering original Python objects from a stored text representation is known as unpickling.

Python's capitalize() function capitalizes the first letter in a string. If the string already starts with a capital letter, it returns the original content.

Example:

stg=’python interview questions'

print(stg.capitalize())

Output: 

Python Interview Questions

Multi-line comments span many lines. Therefore, a # must precede all lines that will comment. You can also annotate multiple lines with a convenient shortcut.

Just Hold the ctrl key and left-click in every area where you want a # character to appear, then write a # once. This will insert a comment into every line where your cursor resides.

Docstrings are documentation strings, not comments. Three quote marks surround these docstrings. Because they are not assigned to any variable, they can also be used as comments.

Example:

"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)

Output: 

2.0

Operators are distinct functions. They process one or more input values and produce a result.

  • is: returns true when both operands are true (Example: "a" is 'a')

  • not: returns the boolean value's opposite.

  • in: determines whether an element is present in a sequence.

The Python interpreter has two tasks to inspect a consolidated dump of built-in functions: help() and dir().

The help() function displays the documentation text and, among other things, displays support for modules, keywords, and attributes. 

The dir() method is used to display the symbols that have been declared.

Some Python modules, when Python exits,mainly circular references to other objects or objects from global namespaces, are not necessarily de-allocated or deleted.

  • It is impossible to de-allocate the memory that the C library has reserved.

  • Python's efficient cleanup mechanism would attempt to de-allocate/destroy all other objects on exit.

The dictionary data type is a built-in data type in Python. It creates a one-to-one relationship between keys and values. Dictionaries store dictionary keys and values in pairs. Dictionaries are indexed using keys.

Consider the following scenario:

Some keys are included in the example below. Country, Capital, and PM. India, Delhi, and Modi are the values that correspond to them.

dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

print dict[Country]

Output: India

print dict[Capital]

Output: Delhi

print dict[PM]

Output: Modi

Conditional statements are displayed using the ternary operator. This is made up of true or false values and a statement that must be evaluated.

Syntax:

The Ternary operator will be given as:

[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

The expression gets evaluated like if x<y else y; in this case, if x<y is true, then the value is returned as big=x, and if it is incorrect, then big=y will be sent as a result.

How many arguments a function will receive, or when we want to give a stored list or tuple of ideas to a position, we use *args. 

**kwargs can use to pass the values of a dictionary as keyword arguments when we don't know how many keyword arguments will be given to a function. 

You could use *bob and **billy instead of args and kwargs, but that would be unwise.

The "re" module in Python has three ways of changing strings. They are:

  • split() divides a string into a list using a regex pattern.

  • sub()  finds all substrings that match the regex pattern and replaces them with a new string.

  • subn() is similar to sub() in that it returns a new string and the number of replacements.

len() in Python means - To figure out how long a string, a list, or an array is.

Example:

stg='ABCD'

len(stg)

Output:

4

In Python, sequences are indexed and can contain both positive and negative numbers. Positive numbers are indexed with the first index being '0,' the second index being '1,' and so on.

A negative number's index starts with '-1,' the last index in the sequence, and finishes with '-2,' the penultimate index,' with the series continuing as a positive number.

The negative index removes any new-line spaces from the string, allowing S[:-1] to be accepted as the final character.

Python packages are namespaces that contain several modules.

You must import the OS Module in Python to delete a file. Following that, you must use the os.remove() function.

Example:

import os

 

os.remove("xyz.txt")

Python has the following built-in types:

  • Integers

  • Floating-point

  • Complex numbers

  • Strings

  • Boolean

  • Built-in functions

  • Python lists are excellent general-purpose containers. They provide (relatively) fast insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to generate and manage.

  • They have some limitations: "vectorized" operations like elementwise addition and multiplication are not supported. Because they can contain objects of different types, Python must store type information for each element and run type dispatching code when operating on it.

  • NumPy is not just more efficient, but it is also easier to use. You receive a number of vector and matrix operations for free, which might save you time by avoiding unnecessary effort. They are also implemented effectively.

  • NumPy comes with many features, and NumPy arrays are faster, including FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, and more.

To add elements to an array, use the append(), extend(), and insert (i,x) operations.

Example:

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])

The pop() or remove() methods can remove array elements. One of these functions returns the removed value, while the other does not.

Example:

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])

Yes. Python is an object-oriented programming language. By creating an object model, any program can be solved in Python. On the other hand, Python can be used as both a procedural and structural language.

A shallow copy is used to maintain the values replicated in the previous instance when a new instance type is generated. Reference pointers are copied via shallow copy. We can copy in the same way as values are copied. 

These are references to the original objects, and any changes made to any class member will impact the original copy. Shallow copy allows for faster program execution and is dependent on the size of the data being used.

Deep copy is a method of archiving previously duplicated data. During the deep copy, the reference pointers to the objects are not transferred. Instead, it creates a reference to an object and stores the new thing pointed to by another entity. 

These changes made to the original copy will not affect any subsequent copies that use the object. Deep copy slows down program execution by creating multiple copies of each thing that is called.

  • Although Python provides a multithreading module, it is usually not a good idea to utilize it if you want to speed up your code via multithreading.

  • A Python construct is the Global Interpreter Lock (GIL). Only one of your 'threads' can run at a time because of the GIL. The GIL is obtained by a thread, which then performs some work before passing the GIL to the next line.

  • Because this happens so quickly, your threads may appear to be running parallel to the naked eye, but they share the same CPU core.

  • The execution time is increased by all of this GIL passing. Using the threading package to make your code run faster isn't always a good idea.

New extensions can only be linked if the compiled procedure is passed therefore compiling and linking are required. 

When dynamic loading is employed, the system-provided style is taken into account. The python interpreter can be used to dynamically load configuration setup files and rebuild the interpreter.

The steps that must be taken are as follows:

  1. Make a file with any name and any language that your system's compiler supports. Consider file.c or file.cpp.

  2. This file should be included in the distribution's Modules/ directory.

  3. Insert a line into the Setup.local file in the Modules/ directory.

  4. To run the file, use the spam file. o

  5. After a successful run, use the make command on the top-level directory to rebuild the interpreter.

  6. If the file is changed, run rebuildMakefile using the command 'make Makefile.'

Python libraries are collections of Python packages. For example, NumPy, Pandas, Matplotlib, Scikit-learn, and many other Python libraries are widely used.

To split a string in Python, use the split() method.

Example:

a="tutorials freak"

print(a.split())

Output: 

['tutorials', 'freak']

Encapsulation is combining variables and functions into a single object, or capsule.

The class best demonstrates encapsulation in Python.

You can use the import keyword to import modules. Modules can be imported in three ways:

Example:

  1. import array #importing using the original module name

  2. import array as arr # importing using an alias name

  3. from array import * #imports everything present in the array

  4. What is Polymorphism in Python?

The ability of code to take different forms is known as polymorphism. For example, if the parent class has XYZ's method, the child class can have XYZ with its variables and parameters.

This is accomplished by importing the random module, which is used to produce random integers.

Syntax:

import random

 

random.random # returns the floating point random number between the range of [0,1].

The lower() method is used to lowercase a string.

For Example:

demo_string='ROSES'

 

print(demo_string.lower())

The pop method is used to remove the last object from a Python list.

For example:

list.pop(obj=list[-1]): 

The number -1 signifies the list's last element. As a result, the pop() function eliminates the list's last object (obj).

  • When Python exits, some Python modules exit as well, mainly circular references to other objects or objects from global namespaces, which are not necessarily de-allocated or deleted.

  • It is not feasible to de-allocate the memory that the C library has reserved.

  • Python's efficient cleanup mechanism would attempt to de-allocate all objects on exit.

Python Comments are statements used by programmers to make their code more readable. 

For example, # can define a single comment, and docstrings can be used to comment on multiple lines (strings enclosed within triple quotes).

For example:

#Comments in Python

 

print("Comments in Python ")

  • The acronym NumPy stands for "Numerical Python."

  • SciPy or Scientific Python is used to perform general and efficient mathematical computations on numerical data stored in arrays. Sorting, indexing, reshaping, and other operations

  • This module contains a set of Python utilities for performing operations, including integration, differentiation, and more.

  • Although this module contains some linear algebraic functions, they are not complete.

  • For algebraic computations, SciPy provides full-featured algebraic functions.

With the exception of access specifiers, Python is an object-oriented programming language that incorporates all important OOPs principles. 

Strong encapsulation is not possible in Python (adding a private keyword before data members). It does, however, utilise two underscores before a data member as a data hiding practise.

Python, unlike Java, provides extensive inheritance and usage support to its users. A situation in which a class is produced from numerous parent classes is described in many legacies. This provides users with a wealth of features and benefits.

The Pickle module accepts the Python object, which turns it into a string representation and saves it to a file using the dump method. 

Pickling is the name for this method. On the other hand, unpickling is the process of recovering the original Python objects from the string representation.

Tkinter is a Python package for creating graphical user interfaces (GUIs). It is Python's standard GUI development toolkit. Tkinter is included with Python. Therefore no additional installation is required. You can use it right away by having it in your script.

  • A documentation string, or docstring, is a multiline string that is used to describe a code segment.

  • The function or method should be described in the docstring.

  • Python's unit testing framework is called the unit test.

  • Python's Unit testing refers to the testing of individual software components. Could you explain why unit testing is so important?

  • Consider the following scenario: you're developing software with three parts: The letters A, B, and C Assume your software malfunctions at some point. How will you know which component caused the software to fail?Perhaps part A failed, causing component B to fail and the software to fail. There are numerous possible combinations.

  • This is why it's essential to thoroughly test every component to determine which one is to blame for the software's failure.

  • As the name implies, Slicing is the process of removing portions of anything.

  • [start: stop: step] is the slicing syntax.

  • The initial index from which to slice a list or tuple is started.

  • The ending index, or where to sop, has come to a halt.

  • The number of steps to jump is called a step.

  • The start is set to 0, stop to the number of objects, and step to one.

  • Strings, arrays, lists, and tuples can all be sliced.

In Python, arrays can only contain items of the same data type, i.e., the array's data type should be homogeneous. It's a lightweight wrapper for C language arrays that use far less memory than lists.

Python lists can include items of many data types, making the data type of lists heterogeneous. In addition, it has the drawback of using a lot of 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

The pass keyword in Python signifies a null operation. It's frequently used to fill in blank pieces of code that might run during runtime but haven't been written yet. If the pass statement is not utilized in the following code, we may run into problems during execution.

def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block

Global variables are public variables defined in the global scope. The global keyword is used within a function to reference a variable in the global scope.

Protected attributes, such as _sara, have an underscore before their identification. They can still be accessed and altered outside of the class that defines them, but a responsible developer should avoid doing so.

Private attributes have a double underscore before their identifier, such as __ansh. They cannot be accessed or updated directly from the outside, and any effort to do so will result in an AttributeError.

Python modules and packages are two technologies for allowing modular programming in Python. There are various advantages to modularizing:

  • Simplicity: Working on a single module with simplicity helps you to focus on a small portion of the problem. This facilitates the development and reduces the likelihood of errors.

  • Maintainability: Modules are intended to impose logical boundaries between distinct problem domains. If changes to one module are written in a way that minimizes interdependence, They are less likely to have an impact on other areas of the program.

  • Reusability: The functions of a module can be simply reused by other parts of the program.

  • Scoping: Modules usually have their own namespace, which helps to avoid confusion with identifiers from other sections of the application.

Modules are Python files with the.py extension that contain a collection of declared and implemented functions, classes, or variables. Using the import statement, they can be imported and initialized once. 

If only partial functionality is required, import the necessary classes or functions from the foo import bar.

Dot notation allows for hierarchical organizing of the module namespace with packages. Similarly, modules assist in avoiding conflicts between global variable names; packages help avoid conflicts between module names. 

Because it makes use of the system's built-in file structure, creating a package is simple. Simply place the modules in a folder, and the folder name will serve as the package name. 

When importing a module or its contents from this package, the package name must come first, then the module name, separated by a dot.

Note: You can potentially import the package as well, but it will not import the package's modules to the local namespace, making it essentially worthless.

The Python Memory Manager manages the memory management in Python. The manager provides memory in the form of a private heap region devoted to Python. 

This heap holds all Python objects and is inaccessible to the programmer because it is personal. Python, however, includes several essential API functions for working with the private heap space.

In Python, a namespace ensures that object names are unique and can be used without conflict. In Python, these namespaces are implemented as dictionaries with a 'name as the key' and a 'object as the value.'

Because of this, multiple namespaces can use the same name and map it to various things. The following are some namespace examples:

  • Within a function, local names are stored in the Local Namespace. When a function is called, the Namespace is temporarily created and removed when the function returns.

  • The names of various imported packages/modules used in the current project are stored in the Global Namespace. Python also features a built-in garbage collection system that recycles unneeded memory for the private heap area. This Namespace is generated when the script imports the package and lasts till the script is executed.

  • Built-in Namespace contains essential Python built-in functions and built-in names for different types of exceptions.

The scope of objects to which a namespace is mapped determines its lifespan. When the scope of an object expires, so does the Namespace's lifespan. As a result, accessing inner namespace objects from an outer namespace is impossible

To send emails, Python contains the smtplib and email libraries. Import these modules into the freshly constructed mail script and send email to authenticated users.

It has an SMTP method (smtp-server, port). To establish an SMTP connection, two parameters are required.

Below is a simple example of how to send an email:

import smtplib    
# Calling SMTP    
s = smtplib.SMTP('smtp.gmail.com', 587)    
# TLS for network security    
s.starttls()    
# User email Authentication    
s.login("sender@email_id", "sender_email_id_password")    
# Message to be sent    
message = "Message_sender_need_to_send"    
# Sending the mail    
s.sendmail("sender@email_id ", "receiver@email_id", message)

Explain the difference between Python Arrays and Python Lists?

In Python, arrays and lists both store data in the same way. On the other hand, Arrays can only have a single data type element, whereas lists can contain any data type element.

Example:

import array as arr  
User_Array = arr.array('i', [1,2,3,4])  
User_list = [1, 'abc', 1.20]  
print (User_Array)  
print (User_list) 

Output:

array('i', [1, 2, 3, 4])
[1, 'abc', 1.2]

In Python, type conversion converts one data type to another.

  • int() is a function that converts any data type to an integer.

  • float() is a function that converts any data type to a float type.

  • ord() is a function that converts characters to integers.

  • hex() is a function that converts integers to hexadecimal.

  • oct() transforms an integer into an octal value.

To convert to a tuple, use the tuple() function.

  • set() - After converting to set, this function returns the type.

  • list()- The list() method can transform any data type into a list.

  • dict() - This function creates a dictionary from a tuple of order (key,value).

  • str() - Converts an integer to a string.

The function complex(real,imag) transforms real values to complex(real,imag) numbers.

 

An anonymous function in Python is one that has no name. The keyword "def" is used to describe conventional functions, whereas the lambda function represents anonymous functions.

The statement is not included in lambda forms in Python because it is used to create new function objects and return them at runtime.

Pythons function is a piece of code that is only executed when it is called. To define a Python function, use the def keyword. 

Example:

def New_func():  
    print ("Hi, Welcome to Tutorials Freak")  
New_func() #calling the function  

Output:

Hi, Welcome to Tutorials Freak

Python includes email and smtplib packages for sending emails. Import these modules into the freshly constructed mail script and deliver mail to authenticated users.

The help() function shows the documentation string and provides access to module, keyword, and attribute support.

The dir() method is used to display the symbols that have been declared.

Python 2 is an older Python programming language version. Python 3 is the most recent version. Python 2 is no longer supported. Python 3 is the language's present and future.

The print statement is the most noticeable difference between Python2 and Python3 (function). It looks like printing "Hello" in Python 2 and printing "Hello" in Python 3. ("Hello").

In Python2, a string is inherently ASCII.

while in Python 3, it is Unicode.

The xrange() function has been deprecated in Python 3. Instead, a new keyword was introduced in the Error Handling section.

Some coding is done at compile time in Python, but most of the checking, such as type, name, and so on, is done during execution. As a result, if the Python code references to an undefined user-defined function, the function will be ignored, the code will compile correctly. 

However, when the code execution path does not exist, the Python code will fail with an exception.

The quickest approach to open a text file is to use the "with" command like follows:

Example:

with open("FILE NAME", "r") as fp:  
fileData = fp.read()    
# To print the contents of the file     
print(fileData)

Output:

"The data of the file will be printed."

The enumerate() function iterates across the sequence, retrieving the index location and matching value.

Example:

list_1 = ["A","B","C"]  
s_1 = "Javatpoint"   
# creating enumerate objects  
object_1 = enumerate(list_1)  
object_2 = enumerate(s_1)  
   
print ("Return type:",type(object_1))  
print (list(enumerate(list_1)))  
print (list(enumerate(s_1))) 

Output:

Return type: 

[(0, 'A'), (1, 'B'), (2, 'C')]

[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7, 'i')

These are the most common errors in Python:

  • ArithmeticError: It serves as the foundation class for all arithmetic exceptions. It is raised when there are arithmetic errors.

  • ImportError: This error occurs when you try to import a module that does not exist. This type of issue occurs when you make a typo in the module name or if the module is not found in the standard path.

  • IndexError: When you try to refer to a sequence that is out of range, an IndexError is raised.

A Python Array is a collection of similar data structures with the same data type of elements. It is used to store data collections. The "array" module in Python is responsible for arrays. When utilizing the array module, the array's elements must all be of the same numeric type.

Example:

import array as myarray

abc = myarray.array('d', [2.5, 4.9, 6.7])

Database-driven apps are supported by Flask (RDBS). Creating a schema for such a system necessitates piping the shema.sql file into a sqlite3 program. 

To create or start a database in Flask, you'll need to install the sqlite3 command.

Flask supports three different database requests.

  • before_request() is called before a request and takes no arguments.

  • after_request() is called after a request and takes no arguments. It is invoked in response to a request and passes the answer to the client.

  • teardown _request(): When an exception is triggered, and a response is not guaranteed, it is called. After the reaction has been built, they are summoned. They can't change the request, and their values aren't considered.

The data on the failed server is not lost, however, you can set up an auto-failure option for several nodes. When a socket or Memcached server experiences an error, fail-over can happen, but not when a client meets an error, such as when adding an existing key.

The dogpile effect occurs when a cache expires, and many requests from a single client arrive simultaneously on a website. 

This can be avoided by using a semaphore lock. When the value expires in this system, the first process takes over the safety and begins creating a new deal.

The following are some reasons why you should avoid using Memcached in your Python project:

  • Memcached is usually erroneously regarded as a data store rather than a cache.

  • Never rely only on Memcached to get data for your application. Data should always be accessible from multiple sources.

  • Memcached is key-value storage that cannot be queried or looped through to extract information.

  • Memcached lacks security features like encryption and authentication.

The if statement in Python is used to make decisions. It has a body of code that only executes when the if statement's condition is true. If the state is false, the else statement, which includes code for the else condition, is completed.

When you wish to justify one condition while the other is false, you use the if-else statement in Python.

Python is an interpreted programming language. In Python source code is used to run the program. First, it translates the programmer's source code into an intermediate language, then translated into machine language, which must execute.