Được - Mất khi làm thực tập sinh IT sớm

Trở thành thực tập sinh sớm bạn cũng nên cân nhắc về những thứ được và mất. Không phải bạn đều Được, và cũng không phải ai trở thực tập sinh là sẽ Được. Thậm chí Mất còn nhiều hơn Được.

---

Dạy học Lập trình chất lượng cao NIIT - ICT Hà Nội (Since 2002). Học làm Lập trình viên. Hành động ngay!

Đc: Tầng 3, 25T2, N05, Nguyễn Thị Thập, Cầu Giấy, Hà Nội

SĐT: 02435574074 - 0914939543 - 0353655150

Email: [email protected]

Website: https://niithanoi.edu.vn

Fanpage: https://facebook.com/NIIT.ICT/

#niiticthanoi #hoclaptrinh #khoahoclaptrinh #hoclaptrinhjava #hoclaptrinhphp

Best Java Microservices Interview Questions In 2019

Best Java Microservices Interview Questions In 2019

In this Microservices interview questions article, I have collected the most frequently asked questions by interviewers. These questions are collected after consulting with Microservices Certification Training experts. Let's discuss the best Java Microservices Interview Questions In 2019

Top Microservices Interview Questions

According to Gartner, **microservices **are the new application platform for cloud development. **Microservices **are deployed and managed independently, and once implemented inside containers they have very little interaction with the underlying OS. So, if you are planning to start your career in the **Microservices **and you wish to know the skills related to it, now is the right time to dive in, when the technology is in its nascent state.

In case you have attended any **Microservices interview **in the recent past, do paste those interview questions in the comments section and we’ll answer them ASAP. You can also comment below if you have any **questions **in your mind, which you might face in your Microservices interview.

You may go through this recording of Microservices Interview Questions and **Answers **where our instructor has explained the topics in a detailed manner with examples that will help you to **understand **this concept better.

Q1. List down the advantages of Java Microservices Architecture.

Q2. What do you know about Microservices?

Microservices, aka Microservice Architecture, is an architectural style that structures an application as a collection of small autonomous services, modeled around a **business domain.**In layman terms, you must have seen how bees build their honeycomb by aligning hexagonal wax cells.They initially start with a small section using various materials and continue to build a large beehive out of it.These cells form a pattern resulting in a strong structure which holds together a particular section of the beehive.Here, each cell is independent of the other but it is also correlated with the other cells.This means that damage to one cell does not damage the other cells, so, bees can reconstruct these cells without impacting the complete beehive.

Fig 1: Beehive Representation of Microservices – Microservices Interview Questions

Refer to the above diagram. Here, each hexagonal shape represents an individual service component. Similar to the working of bees, each agile team builds an individual service component with the available frameworks and the chosen technology stack. Just as in a beehive, each service component forms a strong microservice architecture to provide better scalability. Also, issues with each service component can be handled individually by the agile team with no or minimal impact on the entire application.

Q3. What are the features of Microservices?

Fig 3: Features of Microservices – Microservices Interview Questions
Decoupling – Services within a system are largely decoupled. So the application as a whole can be easily built, altered, and scaled
Componentization
– Microservices are treated as independent components that can be easily replaced and upgradedBusiness Capabilities – Microservices are very simple and focus on a single capabilityAutonomy – Developers and teams can work independently of each other, thus increasing speedContinous Delivery – Allows frequent releases of software, through systematic automation of software creation, testing, and approvalResponsibility – Microservices do not focus on applications as projects. Instead, they treat applications as products for which they are responsibleDecentralized Governance – The focus is on using the right tool for the right job. That means there is no standardized pattern or any technology pattern. Developers have the freedom to choose the best useful tools to solve their problemsAgility – Microservices support agile development. Any new feature can be quickly developed and discarded again## Q4. What are the best practices to design Microservices?

The following are the best practices to design microservices:

**Fig 4: **Best Practices to Design Microservices – Microservices Interview Questions

Q5. How does Microservice Architecture work?

A microservice architecture has the following components:

**Fig 5: **Architecture of Microservices – Microservices Interview Questions
Clients – Different users from various devices send requests.Identity Providers – Authenticates user or clients identities and issues security tokens.API Gateway – Handles client requests.Static Content – Houses all the content of the system.Management – Balances services on nodes and identifies failures.Service Discovery – A guide to find the route of communication between microservices.Content Delivery Networks – Distributed network of proxy servers and their data centers.Remote Service – Enables the remote access information that resides on a network of IT devices.## Q6. What are the pros and cons of Microservice Architecture?

Q7. What is the difference between Monolithic, SOA and Microservices Architecture?

**Fig 6: **Comparison Between Monolithic SOA & Microservices – Microservices Interview Questions
Monolithic Architecture is similar to a big container wherein all the software components of an application are assembled together and tightly packaged.A Service-Oriented Architecture is a collection of services which communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity.Microservice Architecture is an architectural style that structures an application as a collection of small autonomous services, modeled around a business domain.## Q8. What are the challenges you face while working Microservice Architectures?

Developing a number of smaller microservices sounds easy, but the challenges often faced while developing them are as follows.
Automate the Components: Difficult to automate because there are a number of smaller components. So for each component, we have to follow the stages of Build, Deploy and, Monitor.Perceptibility: Maintaining a large number of components together becomes difficult to deploy, maintain, monitor and identify problems. It requires great perceptibility around all the components.Configuration Management: Maintaining the configurations for the components across the various environments becomes tough sometimes.Debugging: Difficult to find out each and every service for an error. It is essential to maintain centralized logging and dashboards to debug problems.## Q9. What are the key differences between SOA and Microservices Architecture?

The key differences between SOA and microservices are as follows:

Q10. What are the characteristics of Microservices?

You can list down the characteristics of microservices as follows:

**Fig 7: **Characteristics of Microservices – Microservices Interview Questions

Q11. What is Domain Driven Design?

**Fig 8: **Principles of DDD – Microservices Interview Questions

Q12. Why there is a need for Domain Driven Design (DDD)?

**Fig 9: **Factors Why we need DDD – Microservices Interview Questions

Q13. What is Ubiquitous language?

If you have to define the** Ubiquitous Language (UL)**, then it is a common language used by developers and users of a specific domain through which the domain can be explained easily.

The ubiquitous language has to be crystal clear so that it brings all the team members on the same page and also translates in such a way that a machine can understand.

Q14. What is Cohesion?

The degree to which the elements inside a module belong together is said to be cohesion.

Q15. What is Coupling?

The measure of the strength of the dependencies between components is said to be coupling. A good design is always said to have High Cohesion and** Low Coupling**.

Q16. What is REST/RESTful and what are its uses?

Representational State Transfer (REST)/RESTful web services are an architectural style to help computer systems communicate over the internet. This makes microservices easier to understand and implement.

Microservices can be implemented with or without RESTful APIs, but it’s always easier to build loosely coupled microservices using RESTful APIs.

Q17. What do you know about Spring Boot?

It’s a knows fact that spring has become more and more complex as new functionalities have been added. If you have to start a new spring project, then you have to add build path or add maven dependencies, configure application server, add spring configuration. So everything has to be done from scratch.

Spring Boot is the solution to this problem. Using spring boot you can avoid all the boilerplate code and configurations. So basically consider yourself as if you’re baking a cake spring is like the ingredients that are required to make the cake and spring boot is the complete cake in your hand.

**Fig 10: **Factors of Spring Boot – Microservices Interview Questions

Q18. What is an actuator in Spring boot?

Spring Boot actuator provides restful web services to access the current state of running an application in the production environment. With the help of actuator, you can check various metrics and monitor your application.

Q19. What is Spring Cloud?

According to the official website of Spring Cloud, Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, leadership election, distributed sessions, cluster state).

Q20. What problems are solved by Spring Cloud?

