Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOPs Short Questions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

OOPs short Questions

Top 50 OOPs Interview Questions & Answers


1. What is OOPS?

OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a
collection of objects. Each object is nothing but an instance of a class.

2. Write basic concepts of OOPS?

Following are the concepts of OOPS and are as follows:

1. Abstraction.
2. Encapsulation.
3. Inheritance.
4. Polymorphism.
3. What is a class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describes
the details of an object.

4. What is an object?

An object is an instance of a class. It has its own state, behavior, and identity.

5. What is Encapsulation?

Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data
can be restricted to the members of that class.

Levels are Public, Protected, Private, Internal and Protected Internal.

6. What is Polymorphism?

Polymorphism is nothing but assigning behavior or value in a subclass to something that was already
declared in the main class. Simply, polymorphism takes more than one form.

7. What is Inheritance?

Inheritance is a concept where one class shares the structure and behavior defined in another class. If
inheritance applied on one class is called Single Inheritance, and if it depends on multiple classes,
then it is called multiple Inheritance.

8. What are manipulators?

Manipulators are the functions which can be used in conjunction with the insertion (<<) and
extraction (>>) operators on an object. Examples are endl and setw.

9. Define a constructor?
A constructor is a method used to initialize the state of an object, and it gets invoked at the time of
object creation. Rules forconstructor are:

 Constructor Name should be same as class name.


 A constructor must have no return type.
10. Define Destructor?

A destructor is a method which is automatically called when the object is made of scope or
destroyed. Destructor name is also same as class name but with the tilde symbol before the name.

11. What is an Inline function?

An inline function is a technique used by the compilers and instructs to insert complete body of the
function wherever that function is used in the program source code.

12. What is a virtual function?

A virtual function is a member function of a class, and its functionality can be overridden in its
derived class. This function can be implemented by using a keyword called virtual, and it can be
given during function declaration.

A virtual function can A token in C++, and it can be achieved in C Language by using function
pointers or pointers to function.

13. What is a friend function?

A friend function is a friend of a class that is allowed to access to Public, private or protected data in
that same class. If the function is defined outside the class cannot access such information.

Friend can be declared anywhere in the class declaration, and it cannot be affected by access control
keywords like private, public or protected.

14. What is function overloading?

Function overloading an as a normal function, but it can perform different tasks. It allows the
creation of several methods with the same name which differ from each other by the type of input
and output of the function.

Example
void add(int& a, int& b);
void add(double& a, double& b);
void add(struct bob& a, struct bob& b);
15. What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the
arguments. Operator,-,* can be used to pass through the function, and it has their own precedence to
execute

16. What is an abstract class?


An abstract class is a class which cannot be instantiated. Creation of an object is not possible with an
abstract class, but it can be inherited. An abstract class can contain only Abstract method. Java allows
only abstract method in abstract class while for other languages allow non-abstract method as well.

17. What is a ternary operator?

The ternary operator is said to be an operator which takes three arguments. Arguments and results are
of different data types, and it depends on the function. The ternary operator is also called a
conditional operator.

18. What is the use of finalize method?

Finalize method helps to perform cleanup operations on the resources which are not currently used.
Finalize method is protected, and it is accessible only through this class or by a derived class.

19. What are different types of arguments?

A parameter is a variable used during the declaration of the function or subroutine and arguments are
passed to the an, and it should match with the parameter defined. There are two types of Arguments.

 Call by Value – Value passed will get modified only inside the function, and it returns the
same value whatever it is passed it into the function.
 Call by Reference – Value passed will get modified in both inside and outside the functions
and it returns the same or different value.

20. What is the super keyword?

Super keyword is used to invoke the overridden method which overrides one of its superclass
methods. This keyword allows to access overridden methods and also to access hidden members of
the superclass.

It also forwards a call from a constructor to a constructor in the superclass.

21. What is method overriding?

Method overriding is a feature that allows a subclass to provide the implementation of a method that
overrides in the main class. This will overrides the implementation in the superclass by providing the
same method name, same parameter and same return type.

22. What is an interface?

An interface is a collection of an abstract method. If the class implements an inheritance, and then
thereby inherits all the abstract methods of an interface.

23. What is exception handling?

An exception is an event that occurs during the execution of a program. Exceptions can be of any
type – Runtime exception, Error exceptions. Those exceptions are adequately handled through
exception handling mechanism like try, catch and throw keywords.

24. What are tokens?


The token is recognized by a compiler, and it cannot be broken down into component elements.
Keywords, identifiers, constants, string literals and operators are examples of tokens.

Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and
Parentheses.

25. Difference between overloading and overriding?

Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the
same method with different arguments, and it may or may not return the same value in the same class
itself.

Overriding is the same method names with same arguments and return types associated with the class
and its child class.

26. Difference between class and an object?

An object is an instance of a class. Objects hold multiple information, but classes don’t have any
information. Definition of properties and functions can be done in class and can be used by the
object.

A class can have sub-classes, and an object doesn’t have sub-objects.

27. What is an abstraction?

Abstraction is a good feature of OOPS, and it shows only the necessary details to the client of an
object. Means, it shows only required details for an object, not the inner constructors, of an object.
Example – When you want to switch On television, it not necessary to show all the functions of TV.
Whatever is required to switch on TV will be showed by using abstract class.

28. What are access modifiers?

Access modifiers determine the scope of the method or variables that can be accessed from other
various objects or classes. There are 5 types of access modifiers, and they are as follows:

 Private.
 Protected.
 Public.
 Friend.
 Protected Friend.
29. What are sealed modifiers?

Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed
modifiers can also be applied to properties, events, and methods. This modifier cannot be applied to
static members.

30. How can we call the base method without creating an instance?

Yes, it is possible to call the base method without creating an instance. And that method should be
“Static method”.
Doing inheritance from that class.-Use Base Keyword from a derived class.

31. What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base class
function. Whereas, Override modifier helps to override the base class function.

32. What are the various types of constructors?

There are three various types of constructors, and they are as follows:

– Default Constructor – With no parameters.

– Parametric Constructor – With Parameters. Create a new instance of a class and also passing
arguments simultaneously.

– Copy Constructor – Which creates a new object as a copy of an existing object.

33. What is early and late binding?

Early binding refers to the assignment of values to variables during design time whereas late binding
refers to the assignment of values to variables during run time.

34. What is ‘this’ pointer?

THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which
differentiates between the current object with the global object. Basically, it refers to the current
object.

35. What is the difference between structure and a class?

Structure default access type is public , but class access type is private. A structure is used for
grouping data whereas class can be used for grouping data and methods. Structures are exclusively
used for data, and it doesn’t require strict validation , but classes are used to encapsulates and inherit
data which requires strict validation.

36. What is the default access modifier in a class?

The default access modifier of a class is Private by default.

37. What is a pure virtual function?

A pure virtual function is a function which can be overridden in the derived class but cannot be
defined. A virtual function can be declared as Pure by using the operator =0.

Example -.

C#
1 Virtual void function1() // Virtual, Not pure
2
3 Virtual void function2() = 0 //Pure virtual

38. What are all the operators that cannot be overloaded?

Following are the operators that cannot be overloaded -.

1. Scope Resolution (:: )


2. Member Selection (.)
3. Member selection through a pointer to function (.*)

39. What is dynamic or run time polymorphism?

