In this Python Interview Questions blog, I will introduce you to the most frequently asked questions in Python interviews. These sample questions are framed by experts. We have tried to give correct answers for all the questions. Candidates must read this section, Then by heart the questions and answers.

If there is any Python interview question that have been asked to you, kindly post it in the the comment section.


 

1. What are the key features of Python?

Ans:

If it makes for an introductory language to programming, Python must mean something. These are its qualities:

  • Interpreted
  • Dynamically-typed
  • Object-oriented
  • Concise and simple
  • Free
  • Has a large community

2. Differentiate between deep and shallow copy.

Ans:

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:

>>> import copy
>>> b=copy.deepcopy(a)
Python deep copy

Python deep copy

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

>>> b=copy.copy(a)
Python shallow copy

Python shallow copy

3. Differentiate between lists and tuples.

Ans:

The major difference is that a list is mutable, but a tuple is immutable. Examples:

>>> mylist=[1,3,3]
>>> mylist[1]=2
>>> mytuple=(1,3,3)
>>> mytuple[1]=2
Traceback (most recent call last):
File "<pyshell#97>", line 1, in
mytuple[1]=2

TypeError: ‘tuple’ object does not support item assignment

4. Explain the ternary operator in Python.

Ans:

Unlike C++, we don’t have ?: in Python, but we have this:
[on true] if [expression] else [on false]
If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed.
Below is how you would use it:

>>> a,b=2,3
>>> min=a if a>>> min
2
>>> print("Hi") if a

Out put:

Hi

5. How is multithreading achieved in Python?

Ans:

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

6. Explain inheritance.

Ans:

When one class inherits from another, it is said to be the child/derived/sub class inheriting from the parent/base/super class. It inherits/gains all members (attributes and methods).
Inheritance lets us reuse our code, and also makes it easier to create and maintain applications. Python supports the following kinds of inheritance:
Single Inheritance– A class inherits from a single base class.
Multiple Inheritance– A class inherits from multiple base classes.
Multilevel Inheritance– A class inherits from a base class, which, in turn, inherits from another base class.
Hierarchical Inheritance– Multiple classes inherit from a single base class.
Hybrid Inheritance– Hybrid inheritance is a combination of two or more types of inheritance.

7. What is Flask?

Ans:
Flask, as we’ve previously discussed, is a web microframework for Python. It is based on the ‘Werkzeug, Jinja 2 and good intentions’ BSD license. Two of its dependencies are Werkzeug and Jinja2. This means it has around no dependencies on external libraries. Due to this, we can call it a light framework.
A session uses a signed cookie to allow for the user to look at and modify session contents. It will remember information from one request to another. However, to modify a session, the user must have the secret key Flask.secret_key.

8. How is memory managed in Python?

Ans:
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.

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

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

>>> import copy
>>> help(copy.copy)

Help on function copy in module copy:

copy(x)
Shallow copy operation on arbitrary Python objects.
See the module’s __doc__ string for more info.
The dir() function displays all the members of an object(any kind).
>>> 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__’]

10. Whenever you exit Python, is all memory de-allocated?

Ans:

The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren’t always freed on exiting Python.
Plus, it is impossible to de-allocate portions of memory reserved by the C library.



 

11. What is monkey patching?

Ans:

Dynamically modifying a class or module at run-time.

>>> class A:
def func(self):
print("Hi")
>>> def monkey(self):
print "Hi, monkey"
>>> m.A.func = monkey
>>> a = m.A()
>>> a.func()

Out put:
Hi, monkey

12. What is a dictionary in Python?

Ans:

A dictionary is something I have never seen in other languages like C++ or Java. It holds key-value pairs.
>>> roots={25:5,16:4,9:3,4:2,1:1}
>>> type(roots)
<class ‘dict’>
>>> roots[9]

A dictionary is mutable, and we can also use a comprehension to create it.
>>> roots={x**2:x for x in range(5,0,-1)}
>>> roots

Out put:

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

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

Ans:

In cases when we don’t know how many arguments will be passed to a function, like when we want to pass a list or a tuple of values, we use *args.
>>> def func(*args):
for i in args:
print(i)
>>> func(3,2,1,4,7)
3
2
1
4
7
**kwargs takes keyword arguments when we don’t know how many there will be.
>>> def func(**kwargs):
for i in kwargs:
print(i,kwargs[i])
>>> func(a=1,b=2,c=7)
a.1
b.2
c.7
The words args and kwargs are convention, and we can use anything in their place.

14. Write Python logic to count the number of capital letters in a file.

Ans:

>> import os
>>> os.chdir('C:\Users\lifei\Desktop')
>>> with open('Today.txt') as today:
count=0
for i in today.read():
if i.isupper():
count+=1
print(count)

Out put:

26

15. What are negative indices?

Ans:

Let’s take a list for this.

>> mylist=[0,1,2,3,4,5,6,7,8]

A negative index, unlike a positive one, begins searching from the right.

>>> mylist[-3]

This also helps with slicing from the back:

>> mylist[-6:-1]

Out put:

[3, 4, 5, 6, 7]

16. How would you randomize the contents of a list in-place?

Ans:

For this, we’ll import the function shuffle() from the module random.

>>> from random import shuffle
>>> shuffle(mylist)
>>> mylist

Out put:
[3, 4, 8, 0, 5, 7, 6, 2, 1]

17. Explain join() and split() in Python.

Ans:
join() lets us join characters from a string together by a character we specify.

>>> ','.join('12345')
‘1,2,3,4,5’
split() lets us split a string around the character we specify.
>>> '1,2,3,4,5'.split(',')

Out put:
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

18. Is Python case-sensitive?

Ans:
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.

>>> myname='Ayushi'
>>> Myname

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

19. How long can an identifier be in Python?

Ans:

In Python, an identifier can be of any length. Apart from that, there are certain rules we must follow to name one:
It can only begin with an underscore or a character from A-Z or a-z.
The rest of it can contain anything from the following: A-Z/a-z/_/0-9.
Python is case-sensitive, as we discussed in the previous question.
Keywords cannot be used as identifiers. Python has the following keywords:

and

def

False

import

not

True

as

del

finally

in

or

try

assert

elif

for

is

pass

while

break

else

from

lambda

print

with

class

except

global

None

raise

yield

continue

exec

if

nonlocal

return

 

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

Ans:

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

>>> ' Ayushi '.lstrip()
‘Ayushi ‘

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

>> ' Ayushi '.rstrip()

‘ Ayushi’




 

21. How would you convert a string into lowercase?

Ans:

We use the lower() method for this.

> 'AyuShi'.lower()
‘ayushi’

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

>>> '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

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

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

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

True

22. What is the pass statement in Python?

Ans:

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

>>> def func(*args):
pass
>>>

Similarly, the break statement breaks out of a loop.

>>> for i in range(7):
if i==3: break
print(i)
0
1
2

Finally, the continue statement skips to the next iteration.

>> for i in range(7):
if i==3: continue
print(i)

0

1
2
4
5
6

23. What is a closure in Python?

Ans:

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

>>> def A(x):
def B():
print(x)
return B
>>> A(7)()

24. Explain the //, %, and ** operators in Python.

Ans:
The // operator performs floor division. It will return the integer part of the result on division.

>>> 7//2

3
Normal division would return 3.5 here.
Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.

>> 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

25. How many kinds of operators do we have in Python? Explain arithmetic operators.

Ans:

This type of Python Interview Questions and Answers can decide your knowledge in Python. Answer the Python Interview Questions with some good Examples.
Here in Python, we have 7 kinds of operators: arithmetic, relational, assignment, logical, membership, identity, and bitwise.
We have seven arithmetic operators. These allow us to perform arithmetic operations on values:
Addition (+) This adds two values.

>>> 7+8
15
Subtraction (-) This subtracts he second value from the first.

>>> 7-8
-1
Multiplication (*) This multiplies two numbers.

>>> 7*8
56
Division (/) This divides the first value by the second.
>>> 7/8
0.875
>>> 1/1
1.0

26. Explain relational operators in Python.

Ans:

Relational operators compare values.
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
This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies.
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
Equal to (==) If the two values are equal, it returns 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

27. What are assignment operators in Python?

Ans:

This one is an Important Interview question in Python Interview.
We can combine all arithmetic operators with the assignment symbol.
>>> 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

28. Explain logical operators in Python.

Ans:

We have three logical operators- and, or, not.
>>> False and True
False
>>> 7<7 or True
True
>>> not 2==2
False

29. What are membership operators?

Ans:

With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.
>>> ‘me’ in ‘disappointment’
True
>>> ‘us’ not in ‘disappointment’
True

30. Explain identity operators in Python.

Ans:

This is one of the very commonly asked Python Interview Questions and answer it with examples.
The operators ‘is’ and ‘is not’ tell us if two values have the same identity.
>>> 10 is ’10’
False
>>> True is not False
True


 

31. Finally, tell us about bitwise operators in Python.

Ans:

These operate on values bit by bit.
AND (&) This performs & on each bit pair.
>>> 0b110 & 0b010
2
OR (|) This performs | on each bit pair.
>>> 3|2
3
XOR (^) This performs an exclusive-OR operation on each bit pair.
>>> 3^2
1
4. 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.
Binary Right-Shift (>>)
>>> 4>>2

32. How would you work with numbers other than those in the decimal number system?

Ans:

With Python, it is possible to type numbers in binary, octal, and hexadecimal.
Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.
>>> int(0b1010)
10
To convert a number into its binary form, we use bin().
>>> bin(0xf)
‘0b1111’
Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O.
>>> oct(8)
‘0o10’
Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X.
>>> hex(16)
‘0x10’
>>> hex(15)
‘0xf’

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

Ans:

Be specific in these type of Python Interview Questions and Answers.
For this, we use the function keys().
>>> mydict={‘a’:1,’b’:2,’c’:3,’e’:5}
>>> mydict.keys()
dict_keys([‘a’, ‘b’, ‘c’, ‘e’])

34. Why are identifier names with a leading underscore disparaged?

Ans:

Since Python does not have a concept of private variables, it is a convention to use leading underscores to declare a variable private. This is why we mustn’t do that to variables we do not want to make private.

35. How can you declare multiple assignments in one statement?

Ans:

There are two ways to do this:
>>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively
>>> a=b=c=3 #This assigns 3 to a, b, and c

36. What is tuple unpacking?

Ans:

First, let’s discuss tuple packing. It is a way to pack a set of values into a tuple.
>>> mytuple=3,4,5
>>> mytuple
(3, 4, 5)
This packs 3, 4, and 5 into mytuple.
Now, we will unpack the values from the tuple into variables x, y, and z.
>>> x,y,z=mytuple
>>> x+y+z

37. As a tester what should be your approach when requirements change continuously?

Ans:

When requirement keeps changing, continuously agile tester should take following approach

  • Write generic test plans and test cases, which focuses on the intent of the requirement rather than its exact details
  • To understand the scope of change, work closely with the product owners or business analyst
  • Make sure team understand the risks involved in changing requirements especially at the end of the sprint
  • Until the feature is stable, and the requirements are finalized, it is best to wait if you are going to automate the feature
  • Changes can be kept to a minimum by negotiating or implement the changes in the next sprint

38. List out the pros and cons of exploratory testing (used in Agile) and scripted testing?

Ans:

 

Pros

Cons

Exploratory Testing

– It requires less preparation- Easy to modify when requirement changes- Works well when documentation is scarce

– Presenting progress and Coverage to project management is difficult

Scripted Testing

– In case testing against legal or regulatory requirements it is very useful

– Test preparation is usually time-consuming- Same steps are tested over and again- When requirement changes it is difficult to modify

39. Explain the difference between Extreme programming and Scrum?

Ans:

Scrum

Extreme Programing (XP)

– Scrum teams usually have to work in iterations called sprints which usually last up to two weeks to one month long

– XP team works in iteration that last for one or two weeks

– Scrum teams do not allow change into their sprints

– XP teams are more flexible and change their iterations

– In scrum, the product owner prioritizes the product backlog but the team decides the sequence in which they will develop the backlog items

– XP team work in strict priority order, features developed are prioritized by the customer

– Scrum does not prescribe any engineering practices

– XP does prescribe engineering practices

40. What is an epic, user stories and task?

Ans:

Epic: A customer described software feature that is itemized in the product backlog is known as epic. Epics are sub-divided into stories
User Stories: From the client perspective user stories are prepared which defines project or business functions, and it is delivered in a particular sprint as expected.
Task: Further down user stories are broken down into different task

Agile Testing

Agile Testing



 

41. Explain what is re-factoring?

Ans:

To improve the performance, the existing code is modified; this is re-factoring. During re-factoring the code functionality remains same.

42. Explain how you can measure the velocity of the sprint with varying team capacity?

Ans:

When planning a sprint usually, the velocity of the sprint is measured on the basis of professional judgement based on historical data. However, the mathematical formula used to measure the velocity of the sprint are,
first – completed story points X team capacity: If you measure capacity as a percentage of a 40 hours weeks
Second – completed story points / team capacity: If you measure capacity in man-hours
For our scenario second method is applicable.

43. Mention the key difference between sprint backlog and product backlog?

Ans:

Product backlog: It contains a list of all desired features and is owned by the product owner
Sprint backlog: It is a subset of the product backlog owned by development team and commits to deliver it in a sprint. It is created in Sprint Planning Meeting

44. In Agile mention what is the difference between the Incremental and Iterative development?

Ans:

Iterative: Iterative method is a continuous process of software development where the software development cycles are repeated (Sprint & Releases) till the final product is achieved.
Release 1: Sprint 1, 2… n
Release n: Sprint 1, 2….n
Incremental: Incremental development segregates the system functionality into increments or portions. In each increment, each segment of functionality is delivered through cross-discipline work, from the requirements to the deployment.

45. Explain what is Spike and Zero sprint in Agile? What is the purpose of it?

Ans:

Sprint Zero: It is introduced to perform some research before initiating the first sprint. Usually this sprint is used during the start of the project for activities like setting development environment, preparing product backlog and so on.
Spikes: Spikes are type of stories that are used for activities like research, exploration, design and even prototyping. In between sprints, you can take spikes for the work related to any technical or design issue. Spikes are of two types Technical Spikes and Functional Spikes.

46. What is test driven development?

Ans:

Test driven development or TDD is also known as test-driven design. In this method, developer first writes an automated test case which describes new function or improvement and then creates small codes to pass that test, and later re-factors the new code to meet the acceptable standards.

47. Prototypes and Wireframes are widely used as part of?

Ans:

Prototypes and Wireframes are prototypes that are widely used as part of Empirical Design

48. Explain what is Application Binary Interface?

Ans:

Across different system platforms and environments a specification defining requirements for portability of applications in binary form is known as Application Binary Interface

49. Explain in Agile, burn-up and burn-down chart?

Ans:
To track the project progress burnup and burn down, charts are used
Burnup Chart: It shows the progress of stories done over time
Burndown Chart: It shows how much work was left to do overtime

50. Explain what is Scrum ban?

Ans:
Scrum ban is a software development model based on Scrum and Kanban. It is specially designed for project that requires frequent maintenance, having unexpected user stories and programming errors. Using these approach, the team’s workflow is guided in a way that allows minimum completion time for each user story or programming error.




 

51. What is story points/efforts/ scales?

Ans:

It is used to discuss the difficulty of the story without assigning actual hours. The most common scale used is a Fibonacci sequence ( 1,2,3,5,8,13,….100) although some teams use linear scale (1,2,3,4….), Powers of 2 (1,2,4,8……) and cloth size (XS, S ,M,L, XL)

52. Explain what is tracer bullet?

Ans:

The tracer bullet is a spike with the current architecture, the current set of best practices, current technology set which results in production quality code. It is not a throw away code but might just be a narrow implementation of the functionality.

53. What is a test stub?

Ans:

A test stub is a small code that replaces an undeveloped or fully developed component within a system being tested. Test stub is designed in such a way that it mimics the actual component by generating specifically known outputs and substitute the actual component.

