1. What Is Python? What Are The Benefits Of Using Python? What Do You Understand Of PEP 8?

Python is one of the most successful interpreted languages. When you write a Python script, it doesn’t need to get compiled before execution. Few other interpreted languages are PHP and Javascript.

Benefits Of Python Programming.

  • Python is a dynamic-typed language, this means that you don’t need to mention the date type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as “glue” layer to work with other languages.

PEP 8.

PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.

2. What Is The Output Of The Following Python Code Fragment? Justify Your Answer.

def extendList(val, list=[]):

list.append(val)

return list

list1 = extendList(10)

list2 = extendList(123,[])

list3 = extendList(‘a’)

print “list1 = %s” % list1

print “list2 = %s” % list2

print “list3 = %s” % list3

The result of the above Python code snippet is:

list1 = [10, ‘a’]

list2 = [123]

list3 = [10, ‘a’]

You may erroneously expect list1 to be equal to [10] and list3 to be equal to [‘a’], thinking that the list argument will initialize to its default value of [] every time there is a call to the extendList.

However, the flow is like that a new list gets created once after the function is defined. And the same list is used whenever someone calls the extendList method without a list argument. It works like this because the calculation of expressions (in default arguments) occurs at the time of function definition, not during its invocation.

The list1 and list3 are hence operating on the same default list, whereas list2 is running on a separate list that it has created on its own (by passing an empty list as the value of the list parameter).

The definition of the extendList function can get changed in the following manner.

def extendList(val, list=None):

if list is None:

list = []

list.append(val)

return list

With this revised implementation, the output would be:

list1 = [10]

list2 = [123]

list3 = [‘a’]

3. What Is The Statement That Can Be Used In Python If The Program Requires No Action But Requires It Syntactically?

The pass statement is a null operation. Nothing happens when it executes. You should use “pass” keyword in lowercase. If you write “Pass” you’ll face an error like “NameError: name Pass is not defined.” Python statements are case sensitive.

letter = “hai sethuraman”

for i in letter:

if i == “a”:

pass

print(“pass statement is execute …………..”)

else:

print(i)

4. What’s The Process To Get The Home Directory Using ‘~’ In Python?

You need to import the os module, and then just a single line would do the rest.

import os

print (os.path.expanduser(‘~’))

Output:

/home/runner

5. What Are The Built-In Types Available In Python?

Here is the list of most commonly used built-in types that Python supports:

  • Immutable built-in types of Python
    • Numbers
    • Strings
    • Tuples
  • Mutable built-in types of Python
    • List
    • Dictionaries
    • Sets

6.How To Find Bugs Or Perform Static Analysis In A Python Application?

  • You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
  • Another tool is Pylint, which checks whether the Python module satisfies the coding standard.

7. When Is The Python Decorator Used?

Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.

8. What Is The Key Difference Between A List And The Tuple?

List Vs Tuple.

The major difference between a list and the tuple is that the list is mutable while tuple is not. A tuple is allowed to be hashed, for example, using it as a key for dictionaries.

9. How Does Python Handle The Memory Management?

  • Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
  • And it’s the Python memory manager that handles the Private heap. It does the required allocation of the heap for Python objects.
  • Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.

10. What Are The Principal Differences Between The Lambda And Def?

Lambda Vs Def.

  • def can hold multiple expressions while lambda is a uni-expression function.
  • def generates a function and designates a name so as to call it later. lambda forms a function and returns the function itself.
  • def can have a return statement. lambda can’t have return statements
  • lambda supports to get used inside a list and dictionary.

11. Write A Reg Expression That Confirms An Email Id Using The Python Reg Expression Module <Re>?

Python has a regular expression module <re>.

Check out the <re> expression that can check the email id for .com and .co.in subdomain.

import re