Dynamic or Run time polymorphism is also known as method overriding in which call to an
overridden function is resolved during run time, not at the compile time. It means having two or more
methods with the same name, same signature but with different implementation.

40. Do we require a parameter for constructors?

No, we do not require a parameter for constructors.

41. What is a copy constructor?

This is a special constructor for creating a new object as a copy of an existing object. There will
always be only one copy constructor that can be either defined by the user or the system.

42. What does the keyword virtual represented in the method definition?

It means, we can override the method.

43. Whether static method can use nonstatic members?

False.

44. What is a base class, sub class, and super class?

The base class is the most generalized class, and it is said to be a root class.

A Sub class is a class that inherits from one or more base classes.

The superclass is the parent class from which another class inherits.

45. What is static and dynamic binding?

Binding is nothing but the association of a name with the class. Static binding is a binding in which
name can be associated with the class during compilation time, and it is also called as early Binding.

Dynamic binding is a binding in which name can be associated with the class during execution time,
and it is also called as Late Binding.
46. How many instances can be created for an abstract class?

Zero instances will be created for an abstract class.

47. Which keyword can be used for overloading?

Operator keyword is used for overloading.

48. What is the default access specifier in a class definition?

Private access specifier is used in a class definition.

49. Which OOPS concept is used as reuse mechanism?

Inheritance is the OOPS concept that can be used as reuse mechanism.

50. Which OOPS concept exposes only necessary information to the calling functions?

Encapsulation
What Is Object-Oriented Programming (OOP)?
Object-oriented Programming, or OOP for short, is a programming paradigm which provides a
means of structuring programs so that properties and behaviors are bundled into
individual objects.

For instance, an object could represent a person with a name property, age, address, etc., with
behaviors like walking, talking, breathing, and running. Or an email with properties like recipient
list, subject, body, etc., and behaviors like adding attachments and sending.

Put another way, object-oriented programming is an approach for modeling concrete, real-world
things like cars as well as relations between things like companies and employees, students and
teachers, etc. OOP models real-world entities as software objects, which have some data
associated with them and can perform certain functions.

Another common programming paradigm is procedural programming which structures a


program like a recipe in that it provides a set of steps, in the form of functions and code blocks,
which flow sequentially in order to complete a task.

The key takeaway is that objects are at the center of the object-oriented programming paradigm,
not only representing the data, as in procedural programming, but in the overall structure of the
program as well.

NOTE: Since Python is a multi-paradigm programming language, you can choose the paradigm
that best suits the problem at hand, mix different paradigms in one program, and/or switch from
one paradigm to another as your program evolves.
Classes in Python
Focusing first on the data, each thing or object is an instance of some class.

The primitive data structures available in Python, like numbers, strings, and lists are designed to
represent simple things like the cost of something, the name of a poem, and your favorite colors,
respectively.

What if you wanted to represent something much more complicated?

For example, let’s say you wanted to track a number of different animals. If you used a list, the
first element could be the animal’s name while the second element could represent its age.

How would you know which element is supposed to be which? What if you had 100 different
animals? Are you certain each animal has both a name and an age, and so forth? What if you
wanted to add other properties to these animals? This lacks organization, and it’s the exact need
for classes.

Classes are used to create new user-defined data structures that contain arbitrary information
about something. In the case of an animal, we could create an Animal() class to track properties
about the Animal like the name and age.
It’s important to note that a class just provides structure—it’s a blueprint for how something
should be defined, but it doesn’t actually provide any real content itself. The Animal() class may
specify that the name and age are necessary for defining an animal, but it will not actually state
what a specific animal’s name or age is.

It may help to think of a class as an idea for how something should be defined.

Python Objects (Instances)


While the class is the blueprint, an instance is a copy of the class with actual values, literally an
object belonging to a specific class. It’s not an idea anymore; it’s an actual animal, like a dog
named Roger who’s eight years old.

Put another way, a class is like a form or questionnaire. It defines the needed information. After
you fill out the form, your specific copy is an instance of the class; it contains actual information
relevant to you.

You can fill out multiple copies to create many different instances, but without the form as a
guide, you would be lost, not knowing what information is required. Thus, before you can create
individual instances of an object, we must first specify what is needed by defining a class.

How To Define a Class in Python


Defining a class is simple in Python:

class Dog:
pass
You start with the class keyword to indicate that you are creating a class, then you add the name
of the class (using CamelCase notation, starting with a capital letter.)

Also, we used the Python keyword pass here. This is very often used as a place holder where
code will eventually go. It allows us to run this code without throwing an error.

Note: The above code is correct on Python 3. On Python 2.x (“legacy Python”) you’d use a
slightly different class definition:

# Python 2.x Class Definition:


class Dog(object):
pass
The (object) part in parentheses specifies the parent class that you are inheriting from (more on
this below.) In Python 3 this is no longer necessary because it is the implicit default.
Instance Attributes
All classes create objects, and all objects contain characteristics called attributes (referred to as
properties in the opening paragraph). Use the __init__() method to initialize (e.g., specify) an
object’s initial attributes by giving them their default value (or state). This method must have at
least one argument as well as the self variable, which refers to the object itself (e.g., Dog).
class Dog:

# Initializer / Instance Attributes


def __init__(self, name, age):
self.name = name
self.age = age
In the case of our Dog() class, each dog has a specific name and age, which is obviously
important to know for when you start actually creating different dogs. Remember: the class is
just for defining the Dog, not actually creating instances of individual dogs with specific names
and ages; we’ll get to that shortly.

Similarly, the self variable is also an instance of the class. Since instances of a class have varying
values we could state Dog.name = name rather than self.name = name. But since not all dogs
share the same name, we need to be able to assign different values to different instances. Hence
the need for the special self variable, which will help to keep track of individual instances of
each class.

NOTE: You will never have to call the __init__() method; it gets called automatically when you
create a new ‘Dog’ instance.
Class Attributes
While instance attributes are specific to each object, class attributes are the same for all
instances—which in this case is all dogs.

class Dog:

# Class Attribute
species = 'mammal'

# Initializer / Instance Attributes


def __init__(self, name, age):
self.name = name
self.age = age
So while each dog has a unique name and age, every dog will be a mammal.

Let’s create some dogs…

Instantiating Objects
Instantiating is a fancy term for creating a new, unique instance of a class.

For example:
>>>

>>> class Dog:


... pass
...
>>> Dog()
<__main__.Dog object at 0x1004ccc50>
>>> Dog()
<__main__.Dog object at 0x1004ccc90>
>>> a = Dog()
>>> b = Dog()
>>> a == b
False
We started by defining a new Dog() class, then created two new dogs, each assigned to different
objects. So, to create an instance of a class, you use the the class name, followed by parentheses.
Then to demonstrate that each instance is actually different, we instantiated two more dogs,
assigning each to a variable, then tested if those variables are equal.

What do you think the type of a class instance is?

>>>

>>> class Dog:


... pass
...
>>> a = Dog()
>>> type(a)
<class '__main__.Dog'>
Let’s look at a slightly more complex example…

class Dog:

# Class Attribute
species = 'mammal'

# Initializer / Instance Attributes


def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the Dog object
philo = Dog("Philo", 5)
mikey = Dog("Mikey", 6)

# Access the instance attributes


print("{} is {} and {} is {}.".format(
philo.name, philo.age, mikey.name, mikey.age))

