OOPs Short Questions
OOPs Short Questions
OOPs Short Questions
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.
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.
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.
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:
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and
Parentheses.
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.
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.
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.
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.
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.
There are three various types of constructors, and they are as follows:
– Parametric Constructor – With Parameters. Create a new instance of a class and also passing
arguments simultaneously.
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.
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.
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.
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
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.
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?
False.
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.
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?
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.
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.
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.
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.
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:
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'
Instantiating Objects
Instantiating is a fancy term for creating a new, unique instance of a class.
For example:
>>>
>>>
class Dog:
# Class Attribute
species = 'mammal'
# 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:
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.
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'
# 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)
Modifying Attributes
You can change the value of attributes based on some behavior:
>>>
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
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:
>>>
# Parent class
class Dog:
# Class attribute
species = 'mammal'
# 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)
# Parent class
class Dog:
# Class attribute
species = 'mammal'
# 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)
>>>
('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.
>>>
>>> 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.
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)
# Parent class
class Pets:
dogs = []
# Parent class
class Dog:
# Class attribute
species = 'mammal'
# 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
# Output
print("I have {} dogs.".format(len(my_pets.dogs)))
for dog in my_pets.dogs:
print("{} is {}.".format(dog.name, dog.age))
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.
# Parent class
class Pets:
dogs = []
# Class attribute
species = 'mammal'
# 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
# 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))
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.")
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!
# Parent class
class Pets:
dogs = []
def walk(self):
for dog in self.dogs:
print(dog.walk())
# Parent class
class Dog:
# Class attribute
species = 'mammal'
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
def walk(self):
return "%s is walking!" % (self.name)
# 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?
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. >>> 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.
1. >>> a,b=2,3
2. >>> min=a if a<b else b
3. >>> min
2
Inheritance lets us reuse our code, and also makes it easier to create and maintain applications.
Python supports the following kinds of inheritance:
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.
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
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
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. >>> ','.join('12345')
‘1,2,3,4,5’
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.
as del finally in or
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().
Q. 21 to Q. 35 are some Advanced Python Interview questions for Experience along with their
answers and Examples.
1. >>> 'AyuShi'.lower()
‘ayushi’
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
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.
We have seven arithmetic operators. These allow us to perform arithmetic operations on values:
For floor division, modulus, and exponentiation refer to the previous question.
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
6. Not equal to (!=) If the two values are unequal, it returns True.
1. >>> True!=0.1
True
1. >>> False!=0.1
True
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
The operators ‘is’ and ‘is not’ tell us if two values have the same identity.
1. >>> 10 is '10'
False
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.
1. Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.
1. >>> int(0b1010)
10
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’
1. >>> mydict={'a':1,'b':2,'c':3,'e':5}
2. >>> mydict.keys()
dict_keys([‘a’, ‘b’, ‘c’, ‘e’])
1. >>> mytuple=3,4,5
2. >>> mytuple
(3, 4, 5)
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.
1. >>> sayhi.__doc__
‘\n\tThis function prints Hi\n\t’
1. >>> [7,6,8,5,9][2:]
[8, 5, 9]
1. >>> 'Hello'[:-1]
‘Hell’
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’
1. >>> a*=2
2. >>> a
14
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}
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’>
To generate a random number, we import the function random() from the module random.
1. >>> from random import random
2. >>> random()
0.7931961644126482
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. >>> randint(2,7)
5
1. >>> randint(2,7)
7
1. >>> randint(2,7)
6
1. >>> randint(2,7)
2
1. >>> type(str.capitalize)
<class ‘method_descriptor’>
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
1. >>> '123.3'.isdigit()
False
1. >>> '123'.isnumeric()
True
1. >>> 'ayushi'.islower()
True
1. >>> 'Ayushi'.isupper()
False
1. >>> 'Ayushi'.istitle()
True
1. >>> '123F'.isdecimal()
False
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.
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:
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. >>> 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:
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.
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.
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’>
1. >>> os.chdir('C:\\Users\\lifei\\Desktop')
2. >>> os.getcwd()
‘C:\\Users\\lifei\\Desktop’
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’.
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:
Without the rstrip(), we would get blank lines between the output.
This creates a window with the title ‘My Game’. You can position your widgets on this.
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.