While developing distributed microservices with Spring Boot we face few issues which are solved by Spring Cloud.
**The complexity associated with distributed systems – **This includes network issues, Latency overhead, Bandwidth issues, security issues.**Ability to handle Service Discovery – **Service discovery allows processes and services in a cluster to find each other and communicate.**Solved redundancy issues – **Redundancy issues often occur in distributed systems.**Load balancing – **Improves the distribution of workloads across multiple computing resources, such as a computer cluster, network links, central processing units.**Reduces performance issues – **Reduces performance issues due to various operational overheads.## Q21. What is the use of WebMvcTest annotation in Spring MVC applications?

WebMvcTest annotation is used for unit testing Spring MVC Applications in cases where the test objective is to just focus on Spring MVC Components. In the snapshot shown above, we want to launch only the ToTestController. All other controllers and mappings will not be launched when this unit test is executed.

Q22. Can you give a gist about Rest and Microservices?

REST

Though you can implement microservices in multiple ways, REST over HTTP is a way to implement Microservices. REST is also used in other applications such as web apps, API design, and MVC applications to serve business data.

Microservices

Microservices is an architecture wherein all the components of the system are put into individual components, which can be built, deployed, and scaled individually. There are certain principles and best practices of Microservices that help in building a resilient application.

In a nutshell, you can say that REST is a medium to build Microservices.

Q23. What are different types of Tests for Microservices?

While working with microservices, testing becomes quite complex as there are multiple microservices working together. So, tests are divided into different levels.
At the bottom level, we have technology-facing tests like- unit tests and performance tests. These are completely automated.At the middle level, we have tests for exploratory testing like the stress tests and usability tests.At the **top level, **we have acceptance tests that are few in number. These acceptance tests help stakeholders in understanding and verifying software features.## Q24. What do you understand by Distributed Transaction?

Distributed Transaction is any situation where a single event results in the mutation of two or more separate sources of data which cannot be committed atomically. In the world of microservices, it becomes even more complex as each service is a unit of work and most of the time multiple services have to work together to make a business successful.

Q25. What is an Idempotence and where it is used?

Idempotence is the property of being able to do something twice in such a way that the end result will remain the same i.e. as if it had been done once only.

Usage: Idempotence is used at the remote service, or data source so that, when it receives the instruction more than once, it only processes the instruction once.

Q26. What is Bounded Context?

Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD’s strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their inter-relationships.

Q27. What is Two Factor Authentication?

Two-factor authentication enables the second level of authentication to an account log-in process.

**Fig11: **Representation of Two Factor Authentication – Microservices Interview Questions

So suppose a user has to enter only username and password, then that’s considered a single-factor authentication.

Q28. What are the types of credentials of Two Factor Authentication?

The three types of credentials are:

**Fig 12: **Types of Credentials of Two Factor Authentication – Microservices Interview Questions

Q29. What are Client certificates?

A type of digital certificate that is used by client systems to make authenticated requests to a remote server is known as the** client certificate**. Client certificates play a very important role in many mutual authentication designs, providing strong assurances of a requester’s identity.

Q30. What is the use of PACT in Microservices architecture?

**PACT **is an open source tool to allow testing interactions between service providers and consumers in isolation against the contract made so that the reliability of Microservices integration increases.

Usage in Microservices:

Used to implement Consumer Driven Contract in Microservices.Tests the consumer-driven contracts between consumer and provider of a Microservice.## Q31. What is OAuth?

**OAuth **stands for open authorization protocol. This allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as third-party providers Facebook, GitHub, etc. So with this, you can share resources stored on one site with another site without using their credentials.

Q32. What is Conway’s law?

“Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure.” –*** Mel Conway***

**Fig 13: **Representation of Conway’s Law – Microservices Interview Questions

This law basically tries to convey the fact that, in order for a software module to function, the complete team should communicate well. Therefore the structure of a system reflects the social boundaries of the organization(s) that produced it.

Q33. What do you understand by Contract Testing?

According to Martin Flower,** contract test **is a test at the boundary of an external service which verifies that it meets the contract expected by a consuming service.

Also, contract testing does not test the behavior of the service in depth. Rather, it tests that the inputs & outputs of service calls contain required attributes and the response latency, throughput is within allowed limits.

Q34. What is End to End Microservices Testing?

End-to-end testing validates each and every process in the workflow is functioning properly. This ensures that the system works together as a whole and satisfies all requirements.

In layman terms, you can say that end to end testing is a kind of tests where everything is tested after a particular period.

**Fig 14: **Hierarchy of Tests – Microservices Interview Questions

Q35. What is the use of Container in Microservices?

Containers are a good way to manage microservice based application to develop and deploy them individually*.* You can encapsulate your microservice in a container image along with its dependencies, which then can be used to roll on-demand instances of microservice without any additional efforts required.

**Fig 15: **Representation of Containers and How they are used in Microservices – Microservices Interview Questions

Q36. What is DRY in Microservices architecture?

DRY stands for Don’t Repeat Yourself. It basically promotes the concept of reusing the code. This results in developing and sharing the libraries which in turn result in tight coupling.

Q37. What is a Consumer-Driven Contract (CDC)?

This is basically a pattern for developing Microservices so that they can be used by external systems. When we work on microservices, there is a particular provider who builds it and there are one or more consumers who use Microservice.

Generally, providers specify the interfaces in an XML document. But in Consumer Driven Contract, each consumer of service conveys the interface expected from the Provider.

Q38. What is the role of Web, RESTful APIs in Microservices?

A microservice architecture is based on a concept wherein all its services should be able to interact with each other to build a business functionality. So, to achieve this, each microservice must have an interface. This makes the web API a very important enabler of microservices. Being based on the open networking principles of the Web, RESTful APIs provide the most logical model for building interfaces between the various components of a microservice architecture.

Q39. What do you understand by Semantic monitoring in Microservices architecture?

Semantic monitoring, also known as** synthetic monitoring** combines automated tests with monitoring the application in order to detect business failing factors.

Q40. How can we perform Cross-Functional testing?

Cross-functional testing is a verification of non-functional requirements, i.e. those requirements which cannot be implemented like a normal feature.

Q41. How can we eradicate non-determinism in tests?

Non-Deterministic Tests (NDT) are basically unreliable tests. So, sometimes it may happen that they pass and obviously sometimes they may also fail. As and when they fail, they are made to re-run to pass.

Some ways to remove non-determinism from tests are as follows:
QuarantineAsynchronousRemote ServicesIsolationTimeResource leaks## Q42. What is the difference between Mock or Stub?

Stub

A dummy object that helps in running the test.Provides fixed behavior under certain conditions which can be hard-coded.Any other behavior of the stub is never tested.
For example, for an empty stack, you can create a stub that just returns true for empty() method. So, this does not care whether there is an element in the stack or not.

Mock

A dummy object in which certain properties are set initially.The behavior of this object depends on the set properties.The object’s behavior can also be tested.
For example, for a Customer object, you can mock it by setting name and age. You can set age as 12 and then test for isAdult() method that will return true for age greater than 18. So, your Mock Customer object works for the specified condition.

Q43. What do you know about Mike Cohn’s Test Pyramid?

Mike Cohn provided a model called Test Pyramid. This describes the kind of automated tests required for software development.

**Fig 16: **Mike Cohn’s Test Pyramid – Microservices Interview Questions

As per pyramid, the number of tests at first layer should be highest. At service layer, the number of tests should be less than at the unit test level, but more than at the end-to-end level.

Q44. What is the purpose of Docker?

Docker provides a container environment that can be used to host any application. In this, the software application and the dependencies which support it are tightly-packaged together.

So, this packaged product is called a Container and since it is done by Docker, it is called Docker container!

Q45. What is Canary Releasing?

Canary Releasing is a technique to reduce the risk of introducing a new software version in production. This is done by slowly rolling out the change to a small subset of users before giving it out to the entire infrastructure, i.e. making it available to everybody.

Q46. What do you mean by Continuous Integration (CI)?

Continuous Integration (CI) is the process of automating the build and testing of code every time a team member commits changes to version control. This encourages developers to share code and unit tests by merging the changes into a shared version control repository after every small task completion.