# Is Philo a mammal?
if philo.species == "mammal":
print("{0} is a {1}!".format(philo.name, philo.species))
NOTE: Notice how we use dot notation to access attributes from each object.
Save this as dog_class.py, then run the program. You should see:

Philo is 5 and Mikey is 6.


Philo is a mammal!
What’s Going On?
We created a new instance of the Dog() class and assigned it to the variable philo. We then
passed it two arguments, "Philo" and 5, which represent that dog’s name and age, respectively.

These attributes are passed to the __init__ method, which gets called any time you create a new
instance, attaching the name and age to the object. You might be wondering why we didn’t have
to pass in the self argument.

This is Python magic; when you create a new instance of the class, Python automatically
determines what self is (a Dog in this case) and passes it to the __init__ method.

Review Exercises (#1)

Exercise: "The Oldest Dog"Show/Hide

Solution: "The Oldest Dog"Show/Hide

Instance Methods
Instance methods are defined inside a class and are used to get the contents of an instance. They
can also be used to perform operations with the attributes of our objects. Like
the __init__ method, the first argument is always self:

class Dog:
# Class Attribute
species = 'mammal'

# Initializer / Instance Attributes


def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)

# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)

# Instantiate the Dog object


mikey = Dog("Mikey", 6)

# call our instance methods


print(mikey.description())
print(mikey.speak("Gruff Gruff"))
Save this as dog_instance_methods.py, then run it:

Mikey is 6 years old


Mikey says Gruff Gruff
In the latter method, speak(), we are defining behavior. What other behaviors could you assign to
a dog? Look back to the beginning paragraph to see some example behaviors for other objects.

Modifying Attributes
You can change the value of attributes based on some behavior:

>>>

>>> class Email:


... def __init__(self):
... self.is_sent = False
... def send_email(self):
... self.is_sent = True
...
>>> my_email = Email()
>>> my_email.is_sent
False
>>> my_email.send_email()
>>> my_email.is_sent
True
Here, we added a method to send an email, which updates the is_sent variable to True.

Python Object Inheritance


Inheritance is the process by which one class takes on the attributes and methods of another.
Newly formed classes are called child classes, and the classes that child classes are derived from
are called parent classes.

It’s important to note that child classes override or extend the functionality (e.g., attributes and
behaviors) of parent classes. In other words, child classes inherit all of the parent’s attributes and
behaviors but can also specify different behavior to follow. The most basic type of class is
an object, which generally all other classes inherit as their parent.

When you define a new class, Python 3 it implicitly uses object as the parent class. So the
following two definitions are equivalent:

class Dog(object):
pass

# In Python 3, this is the same as:

class Dog:
pass
Note: In Python 2.x there’s a distinction between new-style and old-style classes. I won’t go into
detail here, but you’ll generally want to specify object as the parent class to ensure you’re
definint a new-style class if you’re writing Python 2 OOP code.
Dog Park Example
Let’s pretend that we’re at a dog park. There are multiple Dog objects engaging in Dog
behaviors, each with different attributes. In regular-speak that means some dogs are running,
while some are stretching and some are just watching other dogs. Furthermore, each dog has
been named by its owner and, since each dog is living and breathing, each ages.

What’s another way to differentiate one dog from another? How about the dog’s breed:
>>>

>>> class Dog:


... def __init__(self, breed):
... self.breed = breed
...
>>> spencer = Dog("German Shepard")
>>> spencer.breed
'German Shepard'
>>> sara = Dog("Boston Terrier")
>>> sara.breed
'Boston Terrier'
Each breed of dog has slightly different behaviors. To take these into account, let’s create
separate classes for each breed. These are child classes of the parent Dog class.

Extending the Functionality of a Parent Class


Create a new file called dog_inheritance.py:

# Parent class
class Dog:

# Class attribute
species = 'mammal'

# Initializer / Instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)

# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
# Child class (inherits from Dog class)
class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)

# Child class (inherits from Dog class)


class Bulldog(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)

# Child classes inherit attributes and


# behaviors from the parent class
jim = Bulldog("Jim", 12)
print(jim.description())

# Child classes have specific attributes


# and behaviors as well
print(jim.run("slowly"))
Read the comments aloud as you work through this program to help you understand what’s
happening, then before you run the program, see if you can predict the expected output.

You should see:

Jim is 12 years old


Jim runs slowly
We haven’t added any special attributes or methods to differentiate a RussellTerrier from
a Bulldog, but since they’re now two different classes, we could for instance give them different
class attributes defining their respective speeds.

Parent vs. Child Classes


The isinstance() function is used to determine if an instance is also an instance of a certain parent
class.

Save this as dog_isinstance.py:

# Parent class
class Dog:
# Class attribute
species = 'mammal'

# Initializer / Instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)

# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)

# Child class (inherits from Dog() class)


class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)

# Child class (inherits from Dog() class)


class Bulldog(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)

# Child classes inherit attributes and


# behaviors from the parent class
jim = Bulldog("Jim", 12)
print(jim.description())

# Child classes have specific attributes


# and behaviors as well
print(jim.run("slowly"))

# Is jim an instance of Dog()?


print(isinstance(jim, Dog))

# Is julie an instance of Dog()?


julie = Dog("Julie", 100)
print(isinstance(julie, Dog))

# Is johnny walker an instance of Bulldog()


johnnywalker = RussellTerrier("Johnny Walker", 4)
print(isinstance(johnnywalker, Bulldog))

# Is julie and instance of jim?


print(isinstance(julie, jim))
Output:

>>>

('Jim', 12)
Jim runs slowly
True
True
False
Traceback (most recent call last):
File "dog_isinstance.py", line 50, in <module>
print(isinstance(julie, jim))
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
Make sense? Both jim and julie are instances of the Dog() class, while johnnywalker is not an
instance of the Bulldog() class. Then as a sanity check, we tested if julie is an instance of jim,
which is impossible since jim is an instance of a class rather than a class itself—hence the reason
for the TypeError.

Overriding the Functionality of a Parent Class


Remember that child classes can also override attributes and behaviors from the parent class. For
examples:

>>>
>>> class Dog:
... species = 'mammal'
...
>>> class SomeBreed(Dog):
... pass
...
>>> class SomeOtherBreed(Dog):
... species = 'reptile'
...
>>> frank = SomeBreed()
>>> frank.species
'mammal'
>>> beans = SomeOtherBreed()
>>> beans.species
'reptile'
The SomeBreed() class inherits the species from the parent class, while
the SomeOtherBreed()class overrides the species, setting it to reptile.

Review Exercises (#2)

Exercise: "Dog Inheritance"Show/Hide

Create a Pets class that holds instances of dogs; this class is completely separate from
the Dog class. In other words, the Dog class does not inherit from the Pets class. Then assign
three dog instances to an instance of the Pets class. Start with the following code below. Save the
file as pets_class.py. Your output should look like this:

I have 3 dogs.
Tom is 6.
Fletcher is 7.
Larry is 9.
And they're all mammals, of course.
Starter code:

# Parent class
class Dog:

# Class attribute
species = 'mammal'
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)

# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)

# Child class (inherits from Dog class)


class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)

# Child class (inherits from Dog class)


class Bulldog(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)

Solution: "Dog Inheritance"Show/Hide

# Parent class
class Pets:

dogs = []

def __init__(self, dogs):


