350 Interview
350 Interview
350 Interview
2. What is PEP 8?
Ans: PEP 8 is a coding convention, a set of recommendation, about how to write your
Python code more readable.
26. Mention what are the rules for local and global variables in Python?
Ans: Local variables: If a variable is assigned a new value anywhere within the
function’s body, it’s assumed to be local.
Global variables: Those variables that are only referenced inside a function are
implicitly global.
27. How can you share global variables across modules?
Ans: To share global variables across modules within a single program, create a
special module. Import the config module in all modules of your application. The
module will be available as a global variable across modules.
28. Explain how can you make a Python Script executable on Unix?To make a Python
Script executable on Unix, you need to do two things,
Ans: Script file’s mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
31. Explain how can you access a module written in Python from C?
Ans: You can access a module written in Python from C by following method, Module =
=PyImport_ImportModule(“”);
36. Mention what is the difference between Django, Pyramid, and Flask?
Ans: Flask is a “micro framework” primarily build for a small application with
simpler requirements. In flask, you have to use external libraries. Flask is ready
to use.
Pyramid are build for larger applications. It provides flexibility and lets the
developer use the right tools for their project. The developer can choose the
database, URL structure, templating style and more. Pyramid is heavy configurable.
Like Pyramid, Django can also used for larger applications. It includes an ORM.
38. Explain what is the common way for the Flask script to work?
Ans: The common way for the flask script to work is…
Either it should be the import path for your application Or the path to a Python
file
40. Is Flask an MVC model and if yes give an example showing MVC pattern for your
application?
Ans: Basically, Flask is a minimalistic framework which behaves same as MVC
framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will
consider for the following example
Def hello():
app.run(debug = True)
app = Flask(_name_)
Def hello():
42. What do you mean by python being an “interpreted language”? (Continues from
previous question)
Ans: An interpreted languageis a programming languagefor which most of its
implementations execute instructions directly, without previously compiling a
program
into machinelanguageinstructions. In context of Python, it means that Python
program
runs directly from the source code.
47. Create a unicode string in python with the string “This is a test string”?
Ans: some_variable=u’Thisisateststring’
Or
some_variable=u”Thisisateststring”
50.What are the rules for local and global variables in Python?
Ans: If a variable is defined outside function then it is implicitly global. If
variable is
assigned new value inside the function means it is local. If we want to make it
global we
need to explicitly define it as global. Variable referenced inside the function are
implicit
global
#!/usr/bin/python
deffun1(a):
print’a:’,a
a=33;
print’locala:’,a
a=100
fun1(a)
print’aoutsidefun1:’,a
Ans. Output:
a:100
locala:33
aoutsidefun1:100
52.What is the output of the following program?
Ans:
#!/usr/bin/python
deffun2():
globalb
print’b:’,b
b=33
print’globalb:’,b
b=100
fun2()
print’boutsidefun2′,b
Ans. Output:
b:100
globalb:33
boutsidefun2:33
#!/usr/bin/python
deffoo(x,y):
globala
a=42
x,y=y,x
b=33
b=17
c=100
print(a,b,x,y)
a,b,x,y=1,15,3,4
foo(17,4)
print(a,b,x,y)
Ans.Output:
4217417
421534
#!/usr/bin/python
deffoo(x=[]):
x.append(1)
returnx
foo()
foo()
Output:
[1]
[1,1]
55. What is the purpose of #!/usr/bin/pythonon the first line in the above
code? Is there any advantage?
Ans: By specifying #!/usr/bin/pythonyou specify exactly which interpreter will be
used to run the script on a particular system. This is the hardcoded path to the
python
interpreter for that particular system. The advantage of this line is that you can
use a
specific python version to run your code.
list=[‘a’,’b’,’c’,’d’,’e’]
printlist[10]
Ans. Output:
IndexError.Or Error.
list=[‘a’,’b’,’c’,’d’,’e’]
printlist[10:]
Ans. Output:
[]
Theabovecodewilloutput[],andwillnotresultinanIndexError.
As one would expect, attempting to access a member of a list using an index that
exceeds the number of members results in an IndexError.
[x**2forxinrange(10)ifx%2==0]
Ans. Creates the following list:
[0,4,16,36,64]
Dictionary number
List boolean
string
tuple
65.When should you use generator expressions vs. list comprehensions in Python and
vice-versa?
Ans: Iterating over the generator expression or the list comprehension will do the
same
thing. However, the list comp will create the entire list in memory first while the
generator expression will create the items on the fly, so you are able to use it
for very
large (and also infinite!) sequences.
69. What is the statement that can be used in Python if a statement is required
syntactically but the program requires no action?
Ans:
pass
70. Do you know what is the difference between lists and tuples? Can you give me an
example for their usage?
Ans:
First list are mutable while tuples are not, and second tuples can be hashed e.g.
to be used as keys for dictionaries. As an example of their usage, tuples are used
when
the order of the elements in the sequence matters e.g. a geographic coordinates,
“list”
of points in a path or route, or set of actions that should be executed in specific
order.
Don’t forget that you can use them a dictionary keys. For everything else use lists
77. How do I get a list of all files (and directories) in a given directory in
Python?
Ans: Following is one possible solution there can be other similar ones:
import os
for dirname,dirnames,filenames in os.walk(‘.’):
#printpathtoallsubdirectoriesfirst.
forsubdirnameindirnames:
printos.path.join(dirname,subdirname)
#printpathtoallfilenames.
forfilenameinfilenames:
printos.path.join(dirname,filename)
#Advancedusage:
#editingthe’dirnames’listwillstopos.walk()fromrecursing
intothere.
if’.git’indirnames:
#don’tgointoany.gitdirectories.
dirnames.remove(‘.git’)
83. What is GIL? What does it do?Talk to me about the GIL. How does it impact
concurrency in Python? What kinds of applications does it impact more than others?
Ans: Python’s GIL is intended to serialize access to interpreter internals from
different
threads. On multicore systems, it means that multiple threads can’t effectively
make
use of multiple cores. (If the GIL didn’t lead to this problem, most people
wouldn’t care
about the GIL it’s only being raised as an issue because of the increasing
prevalence
of multicore systems.)
Note that Python’s GIL is only really an issue for CPython, the reference
implementation. Jython and IronPython don’t have a GIL. As a Python developer, you
don’t generally come across the GIL unless you’re writing a C extension. C
extension
writers need to release the GIL when their extensions do blocking I/O, so that
other
threads in the Python process get a chance to run.
85.How do you iterate over a list and pull element indices at the same time?
Ans: You are looking for the enumerate function. It takes each element in a
sequence
(like a list) and sticks it’s location right before it. For example:
>>>my_list=[‘a’,’b’,’c’]
>>>list(enumerate(my_list))
[(0,’a’),(1,’b’),(2,’c’)]
Note that enumerate() returns an object to be iterated over, so wrapping it in
list() just
helps us see what enumerate() produces.
An example that directly answers the question is given below
my_list=[‘a’,’b’,’c’]
fori,charinenumerate(my_list):
printi,char
The output is:
0a
1b
2c
86. How does Python’s list.sort work at a high level? Is it stable? What’s the
runtime?
Ans: In early pythonversions, the sort function implemented a modified version of
quicksort. However, it was deemed unstable and as of 2.3 they switched to using an
adaptive mergesort algorithm.
88. How can we pass optional or keyword parameters from one function to another in
Python?
Ans:
Gather the arguments using the * and ** specifiers in the function’s parameter
list. This
gives us positional arguments as a tuple and the keyword arguments as a dictionary.
Then we can pass these arguments while calling another function by using * and **:
deffun1(a,*tup,**keywordArg):
…
keywordArg[‘width’]=’23.3c’
…
Fun2(a,*tup,**keywordArg)
91. Tell me a very simple solution to print every other element of this list?
Ans:
L=[0,10,20,30,40,50,60,70,80,90]
L[::2]
A very good solution would be to use the set type. In a Python set, duplicates are
not
allowed.
So, list(set(words)) would remove the duplicates.
98. Print the length of each line in the file ‘file.txt’ not including any
whitespaces at the end of the lines?
Ans:
withopen(“filename.txt”,”r”)asf1:
printlen(f1.readline().rstrip())
rstrip() is an inbuilt function which strips the string from the right end of
spaces or tabs
(whitespace characters).
func([1,2,3])#explicitlypassinginalist
func() #usingadefaultemptylist
deffunc(n=[]):
#dosomethingwithn
printn
This would result in a NameError. The variable n is local to function func and
can’t be accessesd outside. So, printing it won’t be possible.
seems like a string is being concatenated. Nothing much can be said without
knowing types of variables a, b, c. Also, if all of the a, b, c are not of type
string,
TypeError would be raised. This is because of the string constants (‘[‘ , ‘]’) used
in the
statement.
101. What are Python decorators?
Ans:
A Python decorator is a specific change that we make in Python syntax to alter
functions easily.
each of the elements of the existing list. List comprehensions creates lists
without using
map() , filter() or lambda form.
107. Which of the languages does Python resemble in its class syntax?
Ans: c++.
Python is an interpreted language. That means that, unlike languages like C and its
variants, Python does not need to be compiled before it is run. Other interpreted
languages include PHP and Ruby.
Python is dynamically typed, this means that you don’t need to state the types of
variables when you declare them or anything like that. You can do things like x=111
and then x="I'm a string" without error
Python is well suited to object orientated programming in that it allows the
definition of classes along with composition and inheritance. Python does not have
access specifiers (like C++’s public, private).
In Python, functions are first-class objects. This means that they can be assigned
to variables, returned from other functions and passed into functions. Classes are
also first class objects
Writing Python code is quick but running it is often slower than compiled
languages. Fortunately,Python allows the inclusion of C based extensions so
bottlenecks can be optimized away and often are. The numpy package is a good
example of this, it’s really quite quick because a lot of the number crunching it
does isn’t actually done by Python
Python finds use in many spheres – web applications, automation, scientific
modeling, big data applications and many more. It’s also often used as “glue” code
to get other languages and components to play nice.
Memory management in python is managed by Python private heap space. All Python
objects and data structures are located in a private heap. The programmer does not
have access to this private heap. The python interpreter takes care of this
instead.
The allocation of heap space for Python objects is done by Python’s memory manager.
The core API gives access to some tools for the programmer to code.
Python also has an inbuilt garbage collector, which recycles all the unused memory
and so that it can be made available to the heap space.
117.What is PYTHONPATH?
Ans:It is an environment variable which is used when a module is imported. Whenever
a module is imported, PYTHONPATH is also looked up to check for the presence of the
imported modules in various directories. The interpreter uses it to determine which
module to load.
118. What are python modules? Name some commonly used built-in modules in Python?
Ans:Python modules are files containing Python code. This code can either be
functions classes or variables. A Python module is a .py file containing executable
code.
os
sys
math
random
data time
JSON
119.What are local variables and global variables in Python?
Ans:
Global Variables:
Local Variables:
Any variable declared inside a function is known as a local variable. This variable
is present in the local space and not in the global space.
Example:
1
2
3
4
5
6
a=2
def add():
b=3
c=a+b
print(c)
add()
Output: 5
When you try to access the local variable outside the function add(), it will throw
an error.
list() – This function is used to convert any data type to a list type.
Example:
1
2
3
4
5
import array as arr
My_Array=arr.array('i',[1,2,3,4])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)
Output:
1
2
3
def Newfunc():
print("Hi, Welcome to Edureka")
Newfunc(); #calling the function
Output: Hi, Welcome to Edureka
126.What is __init__?
Ans:__init__ is a method or constructor in Python. This method is automatically
called to allocate memory when a new object/ instance of a class is created. All
classes have the __init__ method.
1
2
3
4
5
6
7
8
9
10
11
class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
Output:
XYZ
23
20000
Example:
1
2
a = lambda x,y : x+y
print(a(5, 6))
Output: 11
The self variable in the init method refers to the newly created object while in
other methods, it refers to the object whose method was called.
131. How can you randomize the items of a list in place in Python?
Ans: Consider the example shown below:
1
2
3
4
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
The output of the following code is as below.
1
2
import random
random.random
The statement random.random() method return the floating point number that is in
the range of [0, 1). The function generates random float numbers. The methods that
are used with the random class are the bound methods of the hidden instances. The
instances of the Random can be done to show the multi-threading programs that
creates a different instance of individual threads. The other random generators
that are used in this are:
randrange(a, b): it chooses an integer and define the range in-between [a, b). It
returns the elements by selecting it randomly from the range that is specified. It
doesn’t build a range object.
uniform(a, b): it chooses a floating point number that is defined in the range of
[a,b).Iyt returns the floating point number
normalvariate(mean, sdev): it is used for the normal distribution where the mu is a
mean and the sdev is a sigma that is used for standard deviation.
The Random class that is used and instantiated creates an independent multiple
random number generators.
134. What is the difference between range & xrange?
Ans: For the most part, xrange and range are the exact same in terms of
functionality. They both provide a way to generate a list of integers for you to
use, however you please. The only difference is that range returns a Python list
object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like
range does. It creates the values as you need them with a special technique called
yielding. This technique is used with a type of object known as generators. That
means that if you have a really gigantic range you’d like to generate a list for,
say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell
phone that you are working with, as range will use as much memory as it can to
create your array of integers, which can result in a Memory Error and crash your
program. It’s a memory hungry beast.
Example:
Example:
1
2
stg='ABCD'
print(stg.lower())
Output: abcd
Example:
1
2
3
4
5
6
7
8
"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)
Output: 2.0
is: returns true when 2 operands are true (Example: “a” is ‘a’)
Help() function: The help() function is used to display the documentation string
and also facilitates you to see the help related to modules, keywords, attributes,
etc.
Dir() function: The dir() function is used to display the defined symbols.
143. Whenever Python exits, why isn’t all the memory de-allocated?
Ans:
Whenever Python exits, especially those Python modules which are having circular
references to other objects or the objects that are referenced from the global
namespaces are not always de-allocated or freed.
It is impossible to de-allocate those portions of memory that are reserved by the C
library.
On exit, because of having its own efficient clean up mechanism, Python would try
to de-allocate/destroy every other object.
143. What is a dictionary in Python?
Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one
relationship between keys and values. Dictionaries contain pair of keys and their
corresponding values. Dictionaries are indexed by keys.
The following example contains some keys. Country, Capital & PM. Their
corresponding values are India, Delhi and Modi respectively.
1
dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
1
print dict[Country]
India
1
print dict[Capital]
Delhi
1
print dict[PM]
Modi
144. How can the ternary operators be used in python?
Ans: The Ternary operator is the operator that is used to show the conditional
statements. This consists of the true or false values with a statement that has to
be evaluated for it.
Syntax:
Example:
The expression gets evaluated like if x<y else y, in this case if x<y is true then
the value is returned as big=x and if it is incorrect then big=y will be sent as a
result.
146. What does this mean: *args, **kwargs? And why would we use it?
Ans: We use *args when we aren’t sure how many arguments are going to be passed to
a function, or if we want to pass a stored list or tuple of arguments to a
function. **kwargs is used when we don’t know how many keyword arguments will be
passed to a function, or it can be used to pass the values of a dictionary as
keyword arguments. The identifiers args and kwargs are a convention, you could also
use *bob and **billy but that would not be wise.
Example:
1
2
stg='ABCD'
len(stg)
148. Explain split(), sub(), subn() methods of “re” module in Python.
Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are:
The index for the negative number starts from ‘-1’ that represents the last index
in the sequence and ‘-2’ as the penultimate index and the sequence carries forward
like the positive number.
The negative index is used to remove any new-line spaces from the string and allow
the string to except the last character that is given as S[:-1]. The negative index
is also used to show the index to represent the string in correct order.
Example:
1
2
import os
os.remove("xyz.txt")
152. What are the built-in types of python?
Ans: Built-in types in Python are as follows –
Integers
Floating-point
Complex numbers
Strings
Boolean
Built-in functions
153. What advantages do NumPy arrays offer over (nested) Python lists?
Ans:
Example:
1
2
3
4
5
6
7
a=arr.array('d', [1.1 , 2.1 ,3.1] )
a.append(3.4)
print(a)
a.extend([4.5,6.3,6.8])
print(a)
a.insert(2,3.8)
print(a)
Output:
Example:
4.6
3.1
Deep copy is used to store the values that are already copied. Deep copy doesn’t
copy the reference pointers to the objects. It makes the reference to an object and
the new object that is pointed by some other object gets stored. The changes made
in the original copy won’t affect any other copy that uses the object. Deep copy
makes execution of the program slower due to making certain copies for each object
that is been called.
Python has a multi-threading package but if you want to multi-thread to speed your
code up, then it’s usually not a good idea to use it.
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure
that only one of your ‘threads’ can execute at any one time. A thread acquires the
GIL, does a little work, then passes the GIL onto the next thread.
This happens very quickly so to the human eye it may seem like your threads are
executing in parallel, but they are really just taking turns using the same CPU
core.
All this GIL passing adds overhead to execution. This means that if you want to
make your code run faster then using the threading package often isn’t a good idea.
159. What is the process of compilation and linking in python?
Ans: The compiling and linking allows the new extensions to be compiled properly
without any error and the linking can be done only when it passes the compiled
procedure. If the dynamic loading is used then it depends on the style that is
being provided with the system. The python interpreter can be used to provide the
dynamic loading of the configuration setup files and will rebuild the interpreter.
Create a file with any name and in any language that is supported by the compiler
of your system. For example file.c or file.cpp
Place this file in the Modules/ directory of the distribution which is getting
used.
Add a line in the file Setup.local that is present in the Modules/ directory.
Run the file using spam file.o
After a successful run of this rebuild the interpreter by using the make command on
the top-level directory.
If the file is changed then run rebuildMakefile by using the command as ‘make
Makefile’.
160. What are Python libraries? Name a few of them.
Ans: Python libraries are a collection of Python packages. Some of the majorly used
python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.
Example:
1
2
a="KausalVikash python"
print(a.split())
Output: [‘KausalVikash’, ‘python’]
Example:
1
2
3
import array #importing using the original module name
import array as arr # importing using an alias name
from array import * #imports everything present in the array module
Single Inheritance – where a derived class acquires the members of a single super
class.
Multi-level inheritance – a derived class d1 in inherited from base class base1,
and d2 are inherited from base2.
Hierarchical inheritance – from one base class you can inherit any number of child
classes
Multiple inheritance – a derived class is inherited from more than one base class.
Example:
1
2
3
4
5
class Employee:
def __init__(self, name):
self.name = name
E1=Employee("abc")
print(E1.name)
Output: abc
1
2
3
4
5
6
7
import m
def monkey_f(self):
print "monkey_f()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
The output will be as below:
monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass using the
function we defined, monkey_f(), outside of the module m.
Name = xyz
172.What’s The Process To Get The Home Directory Using ‘~’ In Python?
Ans: You need to import the os module, and then just a single line would do the
rest.
import os
print (os.path.expanduser('~'))
Output:
/home/runner
You can use PyChecker, which is a static analyzer. It identifies the bugs in Python
project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding
standard.
174.When Is The Python Decorator Used?
Ans: Python decorator is a relative change that you do in Python syntax to adjust
the functions quickly.
175.Can Python be used for web client and web server side programming? And which
one is best suited to Python?
Ans: Python is best suited for web server-side application development due to its
vast set of features for creating business logic, database interactions, web server
hosting etc.
However, Python can be used as a web client-side application which needs some
conversions for a browser to interpret the client side logic. Also, note that
Python can be used to create desktop applications which can run as a standalone
application such as utilities for test automation.
176. Mention at least 3-4 benefits of using Python over the other scripting
languages such as Javascript.
Ans: Enlisted below are some of the benefits of using Python.
Similar to PERL and PHP, Python is processed by the interpreter at runtime. Python
supports Object-Oriented style of programming, which encapsulates code within
objects.
Derived from other languages, such as ABC, C, C++, Modula-3, SmallTalk, Algol-68,
Unix shell, and other scripting languages.
Python is copyrighted, and its source code is available under the GNU General
Public License (GPL).
Supports the development of many applications, from text processing to games.
Works for scripting, embedded code and compiled the code.
Detailed
180.What tools can help find bugs or perform the static analysis?
Ans: For performing Static Analysis, PyChecker is a tool that detects the bugs in
source code and warns the programmer about the style and complexity. Pylint is
another tool that authenticates whether the module meets the coding standard.
Python uses private heaps to maintain its memory. So the heap holds all the Python
objects and the data structures. This area is only accessible to the Python
interpreter; programmers can’t use it.
And it’s the Python memory manager that handles the Private heap. It does the
required allocation of the memory for Python objects.
Python employs a built-in garbage collector, which salvages all the unused memory
and offloads it to the heap space.
182.What Are The Principal Differences Between The Lambda And Def?
Ans:
183.Write A Reg Expression That Confirms An Email Id Using The Python Reg
Expression Module “Re”?
Ans: Python has a regular expression module “re.”
Check out the “re” expression that can check the email id for .com and .co.in
subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
184.What Do You Think Is The Output Of The Following Code Fragment? Is There Any
Error In The Code?
Ans:
You should know that trying to fetch a member from the list using an index that
exceeds the member count (for example, attempting to access list[10] as given in
the question) would yield an IndexError. By the way, retrieving only a slice at the
starting index that surpasses the no. of items in the list won’t result in an
IndexError. It will just return an empty list.
185. Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason
For The Same?
Ans: No, Python does not have a Switch statement, but you can write a Switch
function and then use it.
186.What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence?
Ans: Range() generates a list of numbers, which is used to iterate over for loops.
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
range(stop)
stop: It is the no. of integers to generate and starts from zero. eg. range(3) ==
[0, 1, 2].
range([start], stop[, step])
Start: It is the starting no. of the sequence.
Stop: It specifies the upper limit of the sequence.
Step: It is the incrementing factor for generating the sequence.
Points to note:
Only integer arguments are allowed.
Parameters can be positive or negative.
The range() function in Python starts from the zeroth index.
187.What Are The Optional Statements Possible Inside A Try-Except Block In Python?
Ans: There are two optional clauses you can use in the try-except block.
One of the common usages is to push values into a string with the %s format
specifier. The formatting operation in Python has the comparable syntax as the C
function printf() has.
In Python, strings are also lists of characters. We can access them using the index
which begins from zero and goes to the length minus one.
For example, in the string “Program,” the indexing happens like this:
Program 0 1 2 3 4 5
192. What Is Docstring In Python?
Ans: A docstring is a unique text that happens to be the first statement in the
following Python constructs:
1. Built-in, and
2. User-defined.
The built-in functions happen to be part of the Python language. Some of these are
print(), dir(), len(), and abs() etc.
Step-1: to begin the function, start writing with the keyword def and then mention
the function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A
colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for
execution.
The return is a Python statement which we can use in a function for sending a value
back to its caller.
Python will treat that variable as local in the function-level scope. Any changes
made to that variable will remain local and will not reflect outside the function.
This scheme also has the advantage of bringing more time and space efficiency
because it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed
accidentally during a function call. Hence, the programmers need to handle in the
code to avoid such uncertainty.
The continue statement is applicable for both the “while” and “for” loops.
Signature: id(object)
It accepts one parameter and returns a unique identifier associated with the input
object.
Please note that this type of argument syntax doesn’t allow passing a named
argument to the function.
I
am
Learning
Python
Python also does have a Main() method. But it gets executed whenever we run our
Python script either by directly clicking it or starts it from the command line.
We can also override the Python default main() function using the Python if
statement. Please see the below code.
print("Welcome")
print("__name__ contains: ", __name__)
def main():
print("Testing the main function")
if __name__ == '__main__':
main()
The output:
Welcome
__name__ contains: __main__
Testing the main function
206. What Does The __ Name __ Do In Python?
Ans: The __name__ is a unique variable. Since Python doesn’t expose the main()
function, so when its interpreter gets to run the script, it first executes the
code which is at level 0 indentation.
To see whether the main() gets called, we can use the __name__ variable in an if
clause compares with the value “__main__.”
The break statement in a nested loop causes the control to exit from the inner
iterative block.
On the contrary, the pass statement instructs to do nothing, and the remainder of
the code executes as usual.
It returns the string denoting a character whose Unicode code point is an integer.
For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the
string ‘Ҽ’.
>>> ord("z")
122
213. What Is Rstrip() In Python?
Ans: Python provides the rstrip() method which duplicates the string but leaves out
the whitespace characters from the end.
The rstrip() escapes the characters from the right end based on the argument value,
i.e., a string mentioning the group of characters to get excluded.
str.rstrip([char sequence/pre>
#Example
test_str = 'Programming '
# The trailing whitespaces are excluded
print(test_str.rstrip())
It returns True if all characters in the string are of alphabet type, else it
returns False.
#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())
The output:
#Example
str = 'lEaRn pYtHoN'
print(str.title())
The output:
Learn Python
Now, check out some general purpose Python interview questions.
The tests confirmed that PyPy is nearly five times faster than the CPython. It
currently supports Python 2.7.
For example, many of the Python operations execute as atomic such as calling the
sort() method on a list.
This heap manager does the allocation/de-allocation of heap space for objects.
They are mutable and hence will not change. The values associated with the keys can
be of any Python types.
A Python class is a blueprint for creating the objects. It defines member variables
and gets their behavior associated with them.
We can make it by using the keyword “class.” An object gets created from the
constructor. This object represents the instance of the class.
The common code rests with the base class, and the child class objects can access
it via inheritance. Check out the below example.
desk = Desktop()
print(desk.processor, desk.os, desk.ram)
lap = Laptop()
print(lap.processor, lap.os, lap.ram)
The output:
def get_PC(self):
return "%s cpu & %s ram" % (self.processor, self.ram)
class Tablet():
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
def get_Tablet(self):
return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor,
self.PC.ram, self.make)
if __name__ == "__main__":
tab = Tablet("i7", "16 GB", "Intel")
print(tab.get_Tablet())
The output is:
On the contrary, exceptions happen due to the occurrence of an external event which
interrupts the normal flow of the program.
try:
print("Executing code in the try block")
print(exception)
except:
print("Entering in the except block")
finally:
print("Reached to the final block")
The output is:
For example, if we want the user to enter only odd numbers, else will raise an
exception.
Python library has a no. of iterators. For example, a list is also an iterator and
we can start a for loop over it.
print(next(generate()))
The output is:
In the example below, we’ve written a simple closure for multiplying numbers.
def multiply_number(num):
def product(number):
'product() here is a closure'
return num * number
return product
num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))
num_6 = multiply_number(6)
print(num_6(1))
The output is:
22
48
6
239. What Are Decorators In Python?
Ans: Python decorator gives us the ability to add new behavior to the given objects
dynamically. In the example below, we’ve written a simple example to display a
message pre and post the execution of a function.
def decorator_sample(func):
def decorator_hook(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return decorator_hook
@decorator_sample
def product(x, y):
"Function to multiply two numbers."
return x * y
print(product(3, 3))
The output is:
However, we can take values of any kind. For distinguishing the data pairs, we can
use a comma(“,”) and keep the whole stuff inside curly braces({…}).
We can use this object directly in the “for” loops or transform it into a list of
tuples by calling the list() method. It has the following signature:
enumerate(iterable, to_begin=0)
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its default value is 0
# Example - enumerate function
alist = ["apple","mango", "orange"]
astr = "banana"
print(list(enumerate(alist)) )
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))
The output is:
Python maintains a symbol table to keep all necessary information about a program.
This info includes the names of variables, methods, and classes used by the
program.
All the information in this table remains in the global scope of the program and
Python allows us to retrieve it using the globals() method.
Signature: globals()
Arguments: None
# Example: globals() function
x = 9
def fn():
y = 3
z = y + x
# Calling the globals() method
z = globals()['x'] = z
return z
# Test Code
ret = fn()
print(ret)
The output is:
12
252. Why Do You Use The Zip() Method In Python?
Ans: The zip method lets us map the corresponding index of multiple containers so
that we can use them using as a single unit.
Signature:
zip(*iterators)
Arguments:
Python iterables or collections (e.g., list, string, etc.)
Returns:
A single iterator object with combined mapped values
# Example: zip() function
The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28,
'Accounts'), ('tom', 32, 'HR')}
253. What Are Class Or Static Variables In Python Programming?
Ans: In Python, all the objects share common class or static variables.
But the instance or non-static variables are altogether different for different
objects.
The programming languages like C++ and Java need to use the static keyword to make
a variable as the class variable. However, Python has a unique way to declare a
static variable.
All names initialized with a value in the class declaration becomes the class
variables. And those which get assigned values in the class methods becomes the
instance variables.
# Example
class Test:
aclass = 'programming' # A class variable
def __init__(self, ainst):
self.ainst = ainst # An instance variable
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
print(test2.ainst)
programming
programming
1
2
programming
Let’s now answer some advanced-level Python interview questions.
x, y = 35, 75
smaller = x if x < y else y
print(smaller)
255. What Does The “Self” Keyword Do?
Ans: The self is a Python keyword which represents a variable that holds the
instance of an object.
copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.
257: What Is The Purpose Of Docstrings In Python?
Ans: In Python, the docstring is what we call as the docstrings. It sets a process
of recording Python functions, modules, and classes.
258. Which Python Function Will You Use To Convert A Number To A String?
Ans: For converting a number into a string, you can use the built-in function
str(). If you want an octal or hexadecimal representation, use the inbuilt
function oct() or hex().
259. How Do You Debug A Program In Python? Is It Possible To Step Through The
Python Code?
Ans: Yes, we can use the Python debugger (pdb) to debug any Python program. And if
we start a program using pdb, then it let us even step through the code.
260. List Down Some Of The PDB Commands For Debugging Python Programs?
Ans: Here are a few PDB commands to start debugging Python code.
You need to define a trace callback method and pass it to the settrace() function.
The callback should specify three arguments as shown below.
import sys
def demo2():
print 'in demo2()'
def demo1():
print 'in demo1()'
demo2()
sys.settrace(trace_calls)
demo1()
Apart from that, there are certain rules we must follow to name one:
Apart from that, there are certain rules we must follow to name one:
>>> ‘AyuShi’.lower()
‘ayushi’
>>> ‘AyuShi’.upper()
‘AYUSHI’
Also, to check if a string is in all uppercase or all lowercase, we use the methods
isupper() and islower().
>>> ‘AyuShi’.isupper()
False
>>> ‘AYUSHI’.isupper()
True
>>> ‘ayushi’.islower()
True
>>> ‘@yu$hi’.islower()
True
>>> ‘@YU$HI’.isupper()
True
The help() function displays the documentation string and help for its argument.
copy(x)
>>> 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__’]
>>> mydict={‘a’:1,‘b’:2,‘c’:3,‘e’:5}
>>> mydict.keys()
dict_keys([‘a’, ‘b’, ‘c’, ‘e’])
268. How will you check if all characters in a string are alphanumeric?
Ans: For this, we use the method isalnum().
269. With Python, how do you find out which directory you are currently in?
Ans: To find this, we use the function/method getcwd(). We import it from the
module os.
>>> import os
>>> os.getcwd()
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’
>>> type(os.getcwd)
<class ‘builtin_function_or_method’>
>>> os.chdir(‘C:\\Users\\lifei\\Desktop’)
>>> os.getcwd()
‘C:\\Users\\lifei\\Desktop’
>>> a=[1,2,4]
Now, we use the method insert. The first argument is the index at which to insert,
the second is the value to insert.
>>> a.insert(2,3)
>>> a
[1, 2, 3, 4]
>>> a.reverse()
>>> a
[4, 3, 2, 1]
>>> a[::-1]
>>> a
[1, 2, 3, 4]
This gives us the original list because we already reversed it once. However, this
does not modify the original list to reverse it.
>>> if 3>1:
print(“Hello”)
print(“Goodbye”)
Hello
Goodbye
274. Will the do-while loop work if you don’t end it with a semicolon?
Ans: Trick question! Python does not support an intrinsic do-while loop. Secondly,
to terminate do-while loops is a necessity for languages like C++.
275. In one line, show us how you’ll get the max alphabetical character from a
string.?
Ans: For this, we’ll simply use the max function.
>>> max(‘flyiNg’)
‘y’
The following are the ASCII values for all the letters of this string-
f- 102
l- 108
y- 121
i- 105
N- 78
g- 103
>>> max(‘fly{}iNg’)
‘}’
(Bonus: } – 125)
277. Can you name ten built-in functions in Python and explain each in brief?
Ans: Ten Built-in Functions, you say? Okay, here you go.
>>> complex(3.5,4)
(3.5+4j)
>>> eval(‘print(max(22,22.0)-min(2,3))’)
20
>>> hash(3.7)
644245917
>>> hex(14)
‘0xe’
‘7’
len()- Returns the length of an object.
>>> len(‘Ayushi’)
6
>>> locals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {},
‘__builtins__’: <module ‘builtins’ (built-in)>, ‘a’: 2, ‘b’: 3}
>>> file=open(‘tabs.txt’)
278. How will you convert a list into a string?
Ans: We will use the join() method for this.
>>> nums=[‘one’,‘two’,‘three’,‘four’,‘five’,‘six’,‘seven’]
>>> s=‘ ‘.join(nums)
>>> s
o/p= ‘one two three four five six seven’
>>> list=[1,2,1,3,4,2]
>>> set(list)
{1, 2, 3, 4}
To create a thread, we create a class that we make override the run method of the
thread class. Then, we instantiate it.
A thread that we just created is in the new state. When we make a call to start()
on it, it forwards the threads for scheduling. These are in the ready state.
When execution begins, the thread is in the running state.
Calls to methods like sleep() and join() make a thread wait. Such a thread is in
the waiting/blocked state.
When a thread is done waiting or executing, other waiting threads are sent for
scheduling.
A running thread that is done executing terminates and is in the dead state.
>>> 7//2
3
>>> 2**10
1024
Finally, % is for modulus. This gives us the value left after the highest
achievable division.
>>> 13%7
6
>>> 3.5%1.5
0.5
282. What are membership operators?
Ans: With the operators ‘in’ and ‘not in’, we can confirm if a value is a member
in another.
>>> 10 is ’10’
False
Ans:
>>> 3|2
3
>>> 3^2
1
Binary One’s Complement (~) This returns the one’s complement of a value.
>>> ~2
-3
Binary Left-Shift (<<) This shifts the bits to the left by the specified amount.
>>> 1<<2
4
Here, 001 was shifted to the left by two places to get 100, which is binary for 4.
>>> 4>>2
1
>>> a=7.0
>>>
Strings – A string is a sequence of characters. We declare it using single or
double quotes.
>>> colors=[‘red’,‘green’,‘blue’]
>>> type(colors)
<class ‘list’>
>>> name=(‘Ayushi’,‘Sharma’)
>>> name[0]=‘Avery’
Traceback (most recent call last):
name[0]=’Avery’
>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> type(squares)
<class ‘dict’>
>>> type({})
<class ‘dict’>
>>> int(‘227’)
227
>>> type(‘227’)
<class ‘str’>
>>> type(int(‘227’))
<class ‘int’>
The input() function takes, as an argument, the text to be displayed for the task:
But if you have paid attention, you know that it takes input in the form of a
string.
>>> type(a)
<class ‘str’>
>>> a*=2
>>> a
’77’
>>> a*=2
>>> a
14
Less than (<) If the value on the left is lesser, it returns True.
>>> ‘hi’<‘Hi’
False
Greater than (>) If the value on the left is greater, it returns True.
>>> 1.1+2.2>3.3
True
Less than or equal to (<=) If the value on the left is lesser than or equal to, it
returns True.
>>> 3.0<=3
True
Greater than or equal to (>=) If the value on the left is greater than or equal to,
it returns True.
>>> True>=False
True
>>> {1,3,2,2}=={1,2,3}
True
Not equal to (!=) If the two values are unequal, it returns True.
>>> True!=0.1
True
>>> False!=0.1
True
>>> a=7
>>> a+=1
>>> a
8
>>> a-=1
>>> a
7
>>> a*=2
>>> a
14
>>> a/=2
>>> a
7.0
>>> a**=2
>>> a
49.0
>>> a//=3
>>> a
16.0
>>> a%=4
>>> a
0.0
>>> 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.
>>> list(zip((‘a’,‘b’,‘c’),(1,2,3)))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
First –
295. If you are ever stuck in an infinite loop, how will you break out of it?
Ans: For this, we press Ctrl+C. This interrupts the execution. Let’s create an
infinite loop to demonstrate this.
7
7
counterfunc(7)
while(n==7):print(n)
KeyboardInterrupt
>>> tuple=(1,2,4)
>>> tuple
(1, 2, 4)
>>> 2+4j
(2+4j)
Mutable objects – Those that let you modify their contents. Examples of these are
lists, sets, and dicts. Iterations on such objects are slower.
>>> [2,4,9]
[2, 4, 9]
>>> dict1={1:1,2:2}
>>> dict1
{1: 1, 2: 2}
While two equal immutable objects’ reference variables share the same address, it
is possible to create two mutable objects with the same content.
>>> ‘,’.join(‘12345’)
‘1,2,3,4,5’
>>> ‘1,2,3,4,5’.split(‘,’)
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
Sometimes, when we want to iterate over a list, a few methods come in handy.
a. filter()
b. map()
Sometimes, when we want to iterate over a list, a few methods come in handy.
a. filter()
b. map()
>>> list=[3,4,5,6,7]
>>> del list[3]
>>> list
[3, 4, 5, 7]
>>> list.remove(5)
>>> list
[3, 4, 7]
While del lets us delete an element at a certain index, remove() lets us remove an
element by its value.
a. filter()
Filter lets us filter in some values based on conditional logic.
b. map()
>>> file=open(‘tabs.txt’,‘w’)
This opens the file in writing mode. You should close it once you’re done.
>>> file.close()
>>> list1,list2=[1,2,3],[5,6,7,8]
This is how append() works:
>>> list1.append(4)
>>> list1
[1, 2, 3, 4]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
read-only – ‘r’
write-only – ‘w’
read-write – ‘rw’
append – ‘a’
We can open a text file with the option ‘t’. So to open a text file to read it, we
can use the mode ‘rt’. Similarly, for binary files, we use ‘b’.
>>> list=[1,2,3,4,5
>>> list.pop(–1)
5
>>> list
[1, 2, 3, 4]
>>> chr(52)
‘4’
>>> chr(49)
‘1’
>>> chr(67)
‘C’
312. Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”?
Ans: I can think of three ways to do this.
Using join-
Using replace()-
313. How do you get the current working directory using Python?
Ans: Working on software with Python, you may need to read and write files from
various directories. To find out which directory we’re presently working under, we
can borrow the getcwd() method from the os module.
>>> import os
>>> os.getcwd()
‘C:\\Users\\Raj\\AppData\\Local\\Programs\\Python\\Python37-32’
os
os.path
shutil
315. Explain the uses of the modules sqlite3, ctypes, pickle, traceback, and
itertools.
sqlite3- Helps with handling databases of type SQLite
ctypes- Lets create and manipulate C data types in Python
pickle- Lets put any data structure to external files
traceback- Allows extraction, formatting, and printing of stack traces
itertools– Supports working with permutations, combinations, and other useful
iterables.
Let’s say you have a class ClassA which contains a method methodA defined as:
319. What does the Python nonlocal statement do (in Python 3.0 and later)?
Ans: In short, it lets you assign values to a variable in an outer (but non-global)
scope.
The nonlocal statement causes the listed identifiers to refer to previously bound
variables in the nearest enclosing scope excluding globals.
For example the counter generator can be rewritten to use this so that it looks
more like the idioms of languages with closures.
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
320. What are the wheels and eggs? What is the difference?
Ans:
Wheel and Egg are both packaging formats that aim to support the use case of
needing an install artifact that doesn’t require building or compilation, which can
be costly in testing and production workflows.
The Egg format was introduced by setuptools in 2004, whereas the Wheel format was
introduced by PEP 427 in 2012.
Wheel is currently considered the standard for built and binary packaging for
Python.
Dead asset elimination. This is killer, especially for CSS rules. You only build
the images and CSS into your dist/ folder that your application actually needs.
Easier code splitting. For example, because you know that your file Homepage.js
only requires specific CSS files, Webpack could easily build a homepage.css file to
greatly reduce initial file size.
You control how assets are processed. If an image is below a certain size, you
could base64 encode it directly into your Javascript for fewer HTTP requests. If a
JSON file is too big, you can load it from a URL. You can require('./style.less')
and it’s automaticaly parsed by Less into vanilla CSS.
Stable production deploys. You can’t accidentally deploy code with images missing,
or outdated styles.
Webpack will slow you down at the start, but give you great speed benefits when
used correctly. You get hot page reloading. True CSS management. CDN cache busting
because Webpack automatically changes file names to hashes of the file contents,
etc.
Webpack is the main build tool adopted by the React community.
323. Name some plugins you think are very important and helpful?
Ans:
The require('logo.png') source code never actually gets executed in the browser
(nor in Node.js). Webpack builds a new Javascript file, replacing require() calls
with valid Javascript code, such as URLs. The bundled file is what’s executed by
Node or the browser.
"<b><i>Hello</i></b>"
Answer:
Consider:
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
@makebold
@makeitalic
def log(s):
return s
class C:
@staticmethod
def f(arg1, arg2, ...): ...
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. Its
definition follows Sub class, not Parent class, via inheritance.
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
If your method accesses other variables/methods in your class then use
@classmethod.
328. What’s the difference between a Python module and a Python package?
Ans: Any Python file is a module, its name being the file’s base name without
the .py extension.
import my_module
A package is a collection of Python modules: while a module is a single Python
file, a package is a directory of Python modules containing an additional init.py
file, to distinguish a package from a directory that just happens to contain a
bunch of Python scripts. Packages can be nested to any depth, provided that the
corresponding directories contain their own init.py file.
Packages are modules too. They are just packaged up differently; they are formed by
the combination of a directory plus init.py file. They are modules that can contain
other modules.
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure
that only one of your ‘threads’ can execute at any one time. A thread acquires the
GIL, does a little work, then passes the GIL onto the next thread. This happens
very quickly so to the human eye it may seem like your threads are executing in
parallel, but they are really just taking turns using the same CPU core. All this
GIL passing adds overhead to execution.
So to achieve the desired effect your best choice is to return a tuple containing
the multiple results:
x, y = 'old-value', 99
x, y = func2(x, y)
print(x, y)
333. What is the purpose of the single underscore “_” variable in Python?
Ans: has 4 main conventional uses in Python:
Ans:
Indeed, CPython’s sets are implemented as something like dictionaries with dummy
values (the keys being the members of the set), with some optimization(s) that
exploit this lack of values.
So basically a set uses a hashtable as its underlying data structure. This explains
the O(1) membership checking, since looking up an item in a hashtable is an O(1)
operation, on average.
Also, it worth to mention when people say sets have O(1) membership-checking, they
are talking about the average case. In the worst case (when all hashed values
collide) membership-checking is O(n).
In Python,** method resolution order** defines the order in which the base classes
are searched when executing a method. First, the method or attribute is searched
within a class and then it follows the order we specified while inheriting. This
order is also called Linearization of a class and set of rules are called MRO
(Method Resolution Order). While inheriting from another class, the interpreter
needs a way to resolve the methods that are being called via an instance. Thus we
need the method resolution order.
Python resolves method and attribute lookups using the C3 linearisation of the
class and its parents. The C3 linearisation is neither depth-first nor breadth-
first in complex multiple inheritance hierarchies.
336. What is the difference between old style and new style classes in Python?
Ans: 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.
Classic classes do a depth first search from left to right. Stop on first match.
They do not have the mro attribute.
New-style classes MRO is more complicated to synthesize in a single English
sentence. One of its properties is that a Base class is only searched for once all
its Derived classes have been. They have the mro attribute which shows the search
order.
Some other notes:
New style class objects cannot be raised unless derived from Exception.
Old style classes are still marginally faster for attribute lookup.
Pass by value: Copy of the actual object is passed. Changing the value of the copy
of the object will not change the value of the original object.
Pass by reference: Reference to the actual object is passed. Changing the value of
the new object will change the value of the original object.
In Python, arguments are passed by reference, i.e., reference to the actual object
is passed.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
1
Syntax for bool() method: bool([a])
1
template.format(p0, p1, ..., k0=v0, k1=v1, ...)
Python String Replace: This method is mainly used to return a copy of the string in
which all the occurrence of the substring is replaced by another substring.
1
str.replace(old, new [, count])
sys module
OS module
random module
collection module
JSON
Math module
Example:
1
2
str = 'XYZ'
print(str.lower())
Output:
1
xyz
Example:
1
2
3
4
5
x = arr.array('d', [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3])
print(x.pop())
print(x.pop(3))
x.remove(1.0)
print(a)
Output:
1
2
3
7.3
4.8
array(‘d’, [2.2, 3.4, 5.2, 6.6])
344. What is Try Block?
A block which is preceded by the try keyword is known as a try block
Syntax:
1
2
3
try{
//statements that may cause an exception
}
1
Module == PyImport_ImportModule("<modulename>");
1
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
1
2
3
4
def pyfun(r):
for a in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfun(9)
Output:
1
2
3
4
5
6
7
8
9
*
***
*****
*******
*********
***********
*************
***************
*****************
349. Write a program to check whether the given number is prime or not?
Ans: The code to check prime number is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# program to check the number is prime or not
n1 = 409
# num1 = int(input("Enter any one number: "))
# prime number is greater than 1
if n1 > 1:
# check the following factors
for x is in range of(2,num1):
if (n1 % x) == 0:
print(n1,"is not a prime number")
print(x,"times",n1//x,"is",num)
break
else:
print(n1,"is a prime number")
# if input number is smaller than
# or equal to the value 1, then it is not prime number
else:
print(n1,"is not a prime number")
Output:
1
409 is a prime number
350. Write Python code to check the given sequence is a palindrome or not?
Ans:
1
2
3
4
5
6
7
8
9
10
11
# Python code to check a given sequence
# is palindrome or not
my_string1 = 'MOM'
My_string1 = my_string1.casefold()
# reverse the given string
rev_string1 = reversed(my_string1)
# check whether the string is equal to the reverse of it or not
if list(my_string1) == list(rev_string1):
print("It is a palindrome")
else:
print("It is not a palindrome")
Output:
1
it is a palindrome
1
2
3
4
list = [ "13", "16", "1", "5" , "8"]
list = [int(x) for x in the list]
list.sort()
print(list)
Output:
1
1, 5, 8, 13, 16