Q47. What is Continuous Monitoring?

**Continuous monitoring **gets into the depth of monitoring coverage, from in-browser front-end performance metrics, through application performance, and down to host virtualized infrastructure metrics.

Q48. What is the role of an architect in Microservices architecture?

An architect in microservices architecture plays the following roles:
Decides broad strokes about the layout of the overall software system.Helps in deciding the zoning of the components. So, they make sure components are mutually cohesive, but not tightly coupled.Code with developers and learn the challenges faced in day-to-day life.Make recommendations for certain tools and technologies to the team developing microservices.Provide technical governance so that the teams in their technical development follow principles of Microservice.## Q49. Can we create State Machines out of Microservices?

As we know that each Microservice owning its own database is an independently deployable program unit, this, in turn, lets us create a State Machine out of it. So, we can specify different states and events for a particular microservice.

For Example, we can define an Order microservice. An Order can have different states. The transitions of Order states can be independent events in the Order microservice.

Q50. What are Reactive Extensions in Microservices?

Reactive Extensions also are known as Rx. It is a design approach in which we collect results by calling multiple services and then compile a combined response. These calls can be synchronous or asynchronous, blocking or non-blocking. Rx is a very popular tool in distributed systems which works opposite to legacy flows.

Hope these Microservices Interview Questions would help you in your Microservices Architect Interviews.

Spring Framework - Top 50 Questions for Interview In 2019

Spring Framework - Top 50 Questions for Interview In 2019

In this article, you'll see top 50 Spring interview questions which are most likely to be asked by the interviewer. If you are seeking a future in this field, these questions will surely help you to ace the interview.

In this article, you'll see top 50 Spring interview questions which are most likely to be asked by the interviewer. If you are seeking a future in this field, these questions will surely help you to ace the interview.

Are you thinking of pursuing your career in Spring Framework? Are you searching for an appropriate QnA set to prepare for your interviews? Here is a blog on Spring Interview Questions which discusses on top 50 questions with proper explanation and examples. It will definitely help you to ace the interviews. But before starting with the Spring Interview Questions, let’s take a quick look on Spring Framework’s demand and status in the market.

Since it’s release, the Spring Framework has continued to bloom in the market. Spring community is continuously coming up with new things and have spread into a vast ecosystem. Today, it holds the top position in the framework market. Check out the below graph which shows the frameworks most frequently used in the market as on January 2018.

You might ask why is Spring certification so much in demand? Well, the answer is, because it provides a comprehensive programming and configuration model for modern Java-based enterprise applications. It is not concerned with the deployment platform used. A key element of Spring Framework is infrastructural support at the application level. It’s very much unlikely to go out of the market in the near future with more major releases announced.

Before we move any further let us take a look some of the most frequently asked Spring Interview Questions,

Q1. What are the major features in different versions of Spring Framework?

Q2. What is a Spring Framework?

Q3. List the advantages of Spring Framework

Q4. What are the different features of Spring Framework?

Q5. How many modules are there in Spring Framework and what are they?

Q6. What is a Spring configuration file?

Q7. What are the different components of a Spring application?

Q8. What are the various ways of using Spring Framework?

Q9. What is Spring IOC Container?

Q10. What do you mean by Dependency Injection?

Spring Interview Questions

So, here are the Top 50 Spring Interview Questions which are most likely to be asked by the interviewer. If you are seeking a future in this field, these questions will surely help you to ace the interview. For your ease of access, I have categorized the questions under a few topics, namely:

  • General Questions
  • Dependency Injection/ IoC
  • Spring Beans
  • Spring Annotations
  • Spring Data Access
  • Spring AOP
  • Spring MVC

You may watch the webinar recording of Spring Interview Questions where our instructor has shared his experience and expertise that will help you to crack any Spring Interview.

Let’s begin with the first section of Spring interview questions that is the General Questions.

General Questions – Spring Interview Questions

1. What are the major features in different versions of Spring Framework?

2. What is a Spring Framework?


Spring is a powerful open source, application framework created to reduce the complexity of enterprise application development.It is light-weighted and loosely coupled.It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development.Spring framework is also called the framework of frameworks as it provides support to various other frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc.### 3. List the advantages of Spring Framework.
Because of Spring Frameworks layered architecture, you can use what you need and leave which you don’t.Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.JDBC is simplified due to Dependency Injection and Inversion of Control.It is open-source and has no vendor lock-in.### 4. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :
Lightweight: Spring is lightweight when it comes to size and transparency. Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion Of Control.Aspect oriented Programming (AOP): Aspect oriented programming in Spring supports cohesive development by separating application business logic from system services.**Container: **Spring Framework creates and manages the life cycle and configuration of the application objects.MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container less environments.JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.### 5. How many modules are there in Spring Framework and what are they?

There are around 20 modules which are generalized into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test.

**Spring Core Container – This layer is basically the core of Spring Framework. **It contains the following modules:1. Spring Core

  1. Spring Bean
  2. SpEL (Spring Expression Language)
  3. Spring Context
    **Data Access/Integration – This layer provides support to interact with the database. It contains the following modules:JDBC (Java DataBase Connectivity)ORM (Object Relational Mapping)OXM (Object XML Mappers)JMS (Java Messaging Service)TransactionWeb – **This layer provides support to create web application. It contains the following modules :1. Web
  4. Web – MVC
  5. Web – Socket
  6. Web – Portlet
    Aspect Oriented Programming (AOP) – In this layer you can use Advices, Pointcuts etc., to decouple the code.**Instrumentation – **This layer provides support to class instrumentation and classloader implementations.**Test – **This layer provides support to testing with JUnit and TestNG.
    Few Miscellaneous modules are given below:
    **Messaging – *This module provides support for STOMP. It also supports an annotation programming model that is used for routing and processing STOMP messages from WebSocket clients. **Aspects – **This module provides support to integration with AspectJ.

6. What is a Spring configuration file?

A Spring configuration file is an XML file. This file mainly contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and more clean. If it’s not planned and written correctly, it becomes very difficult to manage in big projects.

7. What are the different components of a Spring application?

A Spring application, generally consists of following components:
Interface: It defines the functions.Bean class: It contains properties, its setter and getter methods, functions etc.Spring Aspect Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.Bean Configuration File: Contains the information of classes and how to configure them.User program: It uses the function.### 8. What are the various ways of using Spring Framework?

Spring Framework can be used in various ways. They are listed as follows:

  1. As a Full-fledged Spring web application.
  2. As a third-party web framework, using Spring Frameworks middle-tier.
  3. For remote usage.
  4. As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java Objects).

The next section of Spring Interview Questions is on Dependency Injection and IoC container.

Dependency Injection/ IoC Container – Spring Interview Questions

9. What is Spring IOC Container?

At the core of the Spring Framework, lies the Spring container. The container creates the object, wires them together, configures them and manages their complete life cycle. The Spring container makes use of Dependency Injection to manage the components that make up an application. The container receives instructions for which objects to instantiate, configure, and assemble by reading the configuration metadata provided. This metadata can be provided either by XML, Java annotations or Java code.

**10. What do you mean by Dependency Injection? **

In Dependency Injection, you do not have to create your objects but have to describe how they should be created. You don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.

11. In how many ways can Dependency Injection be done?

In general, dependency injection can be done in three ways, namely :

  • Constructor Injection
  • Setter Injection
  • Interface Injection

In Spring Framework, only constructor and setter injections are used.

12. Differentiate between constructor injection and setter injection.

Constructor Injection vs Setter Injection

13. How many types of IOC containers are there in spring?

BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface. It provides some extra functionality on top BeanFactory.### 14. Differentiate between BeanFactory and ApplicationContext.

BeanFactory vs ApplicationContext

15. List some of the benefits of IoC.

Some of the benefits of IoC are:
It will minimize the amount of code in your application.It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.It promotes loose coupling with minimal effort and least intrusive mechanism.It supports eager instantiation and lazy loading of the services.
Let’s move on to the next section of Spring Interview Questions, that is Spring Beans Interview Questions.