self.dogs = dogs

# Parent class
class Dog:

# Class attribute
species = 'mammal'

# Initializer / Instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# Instance method
def description(self):
return self.name, self.age

# Instance method
def speak(self, sound):
return "%s says %s" % (self.name, sound)

# Instance method
def eat(self):
self.is_hungry = False

# Child class (inherits from Dog class)


class RussellTerrier(Dog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)

# Child class (inherits from Dog class)


class Bulldog(Dog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)

# Create instances of dogs


my_dogs = [
Bulldog("Tom", 6),
RussellTerrier("Fletcher", 7),
Dog("Larry", 9)
]

# Instantiate the Pets class


my_pets = Pets(my_dogs)

# Output
print("I have {} dogs.".format(len(my_pets.dogs)))
for dog in my_pets.dogs:
print("{} is {}.".format(dog.name, dog.age))

print("And they're all {}s, of course.".format(dog.species))

Exercise: "Hungry Dogs"Show/Hide

Using the same file, add an instance attribute of is_hungry = True to the Dog class. Then add a
method called eat() which changes the value of is_hungry to False when called. Figure out the
best way to feed each dog and then output “My dogs are hungry.” if all are hungry or “My dogs
are not hungry.” if all are not hungry. The final output should look like this:

I have 3 dogs.
Tom is 6.
Fletcher is 7.
Larry is 9.
And they're all mammals, of course.
My dogs are not hungry.

Solution: "Hungry Dogs"Show/Hide

# Parent class
class Pets:

dogs = []

def __init__(self, dogs):


self.dogs = dogs
# Parent class
class Dog:

# Class attribute
species = 'mammal'

# Initializer / Instance attributes


def __init__(self, name, age):
self.name = name
self.age = age
self.is_hungry = True

# Instance method
def description(self):
return self.name, self.age

# Instance method
def speak(self, sound):
return "%s says %s" % (self.name, sound)

# Instance method
def eat(self):
self.is_hungry = False

# Child class (inherits from Dog class)


class RussellTerrier(Dog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)

# Child class (inherits from Dog class)


class Bulldog(Dog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)

# Create instances of dogs


my_dogs = [
Bulldog("Tom", 6),
RussellTerrier("Fletcher", 7),
Dog("Larry", 9)
]

# Instantiate the Pets class


my_pets = Pets(my_dogs)

# Output
print("I have {} dogs.".format(len(my_pets.dogs)))
for dog in my_pets.dogs:
dog.eat()
print("{} is {}.".format(dog.name, dog.age))

print("And they're all {}s, of course.".format(dog.species))

are_my_dogs_hungry = False
for dog in my_pets.dogs:
if dog.is_hungry:
are_my_dogs_hungry = True

if are_my_dogs_hungry:
print("My dogs are hungry.")
else:
print("My dogs are not hungry.")

Exercise: "Dog Walking"Show/Hide

Next, add a walk() method to both the Pets and Dog classes so that when you call the method on
the Pets class, each dog instance assigned to the Pets class will walk(). Save this
as dog_walking.py. This is slightly more difficult.

Start by implementing the method in the same manner as the speak() method. As for the method
in the Pets class, you will need to iterate through the list of dogs, then call the method itself.
The output should look like this:

Tom is walking!
Fletcher is walking!
Larry is walking!

Solution: "Dog Walking"Show/Hide

# Parent class
class Pets:

dogs = []

def __init__(self, dogs):


self.dogs = dogs

def walk(self):
for dog in self.dogs:
print(dog.walk())

# Parent class
class Dog:

# Class attribute
species = 'mammal'
is_hungry = True

# Initializer / instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# Instance method
def description(self):
return self.name, self.age
# Instance method
def speak(self, sound):
return "%s says %s" % (self.name, sound)

# Instance method
def eat(self):
self.is_hungry = False

def walk(self):
return "%s is walking!" % (self.name)

# Child class (inherits from Dog class)


class RussellTerrier(Dog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)

# Child class (inherits from Dog class)


class Bulldog(Dog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)

# Create instances of dogs


my_dogs = [
Bulldog("Tom", 6),
RussellTerrier("Fletcher", 7),
Dog("Larry", 9)
]

# Instantiate the Pet class


my_pets = Pets(my_dogs)

# Output
my_pets.walk()
Exercise: "Comprehension Check"Show/Hide

Answer the following questions about OOP to check your learning progress:

1. What’s a class?
2. What’s an instance?
3. What’s the relationship between a class and an instance?
4. What’s the Python syntax used for defining a new class?
5. What’s the spelling convention for a class name?
6. How do you instantiate, or create an instance of, a class?
7. How do you access the attributes and behaviors of a class instance?
8. What’s a method?
9. What’s the purpose of self?
10. What’s the purpose of the __init__ method?
11. Describe how inheritance helps prevent code duplication.
12. Can child classes override properties of their parents?

Solution: "Comprehension Check"Show/Hide

1. A class is a mechanism used to create new user-defined data structures. It contains data as
well as the methods used to process that data.
2. An instance is a copy of the class with actual values, literally an object of a specific class.
3. While a class is a blueprint used to describe how to make something, instances are
objects created from those blueprints.
4. class PythonClassName:
5. CamelCase notation, starting with a capital letter - i.e., PythonClassName()
6. You use the the class name, followed by parentheses. So if the class name is Dog(), an
dog instance would be - my_class = Dog().
7. With dot notation - e.g., instance_name.attribute_name
8. A function that’s defined inside a class.
9. The first argument of every method references the current instance of the class, which by
convention, is named self. In the __init__ method, self refers to the newly created object;
while in other methods, self refers to the instance whose method was called. For more
on __init__ vs. self, check out this article.
10. The __init__ method initializes an instance of a class.
11. Child classes inherit all of the parent’s attributes and behaviors.
12. Yes.
Q.1. What are the key features of Python?
If it makes for an introductory language to programming, Python must mean something. These
are its qualities:

1. Interpreted
2. Dynamically-typed
3. Object-oriented
4. Concise and simple
5. Free
6. Has a large community
Follow this link to explore more features of Python Programming
Q.2. Differentiate between deep and shallow copy.
A deep copy copies an object into another. This means that if you make a change to a copy of an
object, it won’t affect the original object. In Python, we use the function deepcopy() for this, and
we import the module copy. We use it like:

1. >>> import copy


2. >>> b=copy.deepcopy(a)

Deep Copy – Python Interview Questions and Answers


A shallow copy, however, copies one object’s reference to another. So, if we make a change in
the copy, it will affect the original object. For this, we have the function copy(). We use it like:

1. >>> b=copy.copy(a)
Shallow Copy – Python Interview Questions and Answers
Refer this link to know more about Deep & Shallow Copy in Python
Q.3. Differentiate between lists and tuples.
The major difference is that a list is mutable, but a tuple is immutable. Examples:

1. >>> mylist=[1,3,3]
2. >>> mylist[1]=2
3. >>> mytuple=(1,3,3)
4. >>> mytuple[1]=2
Traceback (most recent call last):
File “<pyshell#97>”, line 1, in <module>
mytuple[1]=2
TypeError: ‘tuple’ object does not support item assignment
For more insight, refer to Tuples vs Lists.
2. Basic Python Interview Questions for Freshers

Q.4 to Q.20 are some basic Python Interview question for freshers, however Experience can also
refer these questions to revise basic concepts.