print(re.search(r”[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$”,”micheal.pages@mp.com”))

12. What Do You Think Is The Output Of The Following Code Fragment? Is There Any Error In The Code?

list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

print (list[10:])

The result of the above lines of code is []. There won’t be any error like an IndexError.

You should know that trying to fetch a member from the list using an index that exceeds the member count (for example, attempting to access list[10] as given in the question) would yield an IndexError. By the way, retrieving only a slice at an opening index that surpasses the no. of items in the list won’t result in an IndexError. It will just return an empty list.

13: Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For The Same?

No, Python does not have a Switch statement, but you can write a Switch function and then use it.

14. What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence?

range() generates a list of numbers, which is used to iterate over for loops.

for i in range(5):

print(i)

The range() function accompanies two sets of parameters.

  • range(stop)
    • stop: It is the no. of integers to generate and starts from zero. eg. range(3) == [0, 1, 2].
  • range([start], stop[, step])
    • start: It is the starting no. of the sequence.
    • stop: It specifies the upper limit of the sequence.
    • step: It is the incrementing factor for generating the sequence.
  • Points to note:
    • Only integer arguments are allowed.
    • Parameters can be positive or negative.
    • The <range()>function in Python starts from the zeroth index.

15. What Are The Optional Statements That Can Be Used Inside A <Try-Except> Block In Python?

There are two optional clauses you can use in the <try-except> block.

  • The <else>clause
    • It is useful if you want to run a piece of code when the try block doesn’t create any exception.
  • The <finally>clause
    • It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.

16: How Does The Ternary Operator Work In Python?

The ternary operator is an alternative for the conditional statements. It combines of the true or false values with a statement that you need to test. The syntax would look like the one given below.

[onTrue] if [Condition] else [onFalse]

x, y = 35, 75

smaller = x if x < y else y

print(smaller)

17. What Does The <Self> Keyword Do?

The <self> keyword is a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as hidden parameter.

18. What Are Different Methods To Copy An Object In Python?

There are two ways to copy objects in Python.

  • copy() function
    • It makes a copy of the file from source to destination.
    • It’ll return a shallow copy of the parameter.
  • deepcopy() function
    • It also produces the copy of an object from the source to destination.
    • It’ll return a deep copy of the parameter that you can pass to the function.

19. What Is The Purpose Of Doc Strings In Python?

In Python, documentation string is popularly known as doc strings. It sets a process of recording Python functions, modules, and classes.

20. Which Python Function Will You Use To Convert A Number To A String?

For converting a number into a string, you can use the built-in function <str()>. If you want an octal or hexadecimal representation, use the inbuilt function <oct()> or <hex()>.

21: How Do You Debug A Program In Python? Is It Possible To Step Through Python Code?

Yes, we can use the Python debugger (<pdb>) to debug any Python program. And if we start a program using <pdb>, then it let us even step through the code.

22: List Down Some Of The PDB Commands For Debugging Python Programs?

Here are a few PDB commands to start debugging Python code.

  • Add breakpoint – <b>
  • Resume execution – <c>
  • Step by step debugging – <s>
  • Move to next line – <n>
  • List source code – <l>
  • Print an expression – <p>

23. What Is The Command To Debug A Python Program?

The following command helps run a Python program in debug mode.

$ python -m pdb python-script.py

24. How Do You Monitor The Code Flow Of A Program In Python?

In Python, we can use <sys> module’s <settrace()> method to setup trace hooks and monitor the functions inside a program.

You need to define a trace callback method and pass it to the <settrace()> method. The callback should specify three arguments as shown below.

import sys

 

def trace_calls(frame, event, arg):

# The ‘call’ event occurs before a function gets executed.

if event != ‘call’:

return

# Next, inspect the frame data and print information.

print ‘Function name=%s, line num=%s’ % (frame.f_code.co_name, frame.f_lineno)

return

 

def demo2():

print ‘in demo2()’

 

def demo1():

print ‘in demo1()’

demo2()

 

sys.settrace(trace_calls)

demo1()

25. Why And When Do You Use Generators In Python?

A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.

Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

  • We can replace loops with generators for efficiently calculating results involving large data sets.
  • Generators are useful when we don’t want all the results and wish to hold back for some time.
  • Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.

26. What Does The <Yield> Keyword Do In Python?

The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.

See the example below.

def testgen(index):

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

yield weekdays[index]

yield weekdays[index+1]

 

day = testgen(0)

print next(day), next(day)

 

#output: sun mon

27. How To Convert A List Into Other Data Types?

Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.

Turn A List Into A String.

We can use the <”.join()> method which combines all elements into one and returns as a string.

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

listAsString = ‘ ‘.join(weekdays)

print(listAsString)

 

#output: sun mon tue wed thu fri sat

Turn A List Into A Tuple.

Call Python’s <tuple()> function for converting a list into a tuple. This function takes the list as its argument. But remember, we can’t change the list after turning it into a tuple because it becomes immutable.

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

listAsTuple = tuple(weekdays)

print(listAsTuple)

 

#output: (‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’)

Turn A List Into A Set.

Converting a list to a set poses two side-effects.

  • Set doesn’t allow duplicate entries, so the conversion will remove any such item if found.
  • A set is an ordered collection, so the order of list items would also change.

However, we can use the <set()> function to convert a list to a set.

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’,’tue’]

listAsSet = set(weekdays)

print(listAsSet)

 

#output: set([‘wed’, ‘sun’, ‘thu’, ‘tue’, ‘mon’, ‘fri’, ‘sat’])

Turn A List Into A Dictionary.

In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.

However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.

Passing the tuples into the <dict()> function would finally turn them into a dictionary.

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’]

listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))

print(listAsDict)

 

#output: {‘sun’: ‘mon’, ‘thu’: ‘fri’, ‘tue’: ‘wed’}

28. How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?

Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.

Count The Occurrences Of An Individual Item.

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]

print(weekdays.count(‘mon’))

 

#output: 3

Count The Occurrences Of Each Item In The List.

We’ll use the list comprehension along with the <count()> method. It’ll print the frequency of each of the items.

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]

print([[x,weekdays.count(x)] for x in set(weekdays)])

 

#output: [[‘wed’, 1], [‘sun’, 2], [‘thu’, 1], [‘tue’, 1], [‘mon’, 3], [‘fri’, 1]]

29. What Is NumPy And How Is It Better Than A List In Python?

NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.

Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.

  • NumPy arrays are more compact than lists.
  • Reading and writing items is faster with NumPy.
  • Using NumPy is more convenient than to the standard list.
  • NumPy arrays are more efficient as they augment the functionality of lists in Python.

30. What Are Different Ways To Create An Empty NumPy Array In Python?

There are two methods which we can apply to create empty NumPy arrays.

The First Method To Create An Empty Array.

import numpy

numpy.array([])

The Second Method To Create An Empty Array.

# Make an empty NumPy array

numpy.empty(shape=(0,0))

Leave a Reply

Your email address will not be published. Required fields are marked *