Spring Beans – Spring Interview Questions

16. Explain Spring Beans?

They are the objects that form the backbone of the user’s application.Beans are managed by the Spring IoC container.They are instantiated, configured, wired and managed by a Spring IoC containerBeans are created with the configuration metadata that the users supply to the container.### 17. How configuration metadata is provided to the Spring container?

Configuration metadata can be provided to Spring container in following ways:
**XML-Based configuration: **In Spring Framework, the dependencies and the services needed by beans are specified in configuration files which are in XML format. These configuration files usually contain a lot of bean definitions and application specific configuration options. They generally start with a bean tag. For example:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
 <property name="name" value="Edureka"></property>
</bean>

  • Annotation-Based configuration: Instead of using XML to describe a bean wiring, you can configure the bean into the component class itself by using annotations on the relevant class, method, or field declaration. By default, annotation wiring is not turned on in the Spring container. So, you need to enable it in your Spring configuration file before using it. For example:
<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>

**Java-based configuration: **The key features in Spring Framework’s new Java-configuration support are @Configuration annotated classes and @Bean annotated methods. > @Bean annotation plays the same role as the element. > @Configuration classes allows to define inter-bean dependencies by simply calling other @Bean methods in the same class.
For example:

@Configuration
public class StudentConfig
{
@Bean
public StudentBean myStudent()
{ return new StudentBean(); }
}

18. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:
**Singleton: **This provides scope for the bean definition to single instance per Spring IoC container.**Prototype: **This provides scope for a single bean definition to have any number of object instances.**Request: **This provides scope for a bean definition to an HTTP-request. **Session: **This provides scope for a bean definition to an HTTP-session. **Global-session: **This provides scope for a bean definition to an Global HTTP-session.
The last three are available only if the users use a web-aware ApplicationContext.

19. What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:
The Spring container instantiates the bean from the bean’s definition in the XML file.Spring populates all of the properties using the dependency injection, as specified in the bean definition.The factory calls setBeanName() by passing the bean’s ID, if the bean implements the BeanNameAware interface.The factory calls setBeanFactory() by passing an instance of itself, if the bean implements the BeanFactoryAware interface.preProcessBeforeInitialization() methods are called if there are any BeanPostProcessors associated with the bean.If an init-method is specified for the bean, then it will be called.Finally, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean.
To understand it in better way check the below diagram:

20. Explain inner beans in Spring.

A bean can be declared as an inner bean only when it is used as a property of another bean. For defining a bean, the Spring’s XML based configuration metadata provides the use of element inside the or . Inner beans are always anonymous and they are always scoped as prototypes. For example, let’s say we have one Student class having reference of Person class. Here we will be creating only one instance of Person class and use it inside Student.

Here’s a Student class followed by bean configuration file:

Student.java

public class Student
{
private Person person;
//Setters and Getters
}
public class Person
{
private String name;
private String address;
//Setters and Getters
}

studentbean.xml

<bean id=&ldquo;StudentBean" class="com.edureka.Student">
<property name="person">
<!--This is inner bean -->
<bean class="com.edureka.Person">
<property name="name" value=&ldquo;Scott"></property>
<property name="address" value=&ldquo;Bangalore"></property>
</bean>
</property>
</bean>

21. Define Bean Wiring.

When beans are combined together within the Spring container, it’s called wiring or bean wiring. The Spring container needs to know what beans are needed and how the container should use dependency injection to tie the beans together, while wiring beans.

22. What do you understand by auto wiring and name the different modes of it?

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.

Different modes of bean auto-wiring are:
no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring.byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.**byType: **It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the beans name in XML file.**constructor: **It injects the dependency by calling the constructor of the class. It has a large number of parameters.**autodetect: **First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.### 23. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:
**Overriding possibility: You can always specify dependencies using and settings which will override autowiring. Primitive data type: **Simple properties such as primitives, Strings and Classes can’t be autowired.**Confusing nature: **Always prefer using explicit wiring because autowiring is less precise.
In the next section, we will discuss on Spring Annotations Interview Questions.

Spring Annotations – Spring Interview Questions

24. What do you mean by Annotation-based container configuration?

Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. It acts as an alternative to XML setups. For example:

@Configuration
public class AnnotationConfig
{
@Bean
public MyDemo myDemo()
 { return new MyDemoImpll(); }
}

25. How annotation wiring can be turned on in Spring?

By default, Annotation wiring is not turned on in the Spring container. Thus, to use annotation based wiring we must enable it in our Spring configuration file by configuring context:annotation-config/ element. For example:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context">
<context:annotation-config/>
<beans &hellip;&hellip;&hellip;&hellip; />
</beans>

26. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and** **makes the unchecked exceptions eligible for translation into Spring DataAccessException.

27. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at the configuration time with the help of an explicit property value in a bean definition or with autowiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.

For example:

public class Employee
{
private String name;
@Required
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
}

28. What do you understand by @Autowired annotation?

The @Autowired annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property or methods with arbitrary names or multiple arguments. By default, it is a type driven injection.

For Example:

public class Employee
{
private String name;
@Autowired
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
}

29. What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of them with a property you can use the @Qualifier annotation along with @Autowired to remove the ambiguity by specifying which exact bean should be wired.

For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

Employee.java

public class Employee
{
private String name;
@Autowired
public void setName(String name)
{ this.name=name; }
public string getName()
{ return name; }
}

EmpAccount.java

public class EmpAccount
{
private Employee emp;
@Autowired
@Qualifier(emp1)
public void showName()
{
System.out.println(&ldquo;Employee name : &rdquo;+emp.getName);
}
}

30. What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in controller that will be handling the respective request. This annotation can be applied at both levels:

  • **Class level **: Maps the URL of the request
  • Method level: Maps the URL as well as HTTP request method

Next section of Spring Interview Questions is on Data Access.

Data Access – Spring Interview Questions

31. Describe Spring DAO support?

The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies easily. It also allows you to code without worrying about catching exceptions that are specific to each of these technology.

32. Name the exceptions thrown by the Spring DAO classes.

See the below diagram, it depicts all the Spring DAO classes in the hierarchical order.

33. Which classes are present in spring JDBC API?

Classes present in JDBC API are as follows:

  1. JdbcTemplate
  2. SimpleJdbcTemplate
  3. NamedParameterJdbcTemplate
  4. SimpleJdbcInsert
  5. SimpleJdbcCall

34. What are the ways by which Hibernate can be accessed using Spring?

There are two ways by which we can access Hibernate using Spring:

  1. Inversion of Control with a Hibernate Template and Callback
    Extending HibernateDAOSupport and Applying an AOP Interceptor node### 35. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:
**Programmatic transaction management: **In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.**Declarative transaction management: **In this, the transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.### 36. What are the different ORM’s supported by Spring?

Different ORM’s supported by Spring are depicted via the below diagram:

The next section of Spring interview questions discusses on Spring AOP Interview Questions.

Aspect Oriented Programming (AOP) – Spring Interview Questions

37. Describe AOP.

Aspect-oriented programming or AOP is a programming technique which allows programmers to modularize crosscutting concerns or behavior that cuts across the typical divisions of responsibility. Examples of cross-cutting concerns can be logging and transaction management. The core of AOP is an aspect. It encapsulates behaviors that can affect multiple classes into reusable modules.

38. What do you mean by Aspect?

Aspect is a modularization of concern which cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. Aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation in Spring Framework.

39. Explain JoinPoint.

A point during the execution of a program is called JoinPoint, such as the execution of a method or the handling of an exception. In Spring AOP, a joinpoint always represents a method execution.

40. What is an Advice?

An Action taken by an aspect at a particular joinpoint is known as an Advice. Spring AOP uses an advice as an interceptor, maintaining a chain of interceptors “around” the join point.

41. What are the different types of Advices?