Q.4. Explain the ternary operator in Python.


Unlike C++, we don’t have ?: in Python, but we have this:

[on true] if [expression] else [on false]


If the expression is True, the statement under [on true] is executed. Else, that under [on false] is
executed.
Below is how you would use it:

1. >>> a,b=2,3
2. >>> min=a if a<b else b
3. >>> min
2

1. >>> print("Hi") if a<b else print("Bye")


Hi

Are you familiar with all kinds of Python Operators?


Q.5. How is multithreading achieved in Python?
A thread is a lightweight process, and multithreading allows us to execute multiple threads at
once. As you know, Python is a multithreaded language. It has a multi-threading package.
The GIL (Global Interpreter Lock) ensures that a single thread executes at a time. A thread holds
the GIL and does a little work before passing it on to the next thread. This makes for an illusion
of parallel execution. But in reality, it is just threaded taking turns at the CPU. Of course, all the
passing around adds overhead to the execution.

Q.6. Explain inheritance in Python.


When one class inherits from another, it is said to be the child/derived/sub class inheriting from
the parent/base/super class. It inherits/gains all members (attributes and methods).

Inheritance lets us reuse our code, and also makes it easier to create and maintain applications.
Python supports the following kinds of inheritance:

1. Single Inheritance- A class inherits from a single base class.


2. Multiple Inheritance- A class inherits from multiple base classes.
3. Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from
another base class.
4. Hierarchical Inheritance- Multiple classes inherit from a single base class.
5. Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of
inheritance.
For more on inheritance, refer to Python Inheritance.
Q.7. What is Flask?
Python Flask, as we’ve previously discussed, is a web microframework for Python. It is based
on the ‘Werkzeug, Jinja 2 and good intentions’ BSD license. Two of its dependencies are
Werkzeug and Jinja2. This means it has around no dependencies on external libraries. Due to
this, we can call it a light framework.
A session uses a signed cookie to allow the user to look at and modify session contents. It will
remember information from one request to another.

However, to modify a session, the user must have the secret key Flask.secret_key.
Q.8. How is memory managed in Python?
Python has a private heap space to hold all objects and data structures. Being programmers, we
cannot access it; it is the interpreter that manages it. But with the core API, we can access some
tools. The Python memory manager controls the allocation.

Additionally, an inbuilt garbage collector recycles all unused memory so it can make it available
to the heap space.

Q.9. Explain help() and dir() functions in Python.


The help() function displays the documentation string and help for its argument.

1. >>> import copy


2. >>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.
See the module’s __doc__ string for more info.
The dir() function displays all the members of an object(any kind).
1. >>> dir(copy.copy)
[‘__annotations__’, ‘__call__’, ‘__class__’, ‘__closure__’, ‘__code__’, ‘__defaults__’,
‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__get__’,
‘__getattribute__’, ‘__globals__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’,
‘__kwdefaults__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__name__’, ‘__ne__’, ‘__new__’,
‘__qualname__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’,
‘__str__’, ‘__subclasshook__’]Let’s explore more Functions in Python
Q.10. Whenever you exit Python, is all memory de-allocated?
The answer here is no. The modules with circular references to other objects, or to objects
referenced from global namespaces, aren’t always freed on exiting Python.
Plus, it is impossible to de-allocate portions of memory reserved by the C library.

Q.11. What is monkey patching?


Dynamically modifying a class or module at run-time.

1. >>> class A:
2. def func(self):
3. print("Hi")
4. >>> def monkey(self):
5. print "Hi, monkey"
6. >>> m.A.func = monkey
7. >>> a = m.A()
8. >>> a.func()
Hi, monkey
Q.12. What is a dictionary in Python?
A python dictionary is something I have never seen in other languages like C++ or Java
programming. It holds key-value pairs.
1. >>> roots={25:5,16:4,9:3,4:2,1:1}
2. >>> type(roots)
<class ‘dict’>

1. >>> roots[9]
3

A dictionary is mutable, and we can also use a comprehension to create it.

1. >>> roots={x**2:x for x in range(5,0,-1)}


2. >>> roots
{25: 5, 16: 4, 9: 3, 4: 2, 1: 1}

Q.13. What do you mean by *args and **kwargs?


In cases when we don’t know how many arguments will be passed to a function, like when we
want to pass a list or a tuple of values, we use *args.

1. >>> def func(*args):


2. for i in args:
3. print(i)
4. >>> func(3,2,1,4,7)
3
2
1
4
7
**kwargs takes keyword arguments when we don’t know how many there will be.

1. >>> def func(**kwargs):


2. for i in kwargs:
3. print(i,kwargs[i])
4. >>> func(a=1,b=2,c=7)
a.1
b.2
c.7

The words args and kwargs are a convention, and we can use anything in their place.

Any doubt yet in Basic Python Interview Questions and answers for Freshers? Please ask in
Comments.
Q.14. Write Python logic to count the number of capital letters in a file.
1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
3. >>> with open('Today.txt') as today:
4. count=0
5. for i in today.read():
6. if i.isupper():
7. count+=1
8. print(count)
26

Q.15. What are negative indices?


Let’s take a list for this.

1. >>> mylist=[0,1,2,3,4,5,6,7,8]
A negative index, unlike a positive one, begins searching from the right.

1. >>> mylist[-3]
6
This also helps with slicing from the back:

1. >>> mylist[-6:-1]
[3, 4, 5, 6, 7]
Q.16. How would you randomize the contents of a list in-place?
For this, we’ll import the function shuffle() from the module random.

1. >>> from random import shuffle


2. >>> shuffle(mylist)
3. >>> mylist
[3, 4, 8, 0, 5, 7, 6, 2, 1]
Q.17. Explain join() and split() in Python.
join() lets us join characters from a string together by a character we specify.

1. >>> ','.join('12345')
‘1,2,3,4,5’

split() lets us split a string around the character we specify.

1. >>> '1,2,3,4,5'.split(',')
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
Q.18. Is Python case-sensitive?
A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In
other words, it cares about case- lowercase or uppercase. Let’s try this with Python.

1. >>> myname='Ayushi'
2. >>> Myname
Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
Myname
NameError: name ‘Myname’ is not defined
As you can see, this raised a NameError. This means that Python is indeed case-sensitive.

Let’s Discuss Errors and Exceptions in Python Programming


Q.19. How long can an identifier be in Python?
In Python, an identifier can be of any length. Apart from that, there are certain rules we must
follow to name one:

1. It can only begin with an underscore or a character from A-Z or a-z.


2. The rest of it can contain anything from the following: A-Z/a-z/_/0-9.
3. Python is case-sensitive, as we discussed in the previous question.
4. Keywords cannot be used as identifiers. Python has the following keywords:
and def False import not

as del finally in or

assert elif for is pass

break else from lambda print

class except global None raise

continue exec if nonlocal return

Q.20. How do you remove the leading whitespace in a string?


Leading whitespace in a string is the whitespace in a string before the first non-whitespace
character. To remove it from a string, we use the method lstrip().

1. >>> ' Ayushi '.lstrip()


‘Ayushi ‘

As you can see, this string had both leading and trailing whitespaces. lstrip() stripped the string
of the leading whitespace. If we want to strip the trailing whitespace instead, we use rstrip().

1. >>> ' Ayushi '.rstrip()


