Codingcompiler Com Python Coding Interview Questions Answers
Codingcompiler Com Python Coding Interview Questions Answers
Stories
And Answers
by Coding Compiler
Preparing for Python coding interviews? If your answer is yes, then you are right
place. 141 Python Coding Interview Questions and Answers will help you crack
your following Python code interview.
Here Codingcompiler shares a very good list of 141 Python coding interview
questions for freshers and experienced. These Python coding questions are prepared
by expert Python developers. If you are a fresher or experienced in Python coding,
definitely, these interview questions on Python will help you to refresh your
coding knowledge to cross the line in your next Python job interview. All the best for
your future and happy python coding.
Table of Contents
Output
Hello, Python!
Hello, Python!
Hello, Python!
“Hello, Python!”
‘Hello, Python!’
Categories
Explanation: In Python programming, a string can be enclosed inside single quotes,
double quotes, or triple quotes.
Select Category
The above Python add two numbers program throws SyntaxError because, the
comma(,) is missing in print statement. The below print statement will give you the
sum of the two numbers.
Python input() function always converts the user input into a string. Whether you
enter an int or float value it will consider it as a string. We need to convert it into
number using int() or float() functions. See the below example.
The output of the sum of the two numbers program Can You Pay Bills with Bitcoin?
Top 10 Benefits of Paying with
Enter the first number: 15 Cryptocurrencies
Enter the second number: 10
Top 10 Benefits of Blockchain
The sum of 15 and 10 is 25
Technology for Business
The sum of 15 and 10 is 25.0
Launch story behind Shardeum-
Blockchain by WazirX
4) Write a Python program to illustrate arithmetic Why did this Budget Day see
operations (+,-,*,/)? 30%-50% Signups to Crypto
Exchanges?
Here is the Python arithmetic operators program:
Top 10 Best Laptops For
AutoCAD In India
# Read the input numbers from users
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
# Converting and adding two numbers using int() & float() functions
sum = int(num1) + int(num2)
Enter a number: 4
4 is Even number
Enter a number: 5
5 is Odd number
math.factorial() function returns the factorial of a given number. Let’s have a look at
the Python factorial program using a math function:
Enter a number: 2
The square root of 2.0 is 1.4142135623730951
Enter a number: 4
The square root of 4.0 is 2.0
The number should equal the nth power of their digits, i.e
Other Armstrong Numbers: 153, 370, 371, 407, 1634, 8208, 9474
#Printing the result whether the given number is armstrong number or not
if arms == sum1:
print("The given number", arms, "is armstrong number")
else:
print("The given number", arms, "is not an armstrong number")
#Python program to check whether the given year is leap year or not
Example Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, ….
def circ_Area(rad):
PI = 3.142
return PI * (rad*rad);
rad = float(input('Enter the radius of the circle: '))
print("Area of the circle is %.6f" % circ_Area(rad));
import calendar
# Get the month and year from the users
year = int(input("Enter the year: "))
month = int(input("Enter the month: "))
4! = 4x3x2x1 = 24
5! = 5x4x3x2x1 = 120
import math
def check_Fact(num):
return(math.factorial(num))
# Driver program
starting_Num = int(input('Enter the starting range: '))
ending_Num = int(input('Enter the ending range: '))
lst = disp_Prime(starting_Num, ending_Num)
if len(lst) == 0:
print("There are no prime numbers in this range")
else:
print("The prime numbers in the given range are: ", lst)
This Python coding example returns the vowels “a e i o u” present in a string. This
Python program is useful when finding vowels, Let’s try this and see how it works.
def get_vowels(String):
return [each for each in String if each in "aeiou"]
get_string1 = "hello" # ['e', 'o']
get_string2 = "python is fun" # ['o', 'i', 'u']
get_string3 = "coding compiler" # ['o', 'i', 'o', 'i', 'e']
get_string4 = "12345xyz" # []
In this Python coding example we use the join() method to convert comma separated
list to a string. Let’s try this Python program and see how it works.
#The join() method takes all items from the favorite_prog list and joins
them into one string.
print("What is your favorite programming language:", ",
".join(favorite_prog))
This Python coding example capitalizes every first letter of the characters in a string.
This Python program is useful when converting the first letter of a string to a capital
letter, Let’s try this and see how it works.
def capitalize(String):
return String.title()
This Python coding example explains implicit type conversion in Python. This Python
program is useful when working with different data types and conversions. Let’s try
this and see how it works.
print("Datatype of get_num1:",type(get_num1))
print("Datatype of get_num2:",type(get_num2))
Datatype of get_num1:
Datatype of get_num2:
#Let's find out what's the output of the below Python program.
Python is not able to convert string type to integer type implicitly. So we can see
TypeError in output.
Python coding example explains explicit type conversion in Python. This Python
program is useful when working with different data types and conversions. Let’s try
this Python code and see how it works.
print("Datatype of num1:",type(num1))
print("Datatype of num2 before Type Casting:",type(num2))
num2 = int(num2)
print("Datatype of num2 after Type Casting:",type(num2))
def outer_function():
num = 20
def inner_function():
num = 30
print('num =', num)
inner_function()
print('num =', num)
num = 10
outer_function()
print('num =', num)
Three different variables “num” are defined in separate namespaces and accessed
accordingly.
num = 30
num = 20
num = 10
def outer_function():
global num
num = 20
def inner_function():
global num
num = 30
print('num =', num)
inner_function()
print('num =', num)
num = 10
outer_function()
print('num =', num)
All references and assignments are to the global ‘num’ due to the use of the keyword
‘global’.
num = 30
num = 30
num = 30
if __name__ == "__main__":
print("Hello, World!")
Answer#
It’s boilerplate code that protects users from accidentally invoking the script when
they didn’t intend to. Here are some common problems when the guard is omitted
from a script:
If you have a custom class in the guardless script and save it to a pickle file, then
unpickling it in another script will trigger an import of the guardless script, with the
same problems outlined in the previous bullet.
Example Python Code:
# a.py
import b
# b.py
if __name__ == '__main__':
print("if-statement was executed")
Now run each file individually.
$ python a.py
__name__ equals b
When a.py is executed, it imports the module b. This causes all the code
inside b to run. Python sets globals()['__name__'] in the b module to the
module's name, b.
$ python b.py
__name__ equals __main__
if-statement was executed, when only the file b.py is executed, Python sets globals()
[‘name‘] in this file to “main“. Therefore, the if statement evaluates to True this time.
It’s a list of public objects of that module, as interpreted by import *. It overrides the
default of hiding everything that begins with an underscore.
Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list
of strings defining what symbols in a module will be exported when from <module>
import * is used on the module.
For example, the following code in a foo.py explicitly exports the symbols bar and baz:
waz = 5
bar = 10
def baz(): return 'baz'
print(bar)
print(baz)
If the __all__ above is commented out, this code will then execute to completion, as
the default behavior of import * is to import all symbols that do not begin with an
underscore, from the given namespace.
Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package
NOTE: __all__ affects the from <module> import * behavior only. Members that are
not mentioned in __all__ are still accessible from outside the module and can be
imported with from <module> import <member>.
Package-1/namespace/__init__.py
Package-1/namespace/module1/__init__.py
Package-2/namespace/__init__.py
Package-2/namespace/module2/__init__.py
the end-user can import namespace.module1 and import namespace.module2.
What’s the best way to define a namespace package so more than one Python
product can define modules in that namespace?
Answer#
On Python 3.3 you don’t have to do anything, just don’t put any __init__.py in your
namespace package directories and it will just work. On pre-3.3, choose the
pkgutil.extend_path() solution over the pkg_resources.declare_namespace() one,
because it’s future-proof and already compatible with implicit namespace packages.
Python 3.3 introduces implicit namespace packages.
This means there are now three types of objects that can be created by an import foo:
Process Python exited abnormally with code 2 may result in Python repl exiting (as
above) on a silly error.
So, what is the easiest way to create a Python namespace with a given set of
attributes?
E.g., I can create a dict on the fly (dict([(“a”,1),(“b”,”c”)])) but I cannot use it as a
Namespace:
Answer#
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
#and it'll work the exact same way as the argparse Namespace class when it
comes to attributes:
The two types are distinct; SimpleNamespace is primarily used for the
sys.implementation attribute and the return value of time.get_clock_info().
Further comparisons:
Both classes support equality testing; for two instances of the same class,
instance_a == instance_b is true if they have the same attributes with the same
values.
Both classes have a helpful __repr__ to show what attributes they have.
Namespace() objects support containment testing; ‘attrname’ in instance is true
if the namespace instance has an attribute namend attrname.
SimpleNamespace does not.
Namespace() objects have an undocumented ._get_kwargs() method that
returns a sorted list of (name, value) attributes for that instance. You can get
the same for either class using sorted(vars(instance).items()).
While SimpleNamespace() is implemented in C and Namespace() is
implemented in Python, attribute access is no faster because both use the same
__dict__ storage for the attributes. Equality testing and producing the
representation are a little faster for SimpleNamespace() instances.
do?
In some init.py files of modules I saw such single line:
import(‘pkg_resources’).declare_namespace(name)
What does it do and why people use it? Suppose it’s related to dynamic importing and
creating namespace at runtime.
Answer#
Answer#
The “advantage” of from xyz import * as opposed to other forms of import is that it
imports everything (well, almost… [see (a) below] everything) from the designated
module under the current module. This allows using the various objects (variables,
classes, methods…) from the imported module without prefixing them with the
module’s name.
#For example
Answer#
Because it puts a lot of stuff into your namespace (might shadow some other object
from the previous import and you won’t know about it).
Because you don’t know exactly what is imported and can’t easily find from which
module a certain thing was imported (readability).
Because you can’t use cool tools like pyflakes to statically detect errors in your code.
In Java (or C) the compiler determines where a variable is visible through static scope
analysis.
In C, scope is either the body of a function or it’s global or it’s external. The compiler
reasons this out for you and resolves each variable name based on scope rules.
External names are resolved by the linker after all the modules are compiled.
In Java, scope is the body of a method function, or all the methods of a class. Some
class names have a module-level scope, also. Again, the compiler figures this out at
compile time and resolves each name based on the scope rules.
In Python, each package, module, class, function and method function owns a
“namespace” in which variable names are resolved. Plus there’s a global namespace
that’s used if the name isn’t in the local namespace.
Each variable name is checked in the local namespace (the body of the function, the
module, etc.), and then checked in the global namespace.
Variables are generally created only in a local namespace. The global and nonlocal
statements can create variables in other than the local namespace.
When a function, method function, module or package is evaluated (that is, starts
execution) a namespace is created. Think of it as an “evaluation context”. When a
function or method function, etc., finishes execution, the namespace is dropped. The
variables are dropped. The objects may be dropped, also.
Yes, indeed. You can use Python classes strictly for namespacing as that is one of the
special things they can do and do differently than modules. It’s a lot easier to define a
class as a namespace inline in a file than to generate more files.
You should not do it without commenting on your code saying what it’s for. Python
classes come in a lot of different forms and purposes and this makes it difficult to
understand code you have not seen before.
A Python class used as a namespace is no less a Python class than one that meets the
perception of what a class is in other languages. Python does not require a class to be
instantiated to be useful. It does not require ivars and does not require methods. It is
fairly flexible.
Lots of people have their ideas about what is or isn’t Pythonic. But if they were all
worried about something like consistency, they’d push to have things like len() dir(),
and help() be a method of objects rather than a global function.
Answer#
#It is as simple as
Anybody who reads the source will know what the exposed public API is. It doesn’t
prevent them from poking around in private declarations but does provide a good
warning not to.
When using from mod import *, only names listed in __all__ will be imported. This is
not as important, in my opinion, because importing everything is a really bad idea.
@staticmethod
def bar():
MyClass.foo()
Is there a way to make this work without naming MyClass in the call? i.e. so I can just
say foo() on the last line?
Answer#
There is no way to use foo and get what you want. There is no implicit class scope, so
foo is either a local or a global, neither of which you want.
class MyClass:
@classmethod
def foo(cls):
print "hi"
@classmethod
def bar(cls):
cls.foo()
#This way, at least you don't have to repeat the name of the class.
p = Programming()
print(p.__class__.__name__)
#Output
Programming
p = Programming()
print(type(p).__name__)
#Output
Programming
class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
and:
class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
I’ve seen super being used quite a lot in classes with only single inheritance. I can see
why you’d use it in multiple inheritance but am unclear as to what the advantages are
of using it in this kind of situation.
#Output
super() lets you avoid referring to the base class explicitly, which can be nice. But the
main advantage comes with multiple inheritance, where all sorts of fun stuff can
happen. See the standard docs on super if you haven’t already.
Note that the syntax changed in Python 3.0: you can just say super().__init__()
instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.
SomeBaseClass.__init__(self)
means to call SomeBaseClass’s __init__. while
super().__init__()
means to call a bound __init__ from the parent class that follows SomeBaseClass’s
child class (the one that defines this method) in the instance’s Method Resolution
Order (MRO).
If the instance is a subclass of this child class, there may be a different parent that
comes next in the MRO.
Explained simply
When you write a class, you want other classes to be able to use it. super() makes it
easier for other classes to use the class you’re writing.
When another class subclasses the class you wrote, it could also be inherited from
other classes. And those classes could have an __init__ that comes after this __init__
based on the ordering of the classes for method resolution.
Without super you would likely hard-code the parent of the class you’re writing (like
the example does). This would mean that you would not call the next __init__ in the
MRO, and you would thus not get to reuse the code in it.
If you’re writing your own code for personal use, you may not care about this
distinction. But if you want others to use your code, using super is one thing that
allows greater flexibility for users of the code.
Python 2 versus 3
This works in Python 2 and 3:
super(Child, self).__init__()
This only works in Python 3:
super().__init__()
It works with no arguments by moving up in the stack frame and getting the first
argument to the method (usually self for an instance method or cls for a class method
– but could be other names) and finding the class (e.g. Child) in the free variables (it is
looked up with the name class as a free closure variable in the method).
Variables declared inside the class definition, but not inside a method are class or
static variables:
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
This is different from C++ and Java, but not so different from C#, where a static
member can’t be accessed using a reference to an instance.
class MyClass(object):
…
Answer#
#Python 3
#Python 2
Explanation:
When defining base classes in Python 3.x, you’re allowed to drop the object from the
definition. However, this can open the door for a seriously hard-to-track problem…
Python introduced new-style classes back in Python 2.2, and by now old-style classes
are really quite old.
class MyClass:
def func(self, name):
self.name = name
Answer#
The reason you need to use self. is because Python does not use a special syntax to
refer to instance attributes.
Python decided to do methods in a way that makes the instance to which the method
belongs be passed automatically, but not received automatically: the first parameter
of methods is the instance the method is called on.
That makes methods entirely the same as functions and leaves the actual name to
use up to you (although the self is the convention, and people will generally frown at
you when you use something else.) self is not special to the code, it’s just another
object.
Python could have done something else to distinguish normal names from attributes
— special syntax like Ruby has, or requiring declarations like C++ and Java do, or
perhaps something yet more different — but it didn’t.
Python’s all for making things explicit, making it obvious what’s what, and although it
doesn’t do it entirely everywhere, it does do it for instance attributes.
That’s why assigning to an instance attribute needs to know what instance to assign
to, and that’s why it needs self..
#Example: Let's say you have a class ClassA which contains a method
methodA defined as:
Up to Python 2.1, old-style classes were the only flavor available to the user.
This reflects the fact that all old-style instances, independently of their class, are
implemented with a single built-in type, called an instance.
New-style classes were introduced in Python 2.2 to unify the concepts of class and
type. A new-style class is simply a user-defined type, no more, no less.
The major motivation for introducing new-style classes is to provide a unified object
model with a full meta-model.
It also has a number of immediate benefits, like the ability to subclass most built-in
types, or the introduction of “descriptors”, which enable computed properties.
New-style classes are created by specifying another new-style class (i.e. a type) as a
parent class, or the “top-level type” object if no other parent is needed.
The behavior of new-style classes differs from that of old-style classes in a number of
important details in addition to what type returns.
Some of these changes are fundamental to the new object model, like the way special
methods are invoked. Others are “fixes” that could not be implemented before for
compatibility concerns, like the method resolution order in case of multiple
inheritances.
No matter if you subclass from the object or not, classes are new-style in Python 3.
Declaration-wise:
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don’t.
class OldStyleClass():
pass
Python 3 Note:
Python 3 doesn’t support old-style classes, so either form noted above results in a
new-style class.
class Foo(Bar):
def baz(self, **kwargs):
return super().baz(**kwargs)
#For Python < 3, you must explicitly opt in to using new-style classes and
use:
class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)
Return a proxy object that delegates method calls to a parent or sibling class of type.
This is useful for accessing inherited methods that have been overridden in a class.
The search order is the same as that used by getattr() except that the type itself is
skipped.
class B(A):
def foo(self):
super(B, self).foo() # calls 'A.foo()'
myB = B()
myB.foo()
How can I define the printing behavior (or the string representation) of a class and its
instances?
For example, referring to the above code, how can I modify the Test class so that
printing an instance shows the value?
Answer#
The __str__ method is what gets called happens when you print it, and the __repr__
method is what happens when you use the repr() function (or when you look at it with
the interactive prompt).
If no __str__ method is given, Python will print the result of __repr__ instead. If you
define __str__ but not __repr__, Python will use what you see above as the __repr__,
but still use __str__ for printing.
#For example:
class test:
def __init__(self):
self.a = 10
def __call__(self):
b = 20
Answer#
So, the __init__ method is used when the class is called to initialize the instance, while
the __call__ method is called when the instance is called.
Example:
The __init__ is used to initialize newly created object, and receives arguments used to
do that:
class Foo:
def __init__(self, a, b, c):
# ...
x = Foo(1, 2, 3) # __init__
class Foo:
def __call__(self, a, b, c):
# ...
x = Foo()
x(1, 2, 3) # __call__
A metaclass is the class of a class. A class defines how an instance of the class (i.e. an
object) behaves while a metaclass defines how a class behaves. A class is an instance
of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the
better approach is to make it an actual class itself. type is the usual metaclass in
Python. type is itself a class, and it is its own type. You won’t be able to recreate
something like type purely in Python, but Python cheats a little. To create your own
metaclass in Python you really just want to subclass type.
Combined with the normal __init__ and __new__ methods, metaclasses, therefore,
allow you to do ‘extra things’ when creating a class, like registering the new class with
some registry or replacing the class with something else entirely.
When the class statement is executed, Python first executes the body of the class
statement as a normal block of code. The resulting namespace (a dict) holds the
attributes of the class-to-be.
However, metaclasses actually define the type of a class, not just a factory for it, so
you can do much more with them. You can, for instance, define normal methods on
the metaclass.
These metaclass-methods are like class methods in that they can be called on the
class without an instance, but they are also not like class methods in that they cannot
be called on an instance of the class. type.__subclasses__() is an example of a
method on the type metaclass.
You can also define the normal ‘magic’ methods, like __add__, __iter__, and
__getattr__, to implement or change how the class behaves.
In Python 2, you can add a __metaclass__ attribute when you write a class (see next
section for the Python 3 syntax):
class Foo(object):
__metaclass__ = something…
[…]
If you do so, Python will use the metaclass to create the class Foo.
Metaclasses in Python 3
i.e. the metaclass attribute is no longer used, in favor of a keyword argument in the
list of base classes.
One thing added to metaclasses in Python 3 is that you can also pass attributes as
keyword-arguments into a metaclass, like so:
A staticmethod is a method that knows nothing about the class or instance it was
called on. It just gets the arguments that were passed, no implicit first argument. It is
basically useless in Python — you can just use a module function instead of a
staticmethod.
A classmethod, on the other hand, is a method that gets passed the class it was
called on, or the class of the instance it was called on, as first argument.
This is useful when you want the method to be a factory for the class: since it gets the
actual class it was called on as first argument, you can always instantiate the right
class, even when subclasses are involved.
However, privacy is not enforced in any way. Using leading underscores for functions
in a module indicates it should not be imported from somewhere else.
From the PEP-8 style guide:
Any identifier of the form __spam (at least two leading underscores, at most one
trailing underscore) is textually replaced with _classname__spam, where classname is
the current class name with leading underscore(s) stripped.
This mangling is done without regard to the syntactic position of the identifier, so it
can be used to define class-private instance and class variables, methods, variables
stored in globals, and even variables stored in instances. private to this class on
instances of other classes.
Name mangling is intended to give classes an easy way to define “private” instance
variables and methods, without having to worry about instance variables defined by
derived classes, or mucking with instance variables by code outside the class.
Note that the mangling rules are designed mostly to avoid accidents; it still is possible
for a determined soul to access or modify a variable that is considered private.
Example:
Normally, in Python, you want your code to support inheritance, of course (since
inheritance is so handy, it would be bad to stop code using yours from using it!), so
isinstance is less bad than checking identity of types because it seamlessly supports
inheritance.
#Using type:
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
#Using isinstance:
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
A mixin is a special kind of multiple inheritance. There are two main situations where
mixins are used:
For an example of number one, consider werkzeug’s request and response system. I
can make a plain old request object by saying:
class Request(BaseRequest):
pass