Different types of Advices in Spring AOP are:
Before: These types of advices execute before the joinpoint methods and are configured using **@Before **annotation mark.**After returning: **These types of advices execute after the joinpoint methods completes executing normally and are configured using @AfterReturning annotation mark.**After throwing: ** These types of advices execute only if joinpoint method exits by throwing an exception and are configured using @AfterThrowing annotation mark.**After (finally): **These types of advices execute after a joinpoint method, regardless of the method’s exit whether normally or exceptional return and are configured using @After annotation mark.**Around: **These types of advices execute before and after a joinpoint and are configured using @Around annotation mark.### 42. Point out the difference between concern and cross-cutting concern in Spring AOP?

The concern is the behavior we want to have in a particular module of an application. It can be defined as a functionality we want to implement.

The cross-cutting concern is a concern which is applicable throughout the application. This affects the entire application. For example, logging, security and data transfer are the concerns needed in almost every module of an application, thus they are the cross-cutting concerns.

43. What are the different AOP implementations?

Different AOP implementations are depicted by the below diagram:

44. What are the difference between Spring AOP and AspectJ AOP?

Spring AOP vs AspectJ AOP

45. What do you mean by Proxy in Spring Framework?

An object which is created after applying advice to a target object is known as a Proxy. In case of client objects the target object and the proxy object are the same.

46. In Spring, what is Weaving?

The process of linking an aspect with other application types or objects to create an advised object is called Weaving. In Spring AOP, weaving is performed at runtime. Refer the below diagram:

The last section of Spring interview questions is on Spring MVC Interview Questions.

MVC (Model-View-Controller) – Spring Interview Questions

47. What do you mean by Spring MVC framework?

The Spring web MVC framework provides model-view-controller architecture and ready to use components that are used to develop flexible and loosely coupled web applications. The MVC pattern helps in separating the different aspects of the application like input logic, business logic and UI logic, while providing a loose coupling between all these elements.

48. Describe DispatcherServlet.

The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.

49. Explain WebApplicationContext.

The WebApplicationContext is an extension of the plain ApplicationContext. It has some extra features that are necessary for web applications. It differs from a normal ApplicationContext in terms of its capability of resolving themes and in deciding which servlet it is associated with.

50. In Spring MVC framework, what is controller?

Controllers provide access to the application behavior. These behaviors are generally defined through a service interface. Controllers interpret the user input and transform it into a model which is represented to the user by the view. In Spring, controller is implemented in a very abstract way. It also enables you to create a wide variety of controllers.

I hope this set of Spring Interview Questions and Answers will help you in preparing for your interviews. All the best!

Top 100 Python Interview Questions and Answers

Top 100 Python Interview Questions and Answers

In this article, we brought 100 essential Python interview questions to acquaint you with the skills and knowledge required to succeed in a job interview.

In this article, we brought 100 essential Python interview questions to acquaint you with the skills and knowledge required to succeed in a job interview.

Our team which includes experienced Python programmers have made a careful selection of the questions to keep a balance between theory and practical knowledge. So, you can get the full advantage.

Not only the job aspirants but also the recruiters can refer this post to know the right set of questions to evaluate a candidate. Let’s now step-in to explore the Python Q&A section.

100 Essential Python Interview Questions

Let’s begin answering the fundamental-level Python interview questions.

Q-1: What is Python, what are the benefits of using it, and what do you understand of PEP 8?

Python is one of the most successful interpreted languages. When you write a Python script, it doesn’t need to get compiled before execution. Few other interpreted languages are PHP and Javascript.

Benefits of Python Programming

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

PEP 8.

PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.

Q-2: What is the output of the following Python code fragment? Justify your answer.

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

The result of the above Python code snippet is:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

You may erroneously expect list1 to be equal to [10] and list3 to match with [‘a’], thinking that the list argument will initialize to its default value of [] every time there is a call to the extendList.

However, the flow is like that a new list gets created once after the function is defined. And the same get used whenever someone calls the extendList method without a list argument. It works like this because the calculation of expressions (in default arguments) occurs at the time of function definition, not during its invocation.

The list1 and list3 are hence operating on the same default list, whereas list2 is running on a separate object that it has created on its own (by passing an empty list as the value of the list parameter).

The definition of the extendList function can get changed in the following manner.

def extendList(val, list=None):
  if list is None:
    list = []
  list.append(val)
  return list

With this revised implementation, the output would be:

list1 = [10]
list2 = [123]
list3 = ['a']

Q-3: What is the statement that can be used in Python if the program requires no action but requires it syntactically?

The pass statement is a null operation. Nothing happens when it executes. You should use “pass” keyword in lowercase. If you write “Pass,” you’ll face an error like “NameError: name Pass is not defined.” Python statements are case sensitive.

letter = "hai sethuraman"
for i in letter:
    if i == "a":
        pass
        print("pass statement is execute ..............")
    else:
        print(i)

Q-4: What’s the process to get the home directory using ‘~’ in Python?

You need to import the os module, and then just a single line would do the rest.

import os
print (os.path.expanduser('~'))

Output:

/home/runner

Q-5: What are the built-in types available in Python?

Here is the list of most commonly used built-in types that Python supports:

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-6: How to find bugs or perform static analysis in a Python application?

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-7: When is the Python decorator used?

Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.

Q-8: What is the principal difference between a list and the tuple?

List vs. Tuple.

The principal difference between a list and the tuple is that the former is mutable while the tuple is not.

A tuple is allowed to be hashed, for example, using it as a key for dictionaries.

Q-9: How does Python handle memory management?

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-10: What are the principal differences between the lambda and def?

Lambda vs. def.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-11: Write a reg expression that confirms an email id using the python reg expression module “re”?

Python has a regular expression module “re.”

Check out the “re” expression that can check the email id for .com and .co.in subdomain.

import re
print(re.search(r"[0-9a-zA-Z.][email protected][a-zA-Z]+\.(com|co\.in)$","[email protected]"))

Q-12: What do you think is the output of the following code fragment? Is there any error in the code?

list = ['a', 'b', 'c', 'd', 'e']
print (list[10:])

The result of the above lines of code is []. There won’t be any error like an IndexError.

You should know that trying to fetch a member from the list using an index that exceeds the member count (for example, attempting to access list[10] as given in the question) would yield an IndexError. By the way, retrieving only a slice at the starting index that surpasses the no. of items in the list won’t result in an IndexError. It will just return an empty list.

Q-13: Is there a switch or case statement in Python? If not then what is the reason for the same?

No, Python does not have a Switch statement, but you can write a Switch function and then use it.

Q-14: What is a built-in function that Python uses to iterate over a number sequence?

Range() generates a list of numbers, which is used to iterate over for loops.

for i in range(5):
    print(i)

The range() function accompanies two sets of parameters.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-15: 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.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-16: What is a string in Python?

A string in Python is a sequence of alpha-numeric 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.

Q-17: 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 stores 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 which 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).

Q-18: 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.

Q-19: Is a string immutable or mutable in Python?

Python strings are indeed immutable.

Let’s take an example. We have an “str” variable holding a string value. We can’t mutate the container, i.e., the string, but can modify what it contains that means the value of the variable.

Q-20: What is the index in Python?

An index is an integer data type which 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

Q-21: What is Docstring in Python?

A docstring is a unique text that happens to be the first statement in the following Python constructs:

Module, Function, Class, or Method definition.

A docstring gets added to the doc attribute of the string object.

Now, read some of the Python interview questions on functions.

Q-22: What is a function in Python programming?

A function is an object which represents a block of code and is a reusable entity. It brings modularity to a program and a higher degree of code reusability.

Python has given us many built-in functions such as print() and provides the ability to create user-defined functions.

Q-23: How many basic types of functions are available in Python?

Python gives us two basic types of functions.

  1. Built-in, and

  2. User-defined.

The built-in functions happen to be part of the Python language. Some of these are print(), dir(), len(), and abs() etc.

Q-24: How do we write a function in Python?

We can create a Python function in the following manner.

Step-1: to begin the function, start writing with the keyword def and then mention the function name.