‘ Ayushi’
3. Advanced Python Interview Questions and Answers for Experienced

Q. 21 to Q. 35 are some Advanced Python Interview questions for Experience along with their
answers and Examples.

Q.21. How would you convert a string into lowercase?


We use the lower() method for this.

1. >>> 'AyuShi'.lower()
‘ayushi’

To convert it into uppercase, then, we use upper().

1. >>> 'AyuShi'.upper()
‘AYUSHI’

Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and
islower().

1. >>> 'AyuShi'.isupper()
False

1. >>> 'AYUSHI'.isupper()
True

1. >>> 'ayushi'.islower()
True

1. >>> '@yu$hi'.islower()
True

1. >>> '@YU$HI'.isupper()
True

So, characters like @ and $ will suffice for both cases.

Also, istitle() will tell us if a string is in title case.

1. >>> 'The Corpse Bride'.istitle()


True

Refer this link to explore more Python Strings with functions


Q.22. What is the pass statement in Python?
There may be times in our code when we haven’t decided what to do yet, but we must type
something for it to be syntactically correct. In such a case, we use the pass statement.

1. >>> def func(*args):


2. pass
3. >>>
Similarly, the break statement breaks out of a loop.
1. >>> for i in range(7):
2. if i==3: break
3. print(i)
1

Finally, the continue statement skips to the next iteration.

1. >>> for i in range(7):


2. if i==3: continue
3. print(i)
1
2
4
5
6

Q.23. What is a closure in Python?


A closure is said to occur when a nested function references a value in its enclosing scope. The
whole point here is that it remembers the value.

1. >>> def A(x):


2. def B():
3. print(x)
4. return B
5. >>> A(7)()
7

For more depth on closures, refer to Closures in Python.


Q.24. Explain the //, %, and ** operators in Python.
The // operator performs floor division. It will return the integer part of the result on division.
1. >>> 7//2
3
Normal division would return 3.5 here.

Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.

1. >>> 2**10
1024

Finally, % is for modulus. This gives us the value left after the highest achievable division.

1. >>> 13%7
6

1. >>> 3.5%1.5
0.5

Any Doubt yet in Advanced Python Interview Questions and Answers for Experienced? Please
Comment.

Q.24. How many kinds of operators do we have in Python? Explain arithmetic operators.
This type of Python Interview Questions and Answers can decide your knowledge in Python.
Answer the Python Interview Questions with some good Examples.

Here in Python, we have 7 kinds of operators: arithmetic, relational, assignment, logical,


membership, identity, and bitwise.

We have seven arithmetic operators. These allow us to perform arithmetic operations on values:

1. Addition (+) This adds two values.


1. >>> 7+8
15

2. Subtraction (-) This subtracts he second value from the first.


1. >>> 7-8
-1

3. Multiplication (*) This multiplies two numbers.


1. >>> 7*8
56

4. Division (/) This divides the first value by the second.


1. >>> 7/8
0.875
1. >>> 1/1
1.0

For floor division, modulus, and exponentiation refer to the previous question.

Q.25. Explain relational operators in Python.


Relational operators compare values.

1. Less than (<) If the value on the left is lesser, it returns True.
1. >>> 'hi'<'Hi'
False

2. Greater than (>) If the value on the left is greater, it returns True.
1. >>> 1.1+2.2>3.3
True
This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies.

3. Less than or equal to (<=) If the value on the left is lesser than or equal to, it returns True.
1. >>> 3.0<=3
True

4. Greater than or equal to (>=) If the value on the left is greater than or equal to, it returns
True.
1. >>> True>=False
True

5. Equal to (==) If the two values are equal, it returns True.


1. >>> {1,3,2,2}=={1,2,3}
True

6. Not equal to (!=) If the two values are unequal, it returns True.
1. >>> True!=0.1
True

1. >>> False!=0.1
True

Q.26. What are assignment operators in Python?


This one is an Important Interview question in Python Interview.

We can combine all arithmetic operators with the assignment symbol.

1. >>> a=7
2. >>> a+=1
3. >>> a
8

1. >>> a-=1
2. >>> a
7

1. >>> a*=2
2. >>> a
14

1. >>> a/=2
2. >>> a
7.0

1. >>> a**=2
2. >>> a
49.0

1. >>> a//=3
2. >>> a
16.0

1. >>> a%=4
2. >>> a
0.0

Q.27. Explain logical operators in Python.


We have three logical operators- and, or, not.

1. >>> False and True


False

1. >>> 7<7 or True


True

1. >>> not 2==2


False

Q.28. What are membership, operators?


With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

1. >>> 'me' in 'disappointment'


True

1. >>> 'us' not in 'disappointment'


True

Q.29. Explain identity operators in Python.


This is one of the very commonly asked Python Interview Questions and answers it with
examples.

The operators ‘is’ and ‘is not’ tell us if two values have the same identity.

1. >>> 10 is '10'
False

1. >>> True is not False


True

Q.30. Finally, tell us about bitwise operators in Python.


These operate on values bit by bit.

1. AND (&) This performs & on each bit pair.


1. >>> 0b110 & 0b010
2

2. OR (|) This performs | on each bit pair.


1. >>> 3|2
3

3. XOR (^) This performs an exclusive-OR operation on each bit pair.


1. >>> 3^2
1

4. Binary One’s Complement (~) This returns the one’s complement of a value.
1. >>> ~2
-3

5. Binary Left-Shift (<<) This shifts the bits to the left by the specified amount.
1. >>> 1<<2
4
Here, 001 was shifted to the left by two places to get 100, which is binary for 4.

6. Binary Right-Shift (>>)


1. >>> 4>>2
1

For more insight on operators, refer to Operators in Python.


Q.31. How would you work with numbers other than those in the decimal number system?
With Python, it is possible to type numbers in binary, octal, and hexadecimal.

1. Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.
1. >>> int(0b1010)
10

To convert a number into its binary form, we use bin().

1. >>> bin(0xf)
‘0b1111’

2. Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O.
1. >>> oct(8)
‘0o10’

3. Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X.
1. >>> hex(16)
‘0x10’

1. >>> hex(15)
‘0xf’

Q.32. How do you get a list of all the keys in a dictionary?


Be specific in these type of Python Interview Questions and Answers.

For this, we use the function keys().

1. >>> mydict={'a':1,'b':2,'c':3,'e':5}
2. >>> mydict.keys()
dict_keys([‘a’, ‘b’, ‘c’, ‘e’])

Q.33. Why are identifier names with a leading underscore disparaged?


Since Python does not have a concept of private variables, it is a convention to use leading
underscores to declare a variable private. This is why we mustn’t do that to variables we do not
want to make private.
Q.34. How can you declare multiple assignments in one statement?
There are two ways to do this:

1. >>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively


2. >>> a=b=c=3 #This assigns 3 to a, b, and c
Q.35. What is tuple unpacking?
First, let’s discuss tuple packing. It is a way to pack a set of values into a tuple.

1. >>> mytuple=3,4,5
2. >>> mytuple
(3, 4, 5)

This packs 3, 4, and 5 into mytuple.

Now, we will unpack the values from the tuple into variables x, y, and z.

1. >>> x,y,z=mytuple
2. >>> x+y+z
12
Q.1. What data types does Python support?
This is the most basic python interview question.

Python provides us with five kinds of data types:

 Numbers- Numbers use to hold numerical values.