54. What are the differences between RUP (Rational Unified Process) and Scrum methodologies?

Ans:

RUP

SCRUM

– Formal Cycle is defined across four phases, but some workflows can be concurrent

– Each sprint is a complete cycle

– Formal project plan, associated with multiple iterations is used.

– No end to end project plan. Each next iteration plan is determined at the end of the current iteration

– Scope is predefined ahead of the project start and documented in the scope document. During the project, scope can be revised.

– It uses a project backlog instead of scope scrum

– Artifacts include Scope Document, formal functional requirements package, system architecture document, development plan, test scripts, etc.

– Operational software is the only formal artifacts

– Recommended for long term, large, enterprise level projects with medium to high complexity

– Recommended for quick enhancements and organization that are not dependent on a deadline

55. Why Continuous Integration is important for Agile?

Ans:

Continuous Integration is important for Agile for following reasons

  • It helps to maintain release schedule on time by detecting bugs or integration errors
  • Due to frequent agile code delivery usually every sprint of 2-3 weeks, stable quality of build is a must and continuous integration ensures that
  • In helps to maintain the quality and bug free state of code-base
  • Continuous integration helps to check the impact of work on branches to the main trunk if development work is going on branches using automatic building and merging function

56. What testing is done during Agile?

Ans:
The primary testing activities during Agile is automated unit testing and exploratory testing.
Though, depending on project requirements, a tester may execute Functional and Non-functional tests on the Application Under Test (AUT).

57. Explain what is Velocity in Agile?

Ans:
Velocity is a metric that is calculated by addition of all efforts estimates related with user stories completed in an iteration. It figures out how much work Agile can complete in a sprint and how much time will it need to finish a project.

58. What are the qualities of a good Agile tester should have?

Ans:

A good Agile tester should have following qualities

  • It should be able to understand the requirements quickly
  • Agile tester should know Agile principals and concepts well
  • As requirements keep changing, tester should understand the risk involve in it
  • Based on the requirements Agile tester should be able to prioritize the work
  • Continue communication between business associates, developers and tester is must

59. Who are all involved in the Agile team?

Ans:

In agile the two main leads are
Scrum Masters: It coordinates most of the inputs and outputs required for an agile program
Development Managers: They hire right people and develop them with the team

60. Mention in detail what are the role’s of Scrum Master?

Ans:

Scrum Master key responsibilities involves

  1. Understand the requirements and turn them into working software
  2. Monitoring and Tracking
  3. Reporting and Communication
  4. Process Check Master
  5. Quality Master
  6. Resolve Impediments
  7. Resolve Conflicts
  8. Shield the team and performance feedback
  9. Lead all the meetings and resolve obstacles

 

61. Mention what are the Agile quality strategies?

Ans:

Agile quality strategies are

  • Re-factoring
  • Non-solo development
  • Static and dynamic code analysis
  • Reviews and Inspection
  • Iteration/sprint demos
  • All hands demo
  • Light weight milestone reviews
  • Short feedback cycles
  • Standards and guidelines

62. Mention what are the Tools that can be useful for screenshots while working on Agile projects?

Ans:

While working on Agile projects you can use tools like

  • BugDigger
  • BugShooting
  • qTrace
  • Snagit
  • Bonfire
  • Usersnap

63. Mention what are the advantages of maintaining consistent iteration length throughout the project?

Ans:

The advantages are

  • It helps team to objectively measure progress
  • It provides a consistent means of measuring team velocity
  • It helps to establish a consistent pattern of delivery

64. If a timebox plan needs to be reprioritized who should re-prioritise it?

Ans:

If a timebox plan needs to be reprioritized it should include whole team, product owner, and developers.

65. Mention what should a burndown chart should highlight?

Ans:

The burn-down chart shows the remaining work to complete before the timebox (iteration) ends.

66. Mention what is the difference between Scrum and Agile?

Ans:

Scrum: In the scrum, a sprint is a basic unit of development. Each sprint is followed by a planning meeting, where the tasks for the sprint are identified and estimated. During each sprint, the team creates finished portion of a product
Agile: In Agile, each iteration involves a team working through a full software development cycle, including planning, design, coding, requirement analysis, unit testing, and acceptance testing when a product is demonstrated to stakeholders

67. Mention what are the challenges involved in AGILE software development?

Ans:

Challenges involved in Agile Software development includes

  • It requires more testing and customers involvement
  • It impacts management more than developers
  • Each feature needs to be completed before moving on to the next
  • All the code has to work fine to ensure application is in working state
  • More planning is required

68. When not to use Agile?

Ans:

Before using Agile methodology, you must ask following questions

  • Is functionality split-able
  • Is customer available
  • Are requirements flexible
  • Is it really time constrained
  • Is team skilled enough

69. Explain how can you implement scrum in an easy way to your project?

Ans:

These are the tips which can be helpful to implement scrum in your project

  1. Get your backlog in order
  2. Get an idea of the size of your product backlog items
  3. Clarify sprint requirement and duration to complete the sprint backlog
  4. Calculate the team sprint budget and then break requirements into tasks
  5. Collaborate workspace- a center of all team discussion, which includes plans, roadmaps, key dates, sketches of functionality, issues, log, status reports, etc.
  6. Sprint- Make sure you complete one feature at a time before moving on to the next. A sprint should not be abort unless if there is no other option
  7. Attend a daily stand-up meeting: In meeting you need to mention, what have been achieved since the last meeting, what will they achieve before the next meeting and is anything holding up their progress
  8. Use burndown chart to track daily progress. From the burndown chart, you can estimate whether you are on track, or you are running behind
  9. Complete each features well before moving on to the next
  10. At the end of the sprint- hold a sprint review meeting, mention what is achieved or delivered in the sprint.

70. Explain what does it mean by product roadmap?

Ans:

A product roadmap is referred for the holistic view of product features that create the product vision.



 

71. What are the key features of Python?

Ans:

These are the few key features of Python:
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), the justification for this point is given as “we are all adults here”
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 modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.

72. What is the difference between deep and shallow copy?

Ans:

  • Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
  • 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.

73. What is the difference between list and tuples?

Ans:

Lists are mutable i.e they can be edited. Syntax: list_1 = [10, ‘Chelsea’, 20]
Tuples are immutable (tuples are lists which can’t be edited). Syntax: tup_1 = (10, ‘Chelsea’ , 20)

74. How is Multithreading achieved in Python?

Ans:
Python has a multi-threading package but if you want to multi-thread to speed your code up.
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.74.

75. 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:
The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y
Example:
The expression gets evaluated like if x

76. 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:
The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y
Example:
The expression gets evaluated like if x

77. How is memory managed in Python?

Ans:

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

78. Explain Inheritance in Python with an example.

Ans:

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
They are different types of inheritance supported by Python:
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 is 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.

79. Explain what Flask is and its benefits?

Ans:

Flask is a web micro framework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.
A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

80. What is the usage of help() and dir() function in Python?

Ans:

Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
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.




 

81. 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.

82. What is 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.
Let’s take an example:
The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
print dict[Country]
India
print dict[Capital]
Delhi
print dict[PM]
Modi

83. What is monkey patching in Python?

Ans:

In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Consider the below example:

# m.py
class MyClass:
def f(self):
print "f()"

We can then run the monkey-patch testing like this:

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.

84. 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. **kwargsis 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.

85. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory.

Ans:

Let us first write a multiple line solution and then convert it to one liner code.

with open(SOME_LARGE_FILE) as fh:
count = 0
text = fh.read()
for character in text:
if character.isupper():
count += 1

We will now try to transform this into a single line.

count sum(1 for line in fh for character in line if character.isupper())

86. What are negative indexes and why are they used?

Ans:

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.
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.

87. How can you randomize the items of a list in place in Python?

Ans:

Consider the example shown below:

from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)

The output of the following code is as below.

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']