Step-2: We can now pass the arguments and enclose them using the parentheses. A colon, in the end, marks the end of the function header.

Step-3: After pressing an enter, we can add the desired Python statements for execution.

Q-25: 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 fits in the same category.

Q-26: What is the return keyword used for in Python?

The purpose of a function is to receive the inputs and return some output.

The return is a Python statement which we can use in a function for sending a value back to its caller.

Q-27: What is “Call by Value” in Python?

In call-by-value, the argument 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.

Q-28: 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 in the code to avoid such uncertainty.

Q-29: What is the return value of the trunc() 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.

Q-30: Is it mandatory for a Python function to return a value?

It is not at all necessary for a function to return any value. However, if needed, we can use None as a return value.

Q-31: 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.

Q-32: What is the purpose of id() function in Python?

The id() is one of the built-in functions in Python.

Signature: id(object)

It accepts one parameter and returns a unique identifier associated with the input object.

Q-33: What does the *args do in Python?

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

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

Example of using the *args:

# Python code to demonstrate 
# *args for dynamic arguments 
def fn(*argList):  
    for argx in argList:  
        print (argx) 
    
fn('I', 'am', 'Learning', 'Python')

The output:

I
am
Learning
Python

Q-34: 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 which can be named or keyworded.

Example of using the **kwargs:

# 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, Kalley=22, Tom=32)

The output:

John's age is 25.
Kalley's age is 22.
Tom's age is 32.

Q-35: 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 starts it from the command line.

We can also override the Python default main() function using the Python if statement. Please see the below code.

print("Welcome")
print("__name__ contains: ", __name__)
def main():
    print("Testing the main function")
if __name__ == '__main__':
    main()

The output:

Welcome
__name__ contains:  __main__
Testing the main function

Q-36: 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 compares with the value “main.”

Q-37: What is the purpose of “end” in Python?

Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.

# Example: Print a  instead of the new line in the end.
print("Let's learn" , end = ' ')  
print("Python") 

# Printing a dot in the end.
print("Learn to code from techbeamers" , end = '.')  
print("com", end = ' ')

The output is:

Let's learn Python
Learn to code from techbeamers.com

Q-38: 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.

Q-39: What is the difference between pass and continue in Python?

The continue statement makes the loop to resume from the next iteration.

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

Q-40: What does the len() function do in Python?

In Python, the len() is a primary string function. It determines the length of an input string.

>>> some_string = 'techbeamers'
>>> len(some_string)
11

Q-41: What does the chr() function do in Python?

The chr() function got re-added in Python 3.2. In version 3.0, it got removed.

It returns the string denoting a character whose Unicode code point is an integer.

For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the string ‘Ҽ’.

Q-42: What does the ord() function do in Python?

The ord(char) in Python takes a string of size one and returns an integer denoting the Unicode code format of the character in case of a Unicode type object, or the value of the byte if the argument is of 8-bit string type.

>>> ord("z")
122

Q-43: What is Rstrip() in Python?

Python provides the rstrip() method which duplicates the string but leaves out the whitespace characters from the end.

The rstrip() escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded.

The signature of the rstrip() is:

str.rstrip([char sequence/pre>
#Example
test_str = 'Programming    '
# The trailing whitespaces are excluded
print(test_str.rstrip())

Q-44: What is whitespace in Python?

Whitespace represents the characters that we use for spacing and separation.

They possess an “empty” representation. In Python, it could be a tab or space.

Q-45: What is isalpha() in Python?

Python provides this built-in isalpha() function for the string handling purpose.

It returns True if all characters in the string are of alphabet type, else it returns False.

Q-46: How do you use the split() function in Python?

Python’s split() function works on strings to cut a large piece into smaller chunks, or sub-strings. We can specify a separator to start splitting, or it uses the space as one by default.

#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())

The output:

['pdf', 'csv', 'json']
['pdf', 'csv', 'json']

Q-47: What does the join method do in Python?

Python provides the join() method which works on strings, lists, and tuples. It combines them and returns a united value.

Q-48: 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
str = 'lEaRn pYtHoN'
print(str.title())

The output:

Learn Python

Now, check out some general purpose Python interview questions.

Q-49: What makes the CPython different from Python?

CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an interpreter loop used for translating the Python-ish code to C language.

Q-50: Which package is the fastest form of Python?

PyPy provides maximum compatibility while utilizing CPython implementation for improving its performance.

The tests confirmed that PyPy is nearly five times faster than the CPython. It currently supports Python 2.7.

Q-51: What is GIL in Python language?

Python supports GIL (the global interpreter lock) which is a mutex used to secure access to Python objects, synchronizing multiple threads from running the Python bytecodes at the same time.

Q-52: How is Python thread safe?

Python ensures safe access to threads. It uses the GIL mutex to set synchronization. If a thread loses the GIL lock at any time, then you have to make the code thread-safe.

For example, many of the Python operations execute as atomic such as calling the sort() method on a list.

Q-53: How does Python manage the memory?

Python implements a heap manager internally which holds all of its objects and data structures.

This heap manager does the allocation/de-allocation of heap space for objects.

Q-54: What is a tuple in Python?

A tuple is a collection type data structure in Python which is immutable.

They are similar to sequences, just like the lists. However, There are some differences between a tuple and list; the former doesn’t allow modifications whereas the list does.

Also, the tuples use parentheses for enclosing, but the lists have square brackets in their syntax.

Q-55: What is a dictionary in Python programming?

A dictionary is a data structure known as an associative array in Python which stores a collection of objects.

The collection is a set of keys having a single associated value. We can call it a hash, a map, or a hashmap as it gets called in other programming languages.

Q-56: What is the set object in Python?

Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics.

Q-57: What is the use of the dictionary in Python?

A dictionary has a group of objects (the keys) map to another group of objects (the values). A Python dictionary represents a mapping of unique Keys to Values.

They are mutable and hence will not change. The values associated with the keys can be of any Python types.

Q-58: Is Python list a linked list?

A Python list is a variable-length array which is different from C-style linked lists.

Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure.

Here are some Python interview questions on classes and objects.

Q-59: 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 the 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.

In Python, we generate classes and instances in the following way.

>>>class Human:  # Create the class
...     pass
>>>man = Human()  # Create the instance
>>>print(man)


Q-60: What are Attributes and Methods in a Python class?

A class is useless if it has not defined any functionality. We can do so by adding attributes. They work as containers for data and functions. We can add an attribute directly specifying inside the class body.

>>> class Human:
...     profession = "programmer" # specify the attribute 'profession' of the class
>>> man = Human()
>>> print(man.profession)
programmer

After we added the attributes, we can go on to define the functions. Generally, we call them methods. In the method signature, we always have to provide the first argument with a self-keyword.

>>> class Human:
    profession = "programmer"
    def set_profession(self, new_profession):
        self.profession = new_profession      
>>> man = Human()
>>> man.set_profession("Manager")
>>> print(man.profession)
Manager

Q-61: How to assign values for the Class attributes at runtime?

We can specify the values for the attributes at runtime. We need to add an init method and pass input to object constructor. See the following example demonstrating this.

>>> class Human:
    def __init__(self, profession):
        self.profession = profession
    def set_profession(self, new_profession):
        self.profession = new_profession

>>> man = Human("Manager")
>>> print(man.profession)
Manager

Q-62: What is Inheritance in Python programming?

Inheritance is an OOP mechanism which allows an object to access its parent class features. It carries forward the base class functionality to the child.

We do it intentionally to abstract away the similar code in different classes.

The common code rests with the base class, and the child class objects can access it via inheritance. Check out the below example.

class PC: # Base class
    processor = "Xeon" # Common attribute
    def set_processor(self, new_processor):
        processor = new_processor

class Desktop(PC): # Derived class
    os = "Mac OS High Sierra" # Personalized attribute
    ram = "32 GB"

class Laptop(PC): # Derived class
    os = "Windows 10 Pro 64" # Personalized attribute
    ram = "16 GB"

desk = Desktop()
print(desk.processor, desk.os, desk.ram)

lap = Laptop()
print(lap.processor, lap.os, lap.ram)

The output:

Xeon Mac OS High Sierra 32 GB
Xeon Windows 10 Pro 64 16 GB

Q-63: What is Composition in Python?

The composition is also a type of inheritance in Python. It intends to inherit from the base class but a little differently, i.e., by using an instance variable of the base class acting as a member of the derived class.

See the below diagram.

To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances.

class PC: # Base class
    processor = "Xeon" # Common attribute
    def __init__(self, processor, ram):
        self.processor = processor
        self.ram = ram

    def set_processor(self, new_processor):
        processor = new_processor

    def get_PC(self):
        return "%s cpu & %s ram" % (self.processor, self.ram)

class Tablet():
    make = "Intel"
    def __init__(self, processor, ram, make):
        self.PC = PC(processor, ram) # Composition
        self.make = make

    def get_Tablet(self):
        return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make)

if __name__ == "__main__":
    tab = Tablet("i7", "16 GB", "Intel")
    print(tab.get_Tablet())

The output is:

Tablet with i7 CPU & 16 GB ram by Intel

Q-64: What are Errors and Exceptions in Python programs?

Errors are coding issues in a program which may cause it to exit abnormally.

On the contrary, exceptions happen due to the occurrence of an external event which interrupts the normal flow of the program.

Q-65: How do you handle exceptions with Try/Except/Finally in Python?

Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions. We enclose the unsafe code indented under the try block. And we can keep our fall-back code inside the except block. Any instructions intended for execution last should come under the finally block.

try:
    print("Executing code in the try block")
    print(exception)
except:
    print("Entering in the except block")
finally:
    print("Reached to the final block")

The output is:

Executing code in the try block
Entering in the except block
Reached to the final block

Q-66: How do you raise exceptions for a predefined condition in Python?

We can raise an exception based on some condition.

For example, if we want the user to enter only odd numbers, else will raise an exception.

# Example - Raise an exception
while True:
    try:
        value = int(input("Enter an odd number- "))
        if value%2 == 0:
            raise ValueError("Exited due to invalid input!!!")
        else:
            print("Value entered is : %s" % value)
    except ValueError as ex:
        print(ex)
        break

The output is:

Enter an odd number- 2
Exited due to invalid input!!!
Enter an odd number- 1
Value entered is : 1
Enter an odd number-

Q-67: What are Python Iterators?

Iterators in Python are array-like objects which allow moving on the next element. We use them in traversing a loop, for example, in a “for” loop.

Python library has a no. of iterators. For example, a list is also an iterator and we can start a for loop over it.

Q-68: What is the difference between an Iterator and Iterable?

The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are also iterable containers which return an iterator while traversing.

Here are some advanced-level Python interview questions.

Q-69: What are Python Generators?

A Generator is a kind of function which lets us specify a function that acts like an iterator and hence can get used in a “for” loop.

In a generator function, the yield keyword substitutes the return statement.

# Simple Python function
def fn():
    return "Simple Python function."

# Python Generator function
def generate():
    yield "Python Generator function."

print(next(generate()))

The output is:

Python Generator function.

Q-70: What are Closures in Python?

Python closures are function objects returned by another function. We use them to eliminate code redundancy.

In the example below, we’ve written a simple closure for multiplying numbers.

def multiply_number(num):
    def product(number):
        'product() here is a closure'
        return num * number
    return product

num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))