1. >>> a=7.0
2. >>>
 Strings- A string is a sequence of characters. We declare it using single or double quotes.
1. >>> title="Ayushi's Book"
 Lists- A list is an ordered collection of values, and we declare it using square brackets.
1. >>> colors=['red','green','blue']
2. >>> type(colors)
<class ‘list’>
 Tuples- A tuple, like a list, is an ordered collection of values. The difference. However, is
that a tuple is immutable. This means that we cannot change a value in it.
1. >>> name=('Ayushi','Sharma')
2. >>> name[0]='Avery'
Traceback (most recent call last):
File “<pyshell#129>”, line 1, in <module>
name[0]=’Avery’
TypeError: ‘tuple’ object does not support item assignment
5. Dictionary- A dictionary is a data structure that holds key-value pairs. We declare it
using curly braces.
1. >>> squares={1:1,2:4,3:9,4:16,5:25}
2. >>> type(squares)
<class ‘dict’>
1. >>> type({})
<class ‘dict’>
We can also use a dictionary comprehension:
1. >>> squares={x:x**2 for x in range(1,6)}
2. >>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Follow this link to know more about Python Data Structure


Q.2. What is a docstring?
A docstring is a documentation string that we use to explain what a construct does. We place it
as the first thing under a function, class, or a method, to describe what it does. We declare a
docstring using three sets of single or double quotes.

1. >>> def sayhi():


2. """
3. The function prints Hi
4. """
5. print("Hi")
6. >>> sayhi()
Hi
To get a function’s docstring, we use its __doc__ attribute.

1. >>> sayhi.__doc__
‘\n\tThis function prints Hi\n\t’

A docstring, unlike a comment, is retained at runtime.

Q.3. What is the PYTHONPATH variable?


PYTHONPATH is the variable that tells the interpreter where to locate the module files imported
into a program. Hence, it must include the Python source library directory and the directories
containing Python source code. You can manually set PYTHONPATH, but usually, the Python
installer will preset it.
2. Basic Python Interview Questions

Q.4. What is slicing?


These are the types of basic Python interview questions for freshers.
Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we
use the slicing operator [].
1. >>> (1,2,3,4,5)[2:4]
(3, 4)

1. >>> [7,6,8,5,9][2:]
[8, 5, 9]

1. >>> 'Hello'[:-1]
‘Hell’

Q.5. What is a namedtuple?


A namedtuple will let us access a tuple’s elements using a name/label. We use the function
namedtuple() for this, and import it from collections.

1. >>> from collections import namedtuple


2. >>> result=namedtuple('result','Physics Chemistry Maths') #format
3. >>> Ayushi=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple
4. >>> Ayushi.Chemistry
95
As you can see, it let us access the marks in Chemistry using the Chemistry attribute of object
Ayushi.

To learn more about namedtuples, refer to namedtuple in Python.


Q.6. How would you declare a comment in Python?
Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe
(#). Anything following a hash is considered a comment, and the interpreter ignores it.
1. >>> #line 1 of comment
2. >>> #line 2 of comment
In fact, you can place a comment anywhere in your code. You can use it to explain your code.

Q.7. How would you convert a string into an int in Python?


If a string contains only numerical characters, you can convert it into an integer using the int()
function.
1. >>> int('227')
227

Let’s check the types:

1. >>> type('227')
<class ‘str’>
1. >>> type(int('227'))
<class ‘int’>
Q.8. How do you take input in Python?
For taking input from user, we have the function input(). In Python 2, we had another function
raw_input().

The input() function takes, as an argument, the text to be displayed for the task:
1. >>> a=input('Enter a number')
Enter a number7

But if you have paid attention, you know that it takes input in the form of a string.

1. >>> type(a)
<class ‘str’>
Multiplying this by 2 gives us this:

1. >>> a*=2
2. >>> a
’77’

So, what if we need to work on an integer instead?


We use the int() function for this.

1. >>> a=int(input('Enter a number'))


Enter a number7

Now when we multiply it by 2, we get this:

1. >>> a*=2
2. >>> a
14

Q.9. What is a frozen set in Python?


Answer these type of Python Interview Questions with Examples.

First, let’s discuss what a set is. A set is a collection of items, where there cannot be any
duplicates. A set is also unordered.

1. >>> myset={1,3,2,2}
2. >>> myset
{1, 2, 3}

This means that we cannot index it.

1. >>> myset[0]
Traceback (most recent call last):
File “<pyshell#197>”, line 1, in <module>
myset[0]
TypeError: ‘set’ object does not support indexing
However, a set is mutable. A frozen set is immutable. This means we cannot change its values.
This also makes it eligible to be used as a key for a dictionary.
1. >>> myset=frozenset([1,3,2,2])
2. >>> myset
frozenset({1, 2, 3})

1. >>> type(myset)
<class ‘frozenset’>

For more insight on sets, refer to Python Sets and Booleans.


Q.10. How would you generate a random number in Python?
This kind of Python interview Questions and Answers can Prove your depth of knowledge.

To generate a random number, we import the function random() from the module random.
1. >>> from random import random
2. >>> random()
0.7931961644126482

Let’s call for help on this.

1. >>> help(random)
Help on built-in function random:
random(…) method of random.Random instance
random() -> x in the interval [0, 1).

This means that it will return a random number equal to or greater than 0, and less than 1.

We can also use the function randint(). It takes two arguments to indicate a range from which to
return a random integer.

1. >>> from random import randint


2. >>> randint(2,7)
6

1. >>> randint(2,7)
5

1. >>> randint(2,7)
7

1. >>> randint(2,7)
6

1. >>> randint(2,7)
2

Q.11. How will you capitalize the first letter of a string?


Simply using the method capitalize().
1. >>> 'ayushi'.capitalize()
‘Ayushi’

1. >>> type(str.capitalize)
<class ‘method_descriptor’>

However, it will let other characters be.


1. >>> '@yushi'.capitalize()
‘@yushi’

Q.12. How will you check if all characters in a string are alphanumeric?
For this, we use the method isalnum().

1. >>> 'Ayushi123'.isalnum()
True

1. >>> 'Ayushi123!'.isalnum()
False

Other methods that we have include:

1. >>> '123.3'.isdigit()
False

1. >>> '123'.isnumeric()
True

1. >>> 'ayushi'.islower()
True

1. >>> 'Ayushi'.isupper()
False

1. >>> 'Ayushi'.istitle()
True

1. >>> ' '.isspace()


True

1. >>> '123F'.isdecimal()
False

Q.13. What is the concatenation?


This is very basic Python Interview Question, try not to make any mistake in this.

Concatenation is joining two sequences. We use the + operator for this.

1. >>> '32'+'32'
‘3232’
1. >>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]

1. >>> (2,3)+(4)
Traceback (most recent call last):
File “<pyshell#256>”, line 1, in <module>
(2,3)+(4)
TypeError: can only concatenate tuple (not “int”) to tuple
Here, 4 is considered an int. Let’s do this again.

1. >>> (2,3)+(4,)
(2, 3, 4)

Any query yet in basic Python interview questions and answers for freshers? Please Comment.

Q.14. What is a function?


When we want to execute a sequence of statements, we can give it a name. Let’s define a
function to take two numbers and return the greater number.

1. >>> def greater(a,b):


