What Is The Namespace In Python
The namespace is a fundamental idea to structure and organize the code that is more useful in large projects. However, it could be a bit difficult concept to grasp if you’re new to programming. Hence, we tried to make namespaces just a little easier to understand.
A namespace is defined as a simple system to control the names in a program. It ensures that names are unique and won’t lead to any conflict.
Also, Python implements namespaces in the form of dictionaries and maintains name-to-object mapping where names act as keys and the objects as values.
How Will You Get The Items That Are Not Common To Both The Given Series A And B
We can achieve this by first performing the union of both series, then taking the intersection of both series. Then we follow the approach of getting items of union that are not there in the list of the intersection.
The following code demonstrates this:
import pandas as pdimport numpy as npdf1 = pd.Seriesdf2 = pd.Seriesp_union = pd.Series) # union of seriesp_intersect = pd.Series) # intersection of seriesunique_elements = p_unionprint"""Output:0 21 42 55 136 157 17dtype: int64"""
Top Python Interview Questions And Answers For Experienced
If you are experienced then surely you have worked on projects and this is the only tool which can drive the interview on your side. Lets explore the most important python interview questions for experienced.
1. What is a closure in Python?
A closure in Python is said to occur when a nested function references a value in its enclosing scope. The whole point here is that it remembers the value.
> > > def A:
3. What is the Dogpile effect?
In case the cache expires, what happens when a client hits a website with multiple requests is what we call the dogpile effect. To avoid this, we can use a semaphore lock. When the value expires, the first process acquires the lock and then starts to generate the new value.
4. Explain garbage collection with Python.
The following points are worth nothing for the garbage collector with CPython-
Python maintains a count of how many references there are to each object in memory
When a reference count drops to zero, it means the object is dead and Python can free the memory it allocated to that object
The garbage collector looks for reference cycles and cleans them up
Python uses heuristics to speed up garbage collection
Recently created objects might as well be dead
The garbage collector assigns generations to each object as it is created
It deals with the younger generations first.
5. Differentiate between split, sub, and subn methods of the remodule.
split- This makes use of a regex pattern to split a string into a list
What Is The Use Of Help And Dir Functions
help function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help function, then an interactive help utility is launched on the console.dir function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.
- For Modules/Library objects, it returns a list of all attributes, contained in that module.
- For Class Objects, it returns a list of all valid attributes and base attributes.
- With no arguments passed, it returns a list of attributes in the current scope.
What Would You Do If You Wanted To Create Multiple Dags With Similar Functionalities But With Different Arguments
We can use the concept of Dynamic DAGs generation. We can define a create_dag method which can take a fixed number of arguments, but the arguments will be dynamic. The dynamic arguments can be passed to the create_dag method through Variables, Connections, Config Files, or just passing a hard-coded value to the method.
Recommended Reading: Preparing For Google Coding Interview
Is Django Better Than Flask
Django is more popular because it has plenty of functionality out of the box, making complicated applications easier to build. Django is best suited for larger projects with a lot of features. The features may be overkill for lesser applications.
If youre new to web programming, Flask is a fantastic place to start. Many websites are built with Flask and receive a lot of traffic, although not as much as Django-based websites. If you want precise control, you should use flask, whereas a Django developer relies on a large community to produce unique websites.
Are Function Arguments Passed By Reference Or By Value
All function arguments are passed by reference in Python: this means that if you pass a parameter to a function, the function gets a reference to that same object.
If the object is mutable and the function changes it, the parameter will mutate in the outer scope of the function. Lets see an example:
Also Check: Cracking The Coding Interview Audiobook
What Are The Differences Between List And Tuple
Both List and Tuple in Python belong to the class of data structure and are defined to store objects in a given order. While the two have their share of similarities, they differ dramatically.
Difference between List and Tuple:
- Starting with the type, Lists are of type List and Tuples are of type tuple.
- The syntax of the two is also different. To declare and define a List, we use , whereas to define Tuple, are used.
Example: List and Tuple in Python
list_1 = tup_1 =
Another difference between List and Tuple is their mutability. Python Lists are mutable, and so they can be modified or edited. However, Python tuples are immutable. It is not possible to change a tuple after declaration. If you try to make changes to a Tuple, the Python interpreter returns an error.
Basic Python Interview Questions For Freshers With Answers
If you are looking for a Python developer job as a fresher, here are some top and common Python basic interview questions that will land you a decent job.
Python is a highly comprehensive and object-oriented programming language. It uses keywords and not just punctuations. It has way fewer syntactic constructions than other programming languages.
Here are some of the interview questions on Python for freshers to check their knowledge and improve their skills. If you know the answers to these questions, there are better chances of you clearing the interview.
You May Like: How To Send An Email After Interview
Why Don’t We Use Variables Instead Of Airflow Xcoms And How Are They Different
An XCom is identified by a “key,” “dag id,” and the “task id” it had been called from. These work just like variables but are alive for a short time while the communication is being done within a DAG. In contrast, the variables are global and can be used throughout the execution for configurations or value sharing.
There might be multiple instances when multiple tasks have multiple task dependencies defining a variable for each instance and deleting them at quick successions would not be suitable for any process’s time and space complexity.
Q23what Is Type Conversion In Python
Ans: Type conversion refers to the conversion of one data type into another.
int converts any data type into integer type
float converts any data type into float type
ord converts characters into integer
hex converts integers to hexadecimal
converts integer to octal
tuple This function is used to convert to a tuple.
set This function returns the type after converting to set.
list This function is used to convert any data type to a list type.
dict This function is used to convert a tuple of order into a dictionary.
str Used to convert integer into a string.
complex This function converts real numbers to complex number.
Q24. How to install Python on Windows and set path variable?
Ans: To install Python on Windows, follow the below steps:
- Install python from this link:
- After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python.
- Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
- Look for the path variable, select its value and select edit.
- Add a semicolon towards the end of the value if its not present and then type %PYTHON_HOME%
Read Also: Peer Support Specialist Interview Questions
Q: What Is The Difference Between A Tuple And A List
Both tuples and lists are used for storing and collecting the data.
The list is declared with square brackets , whereas tuples are declared with round brackets
The List is mutable and primarily used for data insertion and deletion. It also has several built-in functions.
The Tuple is immutable. The iteration is comparatively fast and consumes less memory than a list. It is mostly used for accessing the elements fast.
What Is The Difference Between The Two Data Series Given Below
df and df.loc, where:
df = pd.DataFrame
Choose the correct option:
Answer – 3. Both are copies of the original dataframe.
Also Check: What To Wear To An Interview Women
List The Common Built
Given below are the most commonly used built-in datatypes :
Numbers: Consists of integers, floating-point numbers, and complex numbers.Example:
List: We have already seen a bit about lists, to put a formal definition a list is an ordered sequence of items that are mutable, also the elements inside lists can belong to different data types.
Tuples: This too is an ordered sequence of elements but unlike lists tuples are immutable meaning it cannot be changed once declared.
String: This is called the sequence of characters declared within single or double quotes.
Hi, I work at great learningHi, I work at great learning
Sets: Sets are basically collections of unique items where order is not uniform.
Dictionary: A dictionary always stores values in key and value pairs where each value can be accessed by its particular key.
Boolean: There are only two boolean values: True and False
Q10 Write A Program To Read And Write The Binary Data Using Python
The module that is used to write and read the binary data is known as struct. This module allows the functionality and with it many functionalities to be used that consists of the string class. This class contains the binary data that is in the form of numbers that gets converted in python objects for use and vice versa. The program can read or write the binary data is:
import structf = open# This Open method allows the file to get opened in binary mode to make it portable for # use.s = f.readx, y, z = struct.unpack
The > is used to show the format string that allows the string to be converted in big-endian data form. For homogenous list of data the array module can be used that will allow the data to be kept more organized fashion.
Did you know :
Unlike Java and C++, Python does not use braces but Indentation is mandatory.
Python Programming/ Coding Interview Questions
First of all, Python is one of the top programming languages with huge library support. It is free, interpreted language providing flexibility and easy to learn for developers. Python supports multiple programming paradigms like object-oriented programming used to perform general-purpose programming.
This article explains the Python Coding Interview Questions and Answers that helps to boost the coding skills of the aspirants. It explains the coding questions with answers asked in top MNCs. Python training course in Chennai assists in developing all the skills needed for the certified python professional. Global Companies are willing to offer amazing job roles and benefits to Python developers.
Q12 What Are Iterators And Generators
An iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter method. It uses the next method for iteration. Generators in Python are used to create iterators and return a traversal object. It helps in traversing all the items one at a time with the help of the keyword yield.
What Are Some Of The Alternatives To Apache Airflow
Luigi – A python package used to build Hadoop Jobs.
Kedro – Used for creating easy-to-maintain and reproducible modular data science codes.
AWS Step Functions – It is a fully managed, serverless, and low-code visual workflow service used to prepare data for machine learning, build serverless applications, automate ETL processes and orchestrate microservices.
Which Python Library Is Built On Top Of Matplotlib And Pandas To Ease Data Plotting
Seaborn is a Python library built on top of matplotlib and pandas to ease data plotting. It is a data visualization library in Python that provides a high-level interface for drawing statistical informative graphs.
Did you know the answers to these Python interview questions? If not, here is what you can do.
Recommended Reading: How To Analyse An Interview
Q: Odd Or Even Determine That
Determine if the sum of n consecutive numbers is even, odd, or either.
- odd_or_even should return Either. The sum can be even or odd.
- odd_or_even should return Odd. The sum of consecutive numbers contains one odd and one even, so the sum will always be odd.
- odd_or_even should return Even. The sum of consecutive numbers contains two even and two odd, so the sum will always be even.
def odd_or_even: if n % 2 == 1: return "Either" elif % 2 == 1: return "Odd" else: return "Even"
To pass this question on the first go, you need to read the description multiple times. The answer is already given in examples.
It is not the only solution. You can find various solutions on the Codewars platform. You can even come up with your unique solution to gain more points.
What Are Dict And List Comprehensions In Python
In Python, dictionary comprehensions are very similar to list comprehensions only for dictionaries. They provide an elegant method of creating a dictionary from an iterable or transforming one dictionary into another.Using an if statement allows you to filter out values to create your new dictionary.
Recommended Reading: How To Crack Amazon Business Analyst Interview
How Do You Achieve Multithreading In Python
Multithreading is an important concept in the world of programming. It allows the execution of multiple tasks at the same time without affecting the performance of each other. An important criterion here is that there must not be any interdependency between the tasks to execute in a multithreading environment.
To achieve multithreading in Python 3, you must first install and then import the package or the threading module.
Syntax: Multithreading in Python 3.
import threading from threading import *
Q10 How To Handle Exceptions
Exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can then choose what operations to perform once we have caught the exception.
Think about that for a min :
In Python, you can declare a local variable in a function, class, or so which will be only visible in that scope. If you call it outside of that scope, then you get an undefined error.
What Are Lambda Expressions
In Python, a lambda function is an anonymous function. It takes any number of arguments but contains a single expression.
As an example, here is a lambda that multiplies a number by three:
lambda x : x * 3
This isnt useful as-is because theres no way to call it. However, you can assign it to a variable and then call it like a regular function:
mult3 = lambda x : x * 3mult3 # returns 45
You dont actually need to assign a lambda to a variable. You can call it like this as well:
# returns 45.0
OutpuLambda functions are useful when the functionality is needed for a short period of time. In this case, you dont want to waste resources by creating a separate method to do the job.
What Does *args And **kwargs Mean
- *args is a special syntax used in the function definition to pass variable-length arguments.
- * means variable length and args is the name used by convention. You can use any other.
defmultiply: mul = a * bfor num in argv: mul *= numreturn mulprint) #output: 120
- **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
- Here, also, kwargs is used just by convention. You can use any other name.
- Keyworded argument means a variable that has a name when passed to a function.
- It is actually a dictionary of the variable names and its value.
deftellArguments:for key, value in kwargs.items:printtellArguments#output:# arg1: argument 1# arg2: argument 2# arg3: argument 3
Airflow Interview Questions On Executors
If you are unable to understand the complications of executors while preparing for your interview, do not worry, this section will cover some basic airflow interview questions on executors that you are likely to get asked in your interview.
5. What are Local Executors and their types in Airflow?
Local Executors run tasks locally inside the scheduler process and are of 3 types:
The Local Executor completes tasks in parallel that run on a single machine . A single Local Worker picks up and runs jobs as scheduled and is fully responsible for all task execution. That means you don’t need resources outside that same machine to run a DAG or multiple DAGs .
Since you can do everything from a single machine, it’s straightforward to set up. But because of the same point, it is less scalable than other executors, and if a failure occurs at any moment, all the tasks will collapse.
The Sequential Executor is similar to the Local Executor, but it will run only one task instance at a time it could be considered a Local Executor with limited parallelism of just one worker . It does identify a single point of failure, which makes it helpful for debugging as well. Also, this is the default executor when installing Airflow we can switch to other airflow configurations anytime.
The Debug Executor is a debug tool and can be used from an IDE. It is a single process executor that queues Task Instances and executes them.
6 . What is a Celery Executor?