num_6 = multiply_number(6)
print(num_6(1))

The output is:

22
48
6

Q-71: What are Decorators in Python?

Python decorator gives us the ability to add new behavior to the given objects dynamically. In the example below, we’ve written a simple example to display a message pre and post the execution of a function.

def decorator_sample(func):
    def decorator_hook(*args, **kwargs):
        print("Before the function call")
        result = func(*args, **kwargs)
        print("After the function call")
        return result
    return decorator_hook

@decorator_sample
def product(x, y):
    "Function to multiply two numbers."
    return x * y

print(product(3, 3))

The output is:

Before the function call
After the function call
9

Q-72: How do you create a dictionary in Python?

Let’s take the example of building site statistics. For this, we first need to break up the key-value pairs using a colon(“:”). The keys should be of an immutable type, i.e., so we’ll use the data-types which don’t allow changes at runtime. We’ll choose from an int, string, or tuple.

However, we can take values of any kind. For distinguishing the data pairs, we can use a comma(“,”) and keep the whole stuff inside curly braces({…}).

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> type(site_stats)

>>> print(site_stats)
{'type': 'organic', 'site': 'tecbeamers.com', 'traffic': 10000}

Q-73: How do you read from a dictionary in Python?

To fetch data from a dictionary, we can directly access using the keys. We can enclose a “key” using brackets […] after mentioning the variable name corresponding to the dictionary.

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats["traffic"])

We can even call the get method to fetch the values from a dict. It also let us set a default value. If the key is missing, then the KeyError would occur.

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.get('site'))
tecbeamers.com

Q-74: How do you traverse through a dictionary object in Python?

We can use the “for” and “in” loop for traversing the dictionary object.

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> for k, v in site_stats.items():
    print("The key is: %s" % k)
    print("The value is: %s" % v)
    print("++++++++++++++++++++++++")

The output is:

The key is: type
The value is: organic
++++++++++++++++++++++++
The key is: site
The value is: tecbeamers.com
++++++++++++++++++++++++
The key is: traffic
The value is: 10000
++++++++++++++++++++++++

Q-75: How do you add elements to a dictionary in Python?

We can add elements by modifying the dictionary with a fresh key and then set the value to it.

>>> # Setup a blank dictionary
>>> site_stats = {}
>>> site_stats['site'] = 'google.com'
>>> site_stats['traffic'] = 10000000000
>>> site_stats['type'] = 'Referral'
>>> print(site_stats)
{'type': 'Referral', 'site': 'google.com', 'traffic': 10000000000}

We can even join two dictionaries to get a bigger dictionary with the help of the update() method.

>>> site_stats['site'] = 'google.co.in'
>>> print(site_stats)
{'site': 'google.co.in'}
>>> site_stats_new = {'traffic': 1000000, "type": "social media"}
>>> site_stats.update(site_stats_new)
>>> print(site_stats)
{'type': 'social media', 'site': 'google.co.in', 'traffic': 1000000}

Q-76: How do you delete elements of a dictionary in Python?

We can delete a key in a dictionary by using the del() method.

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> del site_stats["type"]
>>> print(site_stats)
{'site': 'google.co.in', 'traffic': 1000000}

Another method, we can use is the pop() function. It accepts the key as the parameter. Also, a second parameter, we can pass a default value if the key doesn’t exist.

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.pop("type", None))
organic
>>> print(site_stats)
{'site': 'tecbeamers.com', 'traffic': 10000}

Q-77: How do you check the presence of a key in a dictionary?

We can use Python’s “in” operator to test the presence of a key inside a dict object.

>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> 'site' in site_stats
True
>>> 'traffic' in site_stats
True
>>> "type" in site_stats
True

Earlier, Python also provided the has_key() method which got deprecated.

Q-78: What is the syntax for List comprehension in Python?

The signature for the list comprehension is as follows:

[ expression(var) for var in iterable ]

For example, the below code will return all the numbers from 10 to 20 and store them in a list.

>>> alist = [var for var in range(10, 20)]
>>> print(alist)

Q-79: What is the syntax for Dictionary comprehension in Python?

A dictionary has the same syntax as was for the list comprehension but the difference is that it uses curly braces:

{ aKey, itsValue for aKey in iterable }

For example, the below code will return all the numbers 10 to 20 as the keys and will store the respective squares of those numbers as the values.

>>> adict = {var:var**2 for var in range(10, 20)}
>>> print(adict)

Q-80: What is the syntax for Generator expression in Python?

The syntax for generator expression matches with the list comprehension, but the difference is that it uses parenthesis:

( expression(var) for var in iterable )

For example, the below code will create a generator object that generates the values from 10 to 20 upon using it.

>>> (var for var in range(10, 20))
 at 0x0000000003668728>
>>> list((var for var in range(10, 20)))

Now, see more Python interview questions for practice.

Q-81: How do you write a conditional expression in Python?

We can utilize the following single statement as a conditional expression. default_statment if Condition else another_statement

>>> no_of_days = 366
>>> is_leap_year = "Yes" if no_of_days == 366 else "No"
>>> print(is_leap_year)
Yes

Q-82: What do you know about the Python enumerate?

While using the iterators, sometimes we might have a use case to store the count of iterations. Python gets this task quite easy for us by giving a built-in method known as the enumerate().

The enumerate() function attaches a counter variable to an iterable and returns it as the “enumerated” object.

We can use this object directly in the “for” loops or transform it into a list of tuples by calling the list() method. It has the following signature:

enumerate(iterable, to_begin=0)
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its default value is 0
# Example - enumerate function 
alist = ["apple","mango", "orange"] 
astr = "banana"
  
# Let's set the enumerate objects 
list_obj = enumerate(alist) 
str_obj = enumerate(astr) 
  
print("list_obj type:", type(list_obj))
print("str_obj type:", type(str_obj))

print(list(enumerate(alist)) )  
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))

The output is:

list_obj type: 
str_obj type: 
[(0, 'apple'), (1, 'mango'), (2, 'orange')]
[(2, 'b'), (3, 'a'), (4, 'n'), (5, 'a'), (6, 'n'), (7, 'a')]

Q-83: What is the use of globals() function in Python?

The globals() function in Python returns the current global symbol table as a dictionary object.

Python maintains a symbol table to keep all necessary information about a program. This info includes the names of variables, methods, and classes used by the program.

All the information in this table remains in the global scope of the program and Python allows us to retrieve it using the globals() method.

Signature: globals()

Arguments: None
# Example: globals() function 
x = 9
def fn(): 
    y = 3
    z = y + x
    # Calling the globals() method
    z = globals()['x'] = z
    return z
       
# Test Code     
ret = fn() 
print(ret)

The output is:

12

Q-84: Why do you use the zip() method in Python?

The zip method lets us map the corresponding index of multiple containers so that we can use them using as a single unit.

Signature: 
 zip(*iterators)
Arguments: 
 Python iterables or collections (e.g., list, string, etc.)
Returns: 
 A single iterator object with combined mapped values
# Example: zip() function
  
emp = [ "tom", "john", "jerry", "jake" ] 
age = [ 32, 28, 33, 44 ] 
dept = [ 'HR', 'Accounts', 'R&D', 'IT' ] 
  
# call zip() to map values 
out = zip(emp, age, dept)
  
# convert all values for printing them as set 
out = set(out) 
  
# Displaying the final values  
print ("The output of zip() is : ",end="") 
print (out)

The output is:

The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28, 'Accounts'), ('tom', 32, 'HR')}

Q-85: What are Class or Static Variables in Python programming?

In Python, all the objects share common class or static variables.

But the instance or non-static variables are altogether different for different objects.

The programming languages like C++ and Java need to use the static keyword to make a variable as the class variable. However, Python has a unique way to declare a static variable.

All names initialized with a value in the class declaration becomes the class variables. And those which get assigned values in the class methods becomes the instance variables.

# Example 
class Test: 
    aclass = 'programming' # A class variable 
    def __init__(self, ainst): 
        self.ainst = ainst # An instance variable 
  
# Objects of CSStudent class 
test1 = Test(1) 
test2 = Test(2) 
  
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
print(test2.ainst)

# A class variable is also accessible using the class name
print(Test.aclass)

The output is:

programming
programming
1
2
programming

Let’s now answer some advanced-level Python interview questions.

Q-86: How does the ternary operator work in Python?

The ternary operator is an alternative for the conditional statements. It combines true or false values with a statement that you need to test.

The syntax would look like the one given below.

[onTrue] if [Condition] else [onFalse]

x, y = 35, 75
smaller = x if x < y else y
print(smaller)

Q-87: What does the “self” keyword do?

The self is a Python keyword which represents a variable that holds the instance of an object.

In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.

Q-88: What are the different methods to copy an object in Python?

There are two ways to copy objects in Python.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-89: What is the purpose of docstrings in Python?

In Python, the docstring is what we call as the docstrings. It sets a process of recording Python functions, modules, and classes.

Q-90: Which Python function will you use to convert a number to a string?

For converting a number into a string, you can use the built-in function str(). If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex().

Q-91: How do you debug a program in Python? Is it possible to step through the Python code?

Yes, we can use the Python debugger (pdb) to debug any Python program. And if we start a program using pdb, then it let us even step through the code.

Q-92: List down some of the PDB commands for debugging Python programs?

Here are a few PDB commands to start debugging Python code.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-93: What is the command to debug a Python program?

The following command helps run a Python program in debug mode.

$ python -m pdb python-script.py

Q-94: How do you monitor the code flow of a program in Python?

In Python, we can use the sys module’s settrace() method to setup trace hooks and monitor the functions inside a program.

You need to define a trace callback method and pass it to the settrace() function. The callback should specify three arguments as shown below.

import sys

def trace_calls(frame, event, arg):
    # The 'call' event occurs before a function gets executed.
    if event != 'call':
        return
    # Next, inspect the frame data and print information.
    print 'Function name=%s, line num=%s' % (frame.f_code.co_name, frame.f_lineno)
    return

def demo2():
    print 'in demo2()'

def demo1():
    print 'in demo1()'
    demo2()

sys.settrace(trace_calls)
demo1()

Q-95: Why and when do you use generators in Python?

A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the yield keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.

Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-96: 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.

See the example below.

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

Q-97: How to convert a list into other data types?

Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.

Turn a list into a string.

We can use the ”.join() method which combines all elements into one and returns as a string.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)

#output: sun mon tue wed thu fri sat

Turn a list into a tuple.

Call Python’s tuple() function for converting a list into a tuple.

This function takes the list as its argument.

But remember, we can’t change the list after turning it into a tuple because it becomes immutable.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)

#output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')

Turn a list into a set.

Converting a list to a set poses two side-effects.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

However, we can use the set() function to convert a list into a Set.

weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)

#output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])

Turn a list into a dictionary.

In a dictionary, each item represents a key-value pair. So converting a list isn’t as straightforward as it were for other data types.

However, we can achieve the conversion by breaking the list into a set of pairs and then call the zip() function to return them as tuples.

Passing the tuples into the dict() function would finally turn them into a dictionary.

weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)

#output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}

Q-98: How do you count the occurrences of each item present in the list without explicitly mentioning them?

Unlike sets, lists can have items with the same values.

In Python, the list has a count() function which returns the occurrences of a particular item.

Count the occurrences of an individual item.

weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))

#output: 3

Count the occurrences of each item in the list.

We’ll use the list comprehension along with the count() method. It’ll print the frequency of each of the items.

weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print([[x,weekdays.count(x)] for x in set(weekdays)])

#output: [['wed', 1], ['sun', 2], ['thu', 1], ['tue', 1], ['mon', 3], ['fri', 1]]

Q-99: 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.

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

Q-100: What are different ways to create an empty NumPy array in Python?

There are two methods which we can apply to create empty NumPy arrays.

The first method to create an empty array.

import numpy
numpy.array([])

The second method to create an empty array.

# Make an empty NumPy array
numpy.empty(shape=(0,0))

Summary – Essential Python Interview Questions

Please note that it is our commitment to bring fresh and useful content for the readers. And we are hopeful that all of you would have liked the latest set of Python interview questions.

However, if you want us to take upon a new subject, then please do let us know. We’ll certainly add it to our roadmap.

Next, we are keen to hear your feedback about the post and its content. Please steer your fingers to hit the comment box and give your genuine feedback. It’ll inspire us to write better and produce first-class content.

Thanks for reading ❤