88. 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.
The steps that is required in this as:

  1. 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
  2. Place this file in the Modules/ directory of the distribution which is getting used.
  3. Add a line in the file Setup.local that is present in the Modules/ directory.
  4. Run the file using spam file.o
  5. After successful run of this rebuild the interpreter by using the make command on the top-level directory.
  6. If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

89. Write a sorting algorithm for a numerical dataset in Python.

Ans:

The following code can be used to sort a list in Python:

list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)

90. Looking at the below code, write down the final values of A0, A1, …An.

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)

Ans:

The following will be the final outputs of A0, A1, … A6A0 = {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4} # the order may vary
A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]


 

91. 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:
split() – uses a regex pattern to “split” a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them with a different string
subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

92. How can you generate random numbers in Python?

Ans:

Random module is the standard module that is used to generate the random number. The method is defined as:

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 the 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 different instance of individual threads. The other random generators that are used in this are:

  1. 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.
  2. uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
  3. 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.
  4. The Random class that is used and instantiated creates an independent multiple random number generators.

93. 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.

94. What is pickling and unpickling?

Ans:

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

95. Mention the differences between Django, Pyramid and Flask.

Ans:

  • Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
  • Pyramid is built 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.
  • Django can also used for larger applications just like Pyramid. It includes an ORM.

96. Discuss the Django architecture.

Ans:

Django MVT Pattern:

Django Architecture

Django Architecture

The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

97. Explain how you can set up the Database in Django.

Ans:

You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.
Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.
If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.
Django uses SQLite as default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.
We will add the following lines of code to the setting.py file:

DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

98. Give an example how you can write a VIEW in Django?

Ans:

This is how we can use write a view in Django:

from django.http import HttpResponse
import datetime
def Current_datetime(request):
now = datetime.datetime.now()
html = "It is now %s" % now
return HttpResponse(html)

Returns the current date and time, as an HTML document

99. Mention what the Django templates consists of.

Ans:

The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.

Django Template

Django Template

100. Explain the use of session in Django framework?

Ans:

Django provides session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.

So the data itself is not stored client side. This is nice from a security perspective.

Django Framework

Django Framework



 

101. List out the inheritance styles in Django.

Ans:

In Django, there is three possible inheritance styles:
Abstract Base Classes: This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model.
Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table.
Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields.

102. How To Save An Image Locally Using Python Whose URL Address I Already Know?

Ans:

We will use the following code to save an image locally from an URL address

import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")

103. You are required to scrap data from IMDb top 250 movies page. It should only have fields movie name, year, and rating.

Ans:

We will use the following lines of code:

from bs4 import BeautifulSoup
import requests
import sys
url = 'http://www.imdb.com/chart/top'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)
for movie in tr:
title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0]
rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0]
row = title + ' - ' + year + ' ' + ' ' + rating
print(row)

The above code will help scrap data from IMDb’s top 250 list

104. What is map function in Python?

Ans:

map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.

105. How to get indices of N maximum values in a NumPy array?

Ans:

We can get the indices of N maximum values in a NumPy array using the below code:

import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])

Output
[ 4 3 1 ]

106. How do you calculate percentiles with Python/ NumPy?

Ans:

We can calculate percentiles with the following code

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) #Returns 50th percentile, e.g. median
print(p)

Output
3

107. What advantages do NumPy arrays offer over (nested) Python lists?

Ans:

  1. Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.
  2. They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
  3. NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
  4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.

108. Explain the use of decorators.

Ans:

Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.

109. What is the difference between NumPy and SciPy?

Ans:

  1. In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera.
  2. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
  3. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
  4. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

110. How do you make 3D plots/visualizations using NumPy/SciPy?

Ans:

Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.




 

111. Which of the following statements create a dictionary? (Multiple Correct Answers Possible)

a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)

Ans: b, c & d.

Dictionaries are created by specifying keys and values.

112. Which one of these is floor division?

a) /
b) //
c) %
d) None of the mentioned

Ans:

b) //
When both of the operands are integer then python chops out the fraction part and gives you the round off value, to get the accurate answer use floor division. For ex, 5/2 = 2.5 but both of the operands are integer so answer of this expression in python is 2. To get the 2.5 as the answer, use floor division using //. So, 5//2 = 2.5

113. What is the maximum possible length of an identifier?

a) 31 characters
b) 63 characters
c) 79 characters
d) None of the above

Ans:

d) None of the above
Identifiers can be of any length.

114. Why are local variable names beginning with an underscore discouraged?

a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution

Ans:

a) they are used to indicate a private variables of a class
As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.

115. Which of the following is an invalid statement?

a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000

Ans:

b) a b c = 1000 2000 3000
Spaces are not allowed in variable names.

116. What is the output of the following?

try:
if '1' != 1:
raise "someError"
else:
print("someError has not occured")
except "someError":
print ("someError has occured")

a) someError has occured
b) someError has not occured
c) invalid code
d) none of the above

Ans:

c) invalid code
A new exception class must inherit from a BaseException. There is no such inheritance here.

117. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?

a) Error
b) None
c) 25
d) 2

Ans:

c) 25
The index -1 corresponds to the last index in the list.

118. o open a file c:\scores.txt for writing, we use

a) outfile = open(“c:\scores.txt”, “r”)
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “r”)
d) outfile = open(file = “c:\\scores.txt”, “o”)

Ans:

b) The location contains double slashes ( \\ ) and w is used to indicate that file is being written to.

119. What is the output of the following?

f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print f.closed

a) True
b) False
c) None
d) Error

Ans:

a) True
The WITH statement when used with open file guarantees that the file object is closed when the with block exits.

120. When will the else part of try-except-else be executed?

a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs in to except block

Ans:

c) when no exception occurs
The else part is executed when no exception occurs.


 

121. What is Python?

Ans:

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

122. Name some of the features of Python.

Ans: Following are some of the salient features of python

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

123. Do you have any personal projects? Really?

Ans:

This shows that you are willing to do more than the bare minimum in terms of keeping your skillset up to date. If you work on personal projects and code outside of the workplace then employers are more likely to see you as an asset that will grow. Even if they don’t ask this question I find it’s useful to broach the subject.

124. Is python a case sensitive language?

Ans:

Yes! Python is a case sensitive programming language.

125. What are the supported data types in Python?

Ans:

Python has five standard data types:

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary

126. What is the output of print str if str = ‘Hello World!’?

Ans:

It will print complete string. Output would be Hello World!.

127. What is the output of print str[0] if str = ‘Hello World!’?

Ans:

It will print first character of the string. Output would be H.

128. What is the output of print str[2:5] if str = ‘Hello World!’?

Ans:

It will print characters starting from 3rd to 5th. Output would be llo.

129. What is the output of print str[2:] if str = ‘Hello World!’?

Ans:

It will print characters starting from 3rd character. Output would be llo World!.

130.What is the output of print str * 2 if str = ‘Hello World!’?

Ans:

It will print string two times. Output would be Hello World!Hello World!.



 

131.What is the output of print str + “TEST” if str = ‘Hello World!’?

Ans:

It will print concatenated string. Output would be Hello World!TEST.

132. What is the output of print list if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

Ans:

It will print concatenated lists. Output would be [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ].

133. What is the output of print list[0] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

Ans:

It will print first element of the list. Output would be abcd.

134. What is the output of print list[1:3] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

Ans:

It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].

135. What is the output of print list[2:] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

Ans:

It will print elements starting from 3rd element. Output would be [2.23, ‘john’, 70.200000000000003].

136. What is the output of print tinylist * 2 if tinylist = [123, ‘john’]?

Ans:

It will print list two times. Output would be [123, ‘john’, 123, ‘john’].

137. What is the output of print list + tinylist * 2 if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ] and tinylist = [123, ‘john’]?

Ans:

It will print concatenated lists. Output would be [‘abcd’, 786, 2.23, ‘john’, 70.2, 123, ‘john’, 123, ‘john’].

138. What is tuples in Python?

Ans:

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

139. What is the difference between tuples and lists in Python?

Ans:

The main differences between lists and tuples are – Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

140. What is the output of print tuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

Ans:

It will print complete tuple. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003).




 

141. What is the output of print tuple[0] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

Ans:

It will print first element of the tuple. Output would be abcd.