2. return a is a>b else b
3. >>> greater(3,3.5)
3.5

You can create your own function or use one of Python’s many built-in functions.
Q.15. Explain lambda expressions. When would you use one?
When we want a function with a single expression, we can define it anonymously. A lambda
expression may take input and returns a value. To define the above function as a lambda
expression, we type the following code in the interpreter:

1. >>> (lambda a,b:a if a>b else b)(3,3.5)


3.5

Here, a and b are the inputs. a if a>b else b is the expression to return. The arguments are 3 and
3.5.
It is possible to not have any inputs here.

1. >>> (lambda :print("Hi"))()


Hi

For more insight into lambdas, refer to Lambda Expressions in Python.


Q.16. What is recursion?
When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid
forming an infinite loop, we must have a base condition.
Let’s take an example.

1. >>> def facto(n):


2. if n==1: return 1
3. return n*facto(n-1)
4. >>> facto(4)
24

For more on recursion, visit Recursion in Python.


Q.17. What is a generator?
Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable.
We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.

1. >>> def squares(n):


2. i=1
3. while(i<=n):
4. yield i**2
5. i+=1
6. >>> for i in squares(7):
7. print(i)
1
4
9
16
25
36
49

Q.18. So, what is an iterator, then?


An iterator returns one object at a time to iterate on. To create an iterator, we use the iter()
function.
odds=iter([1,3,5,7,9])

Then, we call the next() function on it every time we want an object.

1. >>> next(odds)
1

1. >>> next(odds)
3

1. >>> next(odds)
5
1. >>> next(odds)
7

1. >>> next(odds)
9
And now, when we call it again, it raises a StopIteration exception. This is because it has reached
the end of the values to iterate on.

1. >>> next(odds)
Traceback (most recent call last):
File “<pyshell#295>”, line 1, in <module>
next(odds)
StopIteration
For more on iterators, refer to Python iterators.
Q.19. Okay, we asked you about generators and iterators, and you gave us the right
answers. But don’t they sound similar?
They do, but there are subtle differences:

1. For a generator, we create a function. For an iterator, we use in-built functions iter() and
next().
2. For a generator, we use the keyword ‘yield’ to yield/return an object at a time.
3. A generator may have as many ‘yield’ statements as you want.
4. A generator will save the states of the local variables every time ‘yield’ will pause the loop.
An iterator does not use local variables; it only needs an iterable to iterate on.
5. Using a class, you can implement your own iterator, but not a generator.
6. Generators are fast, compact, and simpler.
7. Iterators are more memory-efficient.
Read Generators vs Iterators in Python.
Q.20. We know Python is all the rage these days. But to be truly accepting of a great
technology, you must know its pitfalls as well. Would you like to talk about this?
Of course. To be truly yourself, you must be accepting of your flaws. Only then can you move
forward to work on them. Python has its flaws too:

1. Python’s interpreted nature imposes a speed penalty on it.


2. While Python is great for a lot of things, it is weak in mobile computing, and in browsers.
3. Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a
duck). This can raise runtime errors.
4. Python has underdeveloped database access layers. This renders it a less-than-perfect choice
for huge database applications.
5. And then, well, of course. Being easy makes it addictive. Once a Python-coder, always a
Python coder.
So while it has problems, it is also a wonderful tool for a lot of things. Refer to Python
Advantages and Disadvantages.
3. Python Interview Questions for Experienced

These are the Advanced Python Interview Questions and Answers for Experienced, however
they can also refer the basic Python Interview Questions and Answers for Freshers for basic
knowledge.

Q.21. What does the function zip() do?


One of the less common functions with beginners, zip() returns an iterator of tuples.

1. >>> list(zip(['a','b','c'],[1,2,3]))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Here, it pairs items from the two lists, and creates tuples with those. But it doesn’t have to be
lists.

1. >>> list(zip(('a','b','c'),(1,2,3)))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Q.22. If you are ever stuck in an infinite loop, how will you break out of it?
For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to
demonstrate this.

1. >>> def counterfunc(n):


2. while(n==7):print(n)
3. >>> counterfunc(7)
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
Traceback (most recent call last):
File “<pyshell#332>”, line 1, in <module>
counterfunc(7)
File “<pyshell#331>”, line 2, in counterfunc
while(n==7):print(n)
KeyboardInterrupt
1. >>>
Any doubt yet in Python Advanced interview Questions? Please comment.

Q.23. Explain Python’s parameter-passing mechanism.


To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter
within a function, the change reflects in the calling function. This is its default behavior.
However, when we pass literal arguments like strings, numbers, or tuples, they pass by value.
This is because they are immutable.

Q.24. With Python, how do you find out which directory you are currently in?
To find this, we use the function/method getcwd(). We import it from the module os.

1. >>> import os
2. >>> os.getcwd()
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’

1. >>> type(os.getcwd)
<class ‘builtin_function_or_method’>

We can also change the current working directory with chdir().

1. >>> os.chdir('C:\\Users\\lifei\\Desktop')
2. >>> os.getcwd()
‘C:\\Users\\lifei\\Desktop’

For more on this, read up on Python Directory.


Q.25. How will you find, in a string, the first word that rhymes with ‘cake’?
For our purpose, we will use the function search(), and then use group() to get the output.

1. >>> import re
2. >>> rhyme=re.search('.ake','I would make a cake, but I hate to bake')
3. >>> rhyme.group()
‘make’

And as we know, the function search() stops at the first match. Hence, we have our first rhyme to
‘cake’.

Q.26. How would you display a file’s contents in reversed order?


Let’s first get to the Desktop. We use the chdir() function/method form the os module for this.

1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
The file we’ll use for this is Today.txt, and it has the following contents:
OS, DBMS, DS, ADA
HTML, CSS, jQuery, JavaScript
Python, C++, Java
This sem’s subjects
Debugger
itertools
container

Let’s read the contents into a list, and then call reversed() on it:

1. >>> for line in reversed(list(open('Today.txt'))):


2. print(line.rstrip())
container
itertools
Debugger

This sem’s subjects

Python, C++, Java

HTML, CSS, jQuery, JavaScript

OS, DBMS, DS, ADA

Without the rstrip(), we would get blank lines between the output.

Q.27. What is Tkinter?


Tkinter is a famous Python library with which you can craft a GUI. It provides support for
different GUI tools and widgets like buttons, labels, text boxes, radio buttons, and more. These
tools and widgets have attributes like dimensions, colors, fonts, colors, and more.
You can also import the tkinter module.

1. >>> import tkinter


2. >>> top=tkinter.Tk()
This will create a new window for you:

This creates a window with the title ‘My Game’. You can position your widgets on this.

Follow this link to know more about Python Libraries


Q.28. How is a .pyc file different from a .py file?
While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-
independent bytecode. Hence, we can execute it on any platform that supports the .pyc format.
Python automatically generates it to improve performance(in terms of load time, not speed).
Q.29. How do you create your own package in Python?
We know that a package may contain sub-packages and modules. A module is nothing but
Python code.

To create a package of our own, we create a directory and create a file __init__.py in it. We leave
it empty. Then, in that package, we create a module(s) with whatever code we want. For a
detailed explanation with pictures, refer to Python Packages.
Q.30. How do you calculate the length of a string?
This is simple. We call the function len() on the string we want to calculate the length of.

1. >>> len('Usman Institute of Technology’)

You might also like