142. What is the output of print tuple[1:3] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

Ans:

It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).

143. What is the output of print tuple[2:] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

Ans:

It will print elements starting from 3rd element. Output would be (2.23, ‘john’, 70.200000000000003).

144. What is the output of print tinytuple * 2 if tinytuple = (123, ‘john’)?

Ans:

It will print tuple two times. Output would be (123, ‘john’, 123, ‘john’).

145. What is the output of print tuple + tinytuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2) and tinytuple = (123, ‘john’)?

Ans:

It will print concatenated tuples. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’).

146. What are Python’s dictionaries?

Ans:

Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

147. How will you create a dictionary in python?

Ans:

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict[‘one’] = “This is one”
dict[2] = “This is two”
tinydict = {‘name’: ‘john’,’code’:6734, ‘dept’: ‘sales’}

148. How will you get all the keys from the dictionary?

Ans:

Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys() # Prints all the keys

149. How will you get all the values from the dictionary?

Ans:

Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values

150. How will you convert a string to an int in python?

Ans:

int(x [,base]) – Converts x to an integer. base specifies the base if x is a string.


 

151. How will you convert a string to a long in python?

Ans:

long(x [,base] ) – Converts x to a long integer. base specifies the base if x is a string.

152. How will you convert a string to a float in python?

Ans:

float(x) – Converts x to a floating-point number.

153. How will you convert a object to a string in python?

Ans:

str(x) – Converts object x to a string representation.

154. How will you convert a object to a regular expression in python?

Ans:

repr(x) – Converts object x to an expression string.

155. How will you convert a String to an object in python?

Ans:

eval(str) – Evaluates a string and returns an object.

156. How will you convert a string to a tuple in python?

Ans:

tuple(s) – Converts s to a tuple.

157. How will you convert a string to a list in python?

Ans:

list(s) – Converts s to a list.

158. How will you convert a string to a set in python?

Ans:

set(s) – Converts s to a set.

159. How will you create a dictionary using tuples in python?

Ans:

dict(d) – Creates a dictionary. d must be a sequence of (key,value) tuples.

160. How will you convert a string to a frozen set in python?

Ans:

frozenset(s) – Converts s to a frozen set.



 

161. How will you convert an integer to a character in python?

Ans:

chr(x) – Converts an integer to a character.

162. How will you convert an integer to an unicode character in python?

Ans:

unichr(x) – Converts an integer to a Unicode character.

163. How will you convert a single character to its integer value in python?

Ans:

ord(x) – Converts a single character to its integer value.

164. How will you convert an integer to hexadecimal string in python?

Ans:

hex(x) – Converts an integer to a hexadecimal string.

165. How will you convert an integer to octal string in python?

Ans:

oct(x) – Converts an integer to an octal string.

166. What is the purpose of ** operator?

Ans:

** Exponent – Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.

167. What is the purpose of // operator?

Ans:

// Floor Division – The division of operands where the result is the quotient in which the digits after the decimal point are removed.

168. What is the purpose of is operator?

Ans:

is – Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).

169. What is the purpose of not in operator?

Ans:

not in – Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

170. What is the purpose break statement in python?

Ans:

break statement – Terminates the loop statement and transfers execution to the statement immediately following the loop.




 

171. What is the purpose continue statement in python?

Ans:

Continue statement – Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

172. What is the purpose pass statement in python?

Ans:

pass statement – The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

173. How can you pick a random item from a list or tuple?

Ans

choice(seq) – Returns a random item from a list, tuple, or string.

174. How can you pick a random item from a range?

Ans:

randrange ([start,] stop [,step]) – returns a randomly selected element from range(start, stop, step).

175. How can you get a random number in python?

Ans:

random() – returns a random float r, such that 0 is less than or equal to r and r is less than 1.

176. How will you set the starting value in generating random numbers?

Ans:

seed([x]) – Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

177. How will you randomizes the items of a list in place?

Ans:

shuffle(lst) – Randomizes the items of a list in place. Returns None.

178. How will you capitalizes first letter of string?

Ans:

capitalize() – Capitalizes first letter of string.

179. How will you check in a string that all characters are alphanumeric?

Ans:

isalnum() – Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

180. How will you check in a string that all characters are digits?

Ans:

isdigit() – Returns true if string contains only digits and false otherwise.


 

181. How will you check in a string that all characters are in lowercase?

Ans:

islower() – Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

182. How will you check in a string that all characters are numerics?

Ans:

isnumeric() – Returns true if a unicode string contains only numeric characters and false otherwise.

183. How will you check in a string that all characters are whitespaces?

Ans:

isspace() – Returns true if string contains only whitespace characters and false otherwise.

184. How will you check in a string that it is properly titlecased?

Ans:

istitle() – Returns true if string is properly “titlecased” and false otherwise.

185. How will you check in a string that all characters are in uppercase?

Ans:

isupper() – Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

186. How will you merge elements in a sequence?

Ans:

join(seq) – Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

187. How will you get the length of the string?

Ans:

len(string) – Returns the length of the string.

188. How will you get a space-padded string with the original string left-justified to a total of width columns?

Ans:

just(width[, fillchar]) – Returns a space-padded string with the original string left-justified to a total of width columns.

189. How will you convert a string to all lowercase?

Ans:

lower() – Converts all uppercase letters in string to lowercase.

190. How will you remove all leading whitespace in string?

Ans:

strip() – Removes all leading whitespace in string.



 

191. How will you get the max alphabetical character from the string?

Ans:

max(str) – Returns the max alphabetical character from the string str.

192. How will you get the min alphabetical character from the string?

Ans:

min(str) – Returns the min alphabetical character from the string str.

193. How will you replaces all occurrences of old substring in string with new string?

Ans:

replace(old, new [, max]) – Replaces all occurrences of old in string with new or at most max occurrences if max given.

194. How will you remove all leading and trailing whitespace in string?

Ans:

strip([chars]) – Performs both lstrip() and rstrip() on string.

195. How will you change case for all letters in string?

Ans:

swapcase() – Inverts case for all letters in string.

196. How will you get titlecased version of string?

Ans:

title() – Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.

197. How will you convert a string to all uppercase?

Ans:

upper() – Converts all lowercase letters in string to uppercase.

198. How will you check in a string that all characters are decimal?

Ans:

isdecimal() – Returns true if a unicode string contains only decimal characters and false otherwise.

199. What is the difference between del() and remove() methods of list?

Ans:

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know.

200. What is the output of len([1, 2, 3])?

Ans:

3.




 

201. What is the output of [1, 2, 3] + [4, 5, 6]?

Ans:

[1, 2, 3, 4, 5, 6]

202. What is the output of [‘Hi!’] * 4?

Ans:

[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]

203. What is the output of 3 in [1, 2, 3]?

Ans:

True

204. What is the output of for x in [1, 2, 3]: print x?

Ans:

1 2 3

205. What is the output of L[2] if L = [1,2,3]?

Ans:

3, Offsets start at zero.

206. What is the output of L[-2] if L = [1,2,3]?

Ans:

L[-1] = 3, L[-2]=2, L[-3]=1

207. What is the output of L[1:] if L = [1,2,3]?

Ans:

2, 3, Slicing fetches sections.

208. How will you compare two lists?

Ans:

cmp(list1, list2) – Compares elements of both lists.

209. How will you get the length of a list?

Ans:

len(list) – Gives the total length of the list.

210. How will you get the max valued item of a list?

Ans:

max(list) – Returns item from the list with max value.


 

211. How will you get the min valued item of a list?

Ans:

min(list) – Returns item from the list with min value.

212. How will you get the index of an object in a list?

Ans:

list.index(obj) – Returns the lowest index in list that obj appears.

213. How will you insert an object at given index in a list?

Ans:

list.insert(index, obj) – Inserts object obj into list at offset index.

214. How will you remove last object from a list?

Ans:

list.pop(obj=list[-1]) – Removes and returns last object or obj from list.

215. How will you remove an object from a list?

Ans:

list.remove(obj) – Removes object obj from list.

216. How will you reverse a list?

Ans:

list.reverse() – Reverses objects of list in place.

217. How will you sort a list?

Ans:

list.sort([func]) – Sorts objects of list, use compare func if given.

218. Name five modules that are included in python by default (many people come searching for this, so I included some more examples of modules which are often used)

Ans:

datetime (used to manipulate date and time)
re (regular expressions)
urllib, urllib2 (handles many HTTP things)
string (a collection of different groups of strings for example all lower_case letters etc)
itertools (permutations, combinations and other useful iterables)
ctypes (from python docs: create and manipulate C data types in Python)
email (from python docs: A package for parsing, handling, and generating email messages)
__future__ (Record of incompatible language changes. like division operator is different and much better when imported from __future__)
sqlite3 (handles database of SQLite type)
unittest (from python docs: Python unit testing framework, based on Erich Gamma’s JUnit and Kent Beck’s Smalltalk testing framework)
xml (xml support)
logging (defines logger classes. enables python to log details on severity level basis)
os (operating system support)
pickle (similar to json. can put any data structure to external files)
subprocess (from docs: This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes)
webbrowser (from docs: Interfaces for launching and remotely controlling Web browsers.)
traceback (Extract, format and print Python stack traces)

219. Name a module that is not included in python by default

Ans:

mechanize
django
gtk
A lot of other can be found at pypi.

220. What is __init__.py used for?

Ans:

It declares that the given directory is a package. #Python Docs (From Endophage‘s comment)



 

221. When is pass used for?

Ans:

pass does nothing. It is used for completing the code where we need something. For eg:

class abc():
pass

222. What is a docstring?

Ans:

docstring is the documentation string for a function. It can be accessed by

function_name.__doc__

it is declared as:

def function_name():
“””your docstring”””

223. What is list comprehension?

Ans:

Creating a list by doing some operation over data that can be accessed using an iterator. For eg:

>>>[ord(i) for i in string.ascii_uppercase]
[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]

>>>

224. What is map?

Ans:

map executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions
For eg:

>>>a=’ayush’
>>>map(ord,a)

…. [97, 121, 117, 115, 104]

>>> print map(lambda x, y: x*y**2, [1, 2, 3], [2, 4, 1])

…. [4, 32, 3]

Help on built-in function map in module __builtin__:

map(…)

map(function, sequence[, sequence, …]) -> list

Return a list of the results of applying the function to the items of

the argument sequence(s). If more than one sequence is given, the

function is called with an argument list consisting of the corresponding

item of each sequence, substituting None for missing values when not all

sequences have the same length. If the function is None, return a list of

the items of the sequence (or a list of tuples if more than one sequence).

#Python Docs

225. What is the difference between a tuple and a list?

Ans:

A tuple is immutable i.e. can not be changed. It can be operated on only. But a list is mutable. Changes can be done internally to it.

tuple initialization: a = (2,4,5)
list initialization: a = [2,4,5]

The methods/functions provided with each types are also different.

226. Using various python modules convert the list a to generate the output ‘one, two, three’

Ans:

a = [‘one’, ‘two’, ‘three’]

Ans: “, “.join(a)

>>>help(str.join)
Help on method_descriptor:

join(…)

S.join(iterable) -> string

Return a string which is the concatenation of the strings in the

iterable. The separator between elements is S.

227. What would the following code yield?

word = ‘abcdefghij’
print word[:3] + word[3:]

Ans:

‘abcdefghij’ will be printed.
This is called string slicing. Since here the indices of the two slices are colliding, the string slices are ‘abc’ and ‘defghij’. The ‘+’ operator on strings concatenates them. Thus, the two slices formed are concatenated to give the answer ‘abcdefghij’.

228. Optimize these statements as a python programmer.

word = ‘word’
print word.__len__()

Ans:

word = ‘word’
print len(word)

229. Write a program to print all the contents of a file

Ans:

try:
with open(‘filename’,’r’) as f:
print f.read()
except IOError:
print “no such file exists”

230. What will be the output of the following code

a = 1
a, b = a+1, a+1
print a
print b

Ans:

The second line is a simultaneous declaration i.e. value of new a is not used when doing b=a+1.

This is why, exchanging numbers is as easy as:

a,b = b,a




 

231. Given the list below remove the repetition of an element.
All the elements should be unique
words = [‘one’, ‘one’, ‘two’, ‘three’, ‘three’, ‘two’]

Ans:

A bad solution would be to iterate over the list and checking for copies somehow and then remove them!

One of the best solutions I can think of right now:

a = [1,2,2,3]
list(set(a))

set is another type available in python, where copies are not allowed. It also has some good functions available used in set operations ( like union, difference ).

232. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word. for example
{‘one’:2, ‘two’:2, ‘three’:2}

Ans:

>>> def dic(words):
a = {}
for i in words:
try:
a[i] += 1
except KeyError: ## the famous pythonic way:
a[i] = 1 ## Halt and catch fire
return a
>>> a=’1,3,2,4,5,3,2,1,4,3,2′.split(‘,’)
>>> a
[‘1’, ‘3’, ‘2’, ‘4’, ‘5’, ‘3’, ‘2’, ‘1’, ‘4’, ‘3’, ‘2’]
>>> dic(a)
{‘1’: 2, ‘3’: 3, ‘2’: 3, ‘5’: 1, ‘4’: 2}
Without using try-catch block:
>>> def dic(words):
data = {}
for i in words:
data[i] = data.get(i, 0) + 1
return data
>>> a
[‘1’, ‘3’, ‘2’, ‘4’, ‘5’, ‘3’, ‘2’, ‘1’, ‘4’, ‘3’, ‘2’]
>>> dic(a)
{‘1’: 2, ‘3’: 3, ‘2’: 3, ‘5’: 1, ‘4’: 2}

233. Write the following logic in Python:

If a list of words is empty, then let the user know it’s empty, otherwise let the user know it’s not empty

Ans:

Can be checked by a single statement (pythonic beauty):

1

2

3

4

5

6

7

print “The list is empty” if len(a)==0 else “The list is not empty”

>>> a=”

>>> print “‘The list is empty’” if len(a)==0 else “‘The list is not empty’”

‘The list is empty’

>>> a=’asd’

>>> print “‘The list is empty’” if len(a)==0 else “‘The list is not empty’”

‘The list is not empty’

234. Demonstrate the use of exception handling in python.

Ans:

1

2

3

4

try:

import mechanize as me

except ImportError:

import urllib as me

## here you have atleast 1 module imported as me.
This is used to check if the users computer has third party libraries that we need. If not, we work with a default library of python. Quite useful in updating softwares.
PS: This is just one of the uses of try-except blocks. You can note a good use of these in API’s.
Also note that if we do not define the error to be matched, the except block would catch any error raised in try block.

235. Print the length of each line in the file ‘file.txt’ not including any whitespaces at the end of the lines.

Ans:

with open(“filename.txt”, “r”) as f1:
print len(f1.readline().rstrip())

rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs (whitespace characters).

236. Print the sum of digits of numbers starting from 1 to 100 (inclusive of both)

Ans:

print sum(range(1,101))

range() returns a list to the sum function containing all the numbers from 1 to 100. Please see that the range function does not include the end given (101 here).

print sum(xrange(1, 101))

xrange() returns an iterator rather than a list which is less heavy on the memory.

237. Create a new list that converts the following list of number strings to a list of numbers.
num_strings = [‘1′,’21’,’53’,’84’,’50’,’66’,’7′,’38’,’9′]

Ans:
use a list comprehension

>>> [int(i) for i in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]

#num_strings should not contain any non-integer character else ValueError would be raised. A try-catch block can be used to notify the user of this.

Another one suggested by David using maps:

>>> map(int, num_strings)
[1, 21, 53, 84, 50, 66, 7, 38, 9]

238 . Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]

Ans:

>>> odd=[]
>>> even=[]

>>> for i in n:

even.append(i) if i%2==0 else odd.append(i)

## all odd numbers in list odd

## all even numbers in list even

Though if only one of the lists were requires, using list comprehension we could make:

even = [i for i in num_strings if i%2==0]
odd = [i for i in num_strings if i%2==1]

But using this approach if both lists are required would not be efficient since this would iterate the list two times.!

239. Write a program to sort the following intergers in list
nums = [1,5,2,10,3,45,23,1,4,7,9]

Ans:

nums.sort() # The lists have an inbuilt function, sort()
sorted(nums) # sorted() is one of the inbuilt functions)
Python uses TimSort for applying this function.

240. Write a for loop that prints all elements of a list and their position in the list.
Printing using String formatting

Ans:

>>> for index, data in enumerate(asd):
…. print “{0} -> {1}”.format(index, data)

0 -> 4

1 -> 7

2 -> 3

3 -> 2

4 -> 5

5 -> 9

#OR

>>> asd = [4,7,3,2,5,9]

>>> for i in range(len(asd)):

…. print i+1,’–>’,asd[i]

1 –> 4

2 –> 7

3 –> 3

4 –> 2

5 –> 5

6 –> 9


 

241.The following code is supposed to remove numbers less than 5 from list n, but there is a bug. Fix the bug.

Ans:

n = [1,2,5,10,3,100,9,24]
for e in n:
if e<5:
n.remove(e)
print n
## after e is removed, the index position gets disturbed. Instead it should be:
a=[]
for e in n:
if e >= 5:
a.append(e)
n = a

OR again a list comprehension:

return [i for i in n if i >= 5]
OR use filter

return filter(lambda x: x >= 5, n)
itEANz- Online Training in Bangalore

Adding Value Accelerated

242. What will be the output of the following

 

1

2

3

 

def func(x,*y,**z):

….    print z

func(1,2,3)

Ans:

Here the output is :

{}  #Empty Dictionay

x is a normal value, so it takes 1..
y is a list of numbers, so it takes 2,3..
z wants named parameters, so it can not take any value here.
Thus the given answer.

243. Write a program to swap two numbers.

Ans:

a = 5
b = 9
as i told earlier too, just use:
a,b = b,a

244. What will be the output of the following code

1

2

3

4

5

6

7

8

 

class C(object):

…. def__init__(self):

….        self.x =1

c=C()

print c.x

print c.x

print c.x

print c.x

 

Ans:

All the outputs will be 1, since the value of the the object’s attribute(x) is never changed.

x is now a part of the public members of the class C.

Thus it can be accessed directly..

245. What is wrong with the code

 

1

2

3

4

5

 

func([1,2,3]) # explicitly passing in a list

func()        # using a default empty list

def func(n = []):

#do something with n

print n

Ans:

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.

Edit: An extra point for interviews given by Shane Green and Peter: “””Another thing is that mutable types should never be used as default parameter values. Default parameter value expressions are only evaluated once, meaning every invocation of that method shares the same default value. If one invocation that ends up using the default value modifies that value–a list, in this case–it will forever be modified for all future invocations. So default parameter values should limited to primitives, strings, and tuples; no lists, dictionaries, or complex object instances.”””

246. What all options will work?

Ans:

n = 1
print n++   ## no such operator in python (++)
n = 1
print ++n   ## no such operator in python (++)
n = 1
print n += 1  ## will work
int n = 1
print n = n+1 ##will not work as assignment can not be done in print command like this
n =1
n = n+1      ## will work

247. In Python function parameters are passed by value or by reference?

Ans:

It is somewhat more complicated than I have written here (Thanks David for pointing). Explaining all here won’t be possible. Some good links that would really make you understand how things are:

Stackoverflow

Python memory management

Viewing the memory

248. Remove the whitespaces from the string.
s = ‘aaa bbb ccc ddd eee’

Ans:

”.join(s.split())
## join without spaces the string after splitting it

OR

filter(lambda x: x != ‘ ‘, s)

249. What does the below mean?
s = a + ‘[‘ + b + ‘:’ + c + ‘]’

Ans:

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.

250. Optimize the below code

1

2

3

4

5

6

7

def append_s(words):

new_words=[]

for word in words:

new_words.append(word + ‘s’)

return new_words

for word in append_s([‘a’,’b’,’c’]):

print word


Ans:

The above code adds a trailing s after each element of the list.

def append_s(words):
return [i+’s’ for i in words] ## another list comprehension

for word in append_s([‘a’,’b’,’c’]):
print word



 

251. If given the first and last names of bunch of employees how would you store it and what datatype?

Ans:

best stored in a list of dictionaries..
dictionary format:  {‘first_name’:’Ayush’,’last_name’:’Goel’}

252. What is Python really? You can (and are encouraged) make comparisons to other technologies in your answer

Ans:

Here are a few key points:
Python is an interpreted language. That means that, unlike languages like Cand 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=111and 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), the justification for this point is given as “we are all adults here”
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 optimised away and often are. The numpypackage 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 modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.
Python makes difficult things easy so programmers can focus on overriding algorithms and structures rather than nitty-gritty low level details.
Why This Matters:
If you are applying for a Python position, you should know what it is and why it is so gosh-darn cool. And why it isn’t o.O

253. Fill in the missing code:

def print_directory_contents(sPath):
“””
This function takes the name of a directory
and prints out the paths files within that
directory as well as any files contained in
contained directories.
This function is similar to os.walk. Please don’t
use os.walk in your answer. We are interested in your
ability to work with nested structures.
“””
fill_this_in

Ans:

def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
Pay Special Attention

Be consistent with your naming conventions. If there is a naming convention evident in any sample code, stick to it. Even if it is not the naming convention you usually use
Recursive functions need to recurse and Make sure you understand how this happens so that you avoid bottomless callstacks
We use the osmodule for interacting with the operating system in a way that is cross platform. You could say sChildPath = sPath + ‘/’ + sChild but that wouldn’t work on windows
Familiarity with base packages is really worthwhile, but don’t break your head trying to memorize everything, Google is your friend in the workplace!
Ask questions if you don’t understand what the code is supposed to do
KISS! Keep it Simple, Stupid!
Why This Matters:

Displays knowledge of basic operating system interaction stuff
Recursion is hella useful

254. Looking at the below code, write down the final values of A0, A1, …An.

A0 = dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
If you dont know what zip is don’t stress out. No sane employer will expect you to memorize the standard library. Here is the output of help(zip).
zip(…)
zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
If that doesn’t make sense then take a few minutes to figure it out however you choose to.

Ans:

A0 = {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4} # the order may vary
A1 = range(0, 10) # or [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] in python 2
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
Why This Matters
List comprehension is a wonderful time saver and a big stumbling block for a lot of people
If you can read them, you can probably write them down
Some of this code was made to be deliberately weird. You may need to work with some weird people

255. Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in a parallel way.

Ans:

Python doesn’t allow multi-threading in the truest sense of the word. It 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.
There are reasons to use Python’s threading package. If you want to run some things simultaneously, and efficiency is not a concern, then it’s totally fine and convenient. Or if you are running code that needs to wait for something (like some IO) then it could make a lot of sense. But the threading library won’t let you use extra CPU cores.
Multi-threading can be outsourced to the operating system (by doing multi-processing), some external application that calls your Python code (eg, Spark or Hadoop), or some code that your Python code calls (eg: you could have your Python code call a C function that does the expensive multi-threaded stuff).
Why This Matters
Because the GIL is an A-hole. Lots of people spend a lot of time trying to find bottlenecks in their fancy Python multi-threaded code before they learn what the GIL is.

256. How do you keep track of different versions of your code?

Ans:

Version control! At this point, you should act excited and tell them how you even use Git (or whatever is your favorite) to keep track of correspondence with Granny. Git is my preferred version control system, but there are others, for example subversion.
Why This Matters:
Because code without version control is like coffee without a cup. Sometimes we need to write once-off throw away scripts and that’s ok, but if you are dealing with any significant amount of code, a version control system will be a benefit. Version Control helps with keeping track of who made what change to the code base; finding out when bugs were introduced to the code; keeping track of versions and releases of your software; distributing the source code amongst team members; deployment and certain automations. It allows you to roll your code back to before you broke it which is great on its own. Lots of stuff. It’s just great.

257. What does this code output:

def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
f(2)
f(3,[3,2,1])
f(3)

Ans:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
Hu?
The first function call should be fairly obvious, the loop appends 0 and then 1 to the empty list, l. l is a name for a variable that points to a list stored in memory.
The second call starts off by creating a new list in a new block of memory. l then refers to this new list. It then appends 0, 1 and 4 to this new list. So that’s great.
The third function call is the weird one. It uses the original list stored in the original memory block. That is why it starts off with 0 and 1.
Try this out if you don’t understand:
l_mem = []
l = l_mem # the first call
for i in range(2):
l.append(i*i)
print(l) # [0, 1]
l = [3,2,1] # the second call
for i in range(3):
l.append(i*i)
print(l) # [3, 2, 1, 0, 1, 4]
l = l_mem # the third call
for i in range(3):
l.append(i*i)
print(l) # [0, 1, 0, 1, 4]

258. What is monkey patching and is it ever a good idea?

Ans:Monkey patching is changing the behaviour of a function or object after it has already been defined. For example:

import datetime

datetime.datetime.now = lambda: datetime.datetime(2012, 12, 12)

Most of the time it’s a pretty terrible idea – it is usually best if things act in a well-defined way. One reason to monkey patch would be in testing. The mock package is very useful to this end.

Why This Matters

It shows that you understand a bit about methodologies in unit testing. Your mention of monkey avoidance will show that you aren’t one of those coders who favor fancy code over maintainable code (they are out there, and they suck to work with). Remember the principle of KISS? And it shows that you know a little bit about how Python works on a lower level, how functions are actually stored and called and suchlike.

PS: it’s really worth reading a little bit about mock if you haven’t yet. It’s pretty useful.

259. What does this stuff mean: *args, **kwargs? And why would we use it?

Ans:

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. **kwargsis used when we dont 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.

Here is a little illustration:

def f(*args,**kwargs): print(args, kwargs)
l = [1,2,3]
t = (4,5,6)
d = {‘a’:7,’b’:8,’c’:9}
f()
f(1,2,3) # (1, 2, 3) {}
f(1,2,3,”groovy”) # (1, 2, 3, ‘groovy’) {}
f(a=1,b=2,c=3) # () {‘a’: 1, ‘c’: 3, ‘b’: 2}
f(a=1,b=2,c=3,zzz=”hi”) # () {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘zzz’: ‘hi’}
f(1,2,3,a=1,b=2,c=3) # (1, 2, 3) {‘a’: 1, ‘c’: 3, ‘b’: 2}
f(*l,**d) # (1, 2, 3) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f(*t,**d) # (4, 5, 6) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f(1,2,*t) # (1, 2, 4, 5, 6) {}
f(q=”winning”,**d) # () {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
f(1,2,*t,q=”winning”,**d) # (1, 2, 4, 5, 6) {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
def f2(arg1,arg2,*args,**kwargs): print(arg1,arg2, args, kwargs)
f2(1,2,3) # 1 2 (3,) {}
f2(1,2,3,”groovy”) # 1 2 (3, ‘groovy’) {}
f2(arg1=1,arg2=2,c=3) # 1 2 () {‘c’: 3}
f2(arg1=1,arg2=2,c=3,zzz=”hi”) # 1 2 () {‘c’: 3, ‘zzz’: ‘hi’}
f2(1,2,3,a=1,b=2,c=3) # 1 2 (3,) {‘a’: 1, ‘c’: 3, ‘b’: 2}
f2(*l,**d) # 1 2 (3,) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f2(*t,**d) # 4 5 (6,) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f2(1,2,*t) # 1 2 (4, 5, 6) {}
f2(1,1,q=”winning”,**d) # 1 1 () {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
f2(1,2,*t,q=”winning”,**d) # 1 2 (4, 5, 6) {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
Why Care?

Sometimes we will need to pass an unknown number of arguments or keyword arguments into a function. Sometimes we will want to store arguments or keyword arguments for later use. Sometimes it’s just a time saver.

260. What do these mean to you: @classmethod, @staticmethod, @property?

Ans:

Answer Background Knowledge:

These are decorators. A decorator is a special kind of function that either takes a function and returns a function, or takes a class and returns a class. The @ symbol is just syntactic sugar that allows you to decorate something in a way that’s easy to read.
@my_decorator
def my_func(stuff):
do_things
Is equivalent to
def my_func(stuff):
do_things
my_func = my_decorator(my_func)
Actual Answer:

The decorators @classmethod, @staticmethod and @property are used on functions defined within classes. Here is how they behave:
class MyClass(object):
def __init__(self):
self._some_property = “properties are nice”
self._some_other_property = “VERY nice”
def normal_method(*args,**kwargs):
print(“calling normal_method({0},{1})”.format(args,kwargs))
@classmethod
def class_method(*args,**kwargs):
print(“calling class_method({0},{1})”.format(args,kwargs))
@staticmethod
def static_method(*args,**kwargs):
print(“calling static_method({0},{1})”.format(args,kwargs))
@property
def some_property(self,*args,**kwargs):
print(“calling some_property getter({0},{1},{2})”.format(self,args,kwargs))
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
print(“calling some_property setter({0},{1},{2})”.format(self,args,kwargs))
self._some_property = args[0]
@property
def some_other_property(self,*args,**kwargs):
print(“calling some_other_property getter({0},{1},{2})”.format(self,args,kwargs))
return self._some_other_property
o = MyClass()
# undecorated methods work like normal, they get the current instance (self) as the first argument
o.normal_method
# >
o.normal_method()
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>,),{})
o.normal_method(1,2,x=3,y=4)
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>, 1, 2),{‘y’: 4, ‘x’: 3})
# class methods always get the class as the first argument
o.class_method
# >
o.class_method()
# class_method((,),{})
o.class_method(1,2,x=3,y=4)
# class_method((, 1, 2),{‘y’: 4, ‘x’: 3})
# static methods have no arguments except the ones you pass in when you call them
o.static_method
#
o.static_method()
# static_method((),{})
o.static_method(1,2,x=3,y=4)
# static_method((1, 2),{‘y’: 4, ‘x’: 3})
# properties are a way of implementing getters and setters. It’s an error to explicitly call them
# “read only” attributes can be specified by creating a getter without a setter (as in some_other_property)
o.some_property
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# ‘properties are nice’
o.some_property()
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File “”, line 1, in
# TypeError: ‘str’ object is not callable
o.some_other_property
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# ‘VERY nice’
# o.some_other_property()
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File “”, line 1, in
# TypeError: ‘str’ object is not callable
o.some_property = “groovy”
# calling some_property setter(<__main__.MyClass object at 0x7fb2b7077890>,(‘groovy’,),{})
o.some_property
# calling some_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# ‘groovy’
o.some_other_property = “very groovy”
# Traceback (most recent call last):
# File “”, line 1, in
# AttributeError: can’t set attribute
o.some_other_property
# calling some_other_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# ‘VERY nice’




 

261. Describe Python’s garbage collection mechanism in brief.

Ans:
A lot can be said here. There are a few main points that you should mention:
Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else
occasionally things called “reference cycles” happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1and o2 such that x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn’t be live. But each of them has a reference count of 1.
Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first.

262. What is the purpose of PYTHONPATH environment variable?

Ans:

PYTHONPATH – It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

263. What is the purpose of PYTHONSTARTUP environment variable?

Ans:

PYTHONSTARTUP – It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

264. What is the purpose of PYTHONCASEOK environment variable?

Ans:

PYTHONCASEOK – It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

265. What is the purpose of PYTHONHOME environment variable?

Ans:

PYTHONHOME – It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

266. What does a python do?

Ans:

Python is a general-purpose programming language typically used for web development. … SQLite is one free lightweight database commonly used by Python programmers to store data. Many highly trafficked websites, such as YouTube, are created using Python.

267. What is the interpreter in Python?

Ans:

An interpreter is a program that reads and executes code. This includes source code, pre-compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters, which execute Perl, Python, and Ruby code respectively.

268. Why is it called Python?

Ans:

When he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty Python‘s Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.