Wed, Nov 30, 2022
Most Asked Python Programming Interview Questions and Answers
  1. What is a docstring?

Answer: A docstring is a documentation string that we use to explain what a construct does. We place it because the very first thing underneath a operate, class, or a method, to describe what it does. We declare a docstring victimisation 3 sets of single or quote.

 

  1. What is the PYTHONPATH variable?

Answer: PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program. Hence, it should embrace the Python supply library directory and also the directories containing Python ASCII text file. You can manually set PYTHONPATH, however, sometimes, the Python installer will preset it.

 

  1. What is slicing?

Answer: These are the types of basic Python interview questions for fresher.

Slicing may be a technique that permits North American nation to retrieve solely a locality of a listing, tuple, or string. For this, we use the slicing operator [].

>>> (1,2,3,4,5)[2:4]

(3, 4)

>>> [7,6,8,5,9][2:]

[8, 5, 9]

>>> ‘Hello'[:-1]

‘Hell’

 

  1. What is a namedtuple?

Answer: A namedtuple can allow us to access a tuple’s parts employing a name/label. We use the operate namedtuple() for this, and import it from collections.

>>> from collections import namedtuple

>>> Result=namedtuple(‘result’,’Physics Chemistry Maths’) #format

>>> Ayushi=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple

>>> Ayushi.Chemistry

As you’ll see, it allow us to access the marks in Chemistry victimisation the Chemistry attribute of object Ayushi.

 

  1. How would you declare a comment in Python?

Answer: Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe (#). Anything following a hash is taken into account a comment, and the interpreter ignores it.

>>> #line 1 of comment

>>> #line 2 of comment

In fact, you’ll place a comment anyplace in your code. You can use it to explain your code.

 

  1. How would you convert a string into an int in Python?

Answer: If a string contains only numerical characters, you can convert it into an integer using the int() function.

>>> int(‘227’)

227

Let’s check the types:

>>> type(‘227’)

>>> type(int(‘227’))

 

Q.8. How do you take input in Python?

Answer: For taking input from the user, we have the function input(). In Python 2, we had another function raw_input().

The input() function takes, as an argument, the text to be displayed for the task:

>>> a=input(‘Enter a number’)

Enter a number7

But if you have got paid attention, you know that it takes input in the form of a string.

>>> type(a)

Multiplying this by 2 gives us this:

>>> a*=2

>>> a

’77’

So, what if we need to work on an integer instead?

We use the int() function for this.

>>> a=int(input(‘Enter a number’))

Enter a number7

Now when we multiply it by 2, we get this:

>>> a*=2

>>> a

14

 

  1. What is a frozen set in Python?

Answer: First, let’s discuss what a set is. A set may be an assortment of things, where there cannot be any duplicates. A set is also unordered.

>>> myset=

>>> myset

 

This means that we cannot index it.

>>> myset[0]

Traceback (most recent call last):

File “”, line 1, in

myset[0]

TypeError: ‘set’ object does not support indexing

However, a set is mutable. A frozen set is immutable. This means we cannot change its values. This also makes it eligible to be used as a key for a dictionary.

>>> myset=frozenset([1,3,2,2])

>>> myset

frozenset()

>>> type(myset)

For a lot of insight on sets, refer to Python Sets and Booleans.

 

  1. How would you generate a random number in Python?

Answer: These kinds of Python interview Questions and Answers can Prove your depth of knowledge.

To generate a random number, we import the function random() from the module random.

>>> from random import random

>>> random()

0.7931961644126482

Let’s call for help on this.

>>> help(random)

Help on built-in function random:

random(…) method of random.Random instance

random() -> x in the interval [0, 1).

This means that it will return a random number equal to or greater than 0, and less than 1.

We can also use the function randint(). It takes two arguments to indicate a range from which to return a random integer.

>>> from random import randint

>>> randint(2,7)

6

>>> randint(2,7)

5

>>> randint(2,7)

7

>>> randint(2,7)

6

>>> randint(2,7)

2

 

Q.11. How will you capitalize the first letter of a string?

Answer: Simply using the method capitalize().

>>> ‘ayushi’.capitalize()

‘Ayushi’

>>> type(str.capitalize)

However, it will let other characters be.

>>> ‘@yushi’.capitalize()

‘@yushi’

 

Q.12. how can you check if all characters during a string area unit alphanumeric?

Answer: For this, we use the method isalnum().

>>> ‘Ayushi123’.isalnum()

True

>>> ‘Ayushi123!’.isalnum()

Other methods that we have include:

>>> ‘123.3’.isdigit()

False

>>> ‘123’.isnumeric()

True

>>> ‘ayushi’.islower()

True

>>> ‘Ayushi’.isupper()

False

>>> ‘Ayushi’.istitle()

True

>>> ‘ ‘.isspace()

True

>>> ‘123F’.isdecimal()

False

 

Q.13. What is concatenation?

Answer: This is very basic Python Interview Question, try not to make any mistake in this.

Concatenation is joining two sequences. We use the + operator for this.

>>> ’32’+’32’

‘3232’

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

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

>>> (2,3)+(4)

Traceback (most recent call last):

File “”, line 1, in

(2,3)+(4)

TypeError: will solely concatenate tuple (not “int”) to tuple

Here, 4 is considered an int. Let’s do this again.

>>> (2,3)+(4,)

(2, 3, 4)

 

Q.14. What is a function?

Answer: When we want to execute a sequence of statements, we can give it a name. Let’s outline a operate to require 2 ranges and come the larger number.

>>> def greater(a,b):

return a if a>b else b

>>> greater(3,3.5)

3.5

You can create your own function or use one of Python’s many built-in functions.

 

Q.15. Explain lambda expressions. When would you use one?

Answer: When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value. To define the above function as a lambda expression, we type the following code in the interpreter:

 

>>> (lambda a,b:a if a>b else b)(3,3.5)

3.5

 

Here, a and b are the inputs. a if a>b else b is the expression to return. The arguments are 3 and 3.5.

 

It is possible to not have any inputs here.

 

>>> (lambda :print(“Hi”))()

Hi

 

For more insight into lambdas, refer to Lambda Expressions in Python.

 

Q.16. What is recursion?

Answer: When a function makes a call to itself, it is termed recursion. But then, so as for it to avoid forming an infinite loop, we should have a base condition. Let’s take an example.

>>> def facto(n):

if n==1: return 1

return n*facto(n-1)

>>> facto(4)

24

For more on recursion, visit Recursion in Python.

Q.17. What is a generator?

Answer: A generator produces a sequence of values to iterate on. This way, it is kind of an iterable.

We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.

>>> def squares(n):

i=1

while(i>> for i in squares(7):

print(i)

1

4

9

16

25

36

49

For more on generators, read up on Generators in Python.

Q.18. So, what is an iterator, then?

Answer: An iterator returns one object at a time to iterate on. To create an iterator, we use the iter() function.

odds=iter([1,3,5,7,9])

Then, we call the next() function on it every time we want an object.

>>> next(odds)

1

>>> next(odds)

3

>>> next(odds)

5

>>> next(odds)

7

>>> next(odds)

9

And now, when we call it again, it raises a StopIteration exception. This is because it has reached the end of the values to iterate on.

>>> next(odds)

Traceback (most recent call last):

File “”, line 1, in

next(odds)

StopIteration

For more on iterators, refer to Python iterators.

Q.19. Okay, we asked you about generators and iterators, and you gave us the right answers. But don’t they sound similar?

Answer: They do, but there are subtle differences:

For a generator, we create a function. For an iterator, we use in-built functions iter() and next().

For a generator, we use the keyword ‘yield’ to yield/return an object at a time.

A generator could have as several ‘yield’ statements as you would like.

A generator will save the states of the local variables every time ‘yield’ will pause the loop. An iterator doesn’t use native variables; it solely wants an iterable to reiterate on.

Using a category, you can implement your own iterator, but not a generator.

Generators are fast, compact, and simpler.

Iterators are more memory-efficient.

Read Generators vs. Iterators in Python.

Q.20. we all know Python is all the fad currently. But to be really acceptive of an excellent technology, you must know its pitfalls as well. Would you like to talk about this?

Answer: Of course. To be really yourself, you must be accepting of your flaws. Only then can you move forward to work on them. Python has its flaws too:

Python’s understood nature imposes a speed penalty on that.

While Python is nice for a lot of things, it is weak in mobile computing, and in browsers.

Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a duck). This can raise runtime errors.

Python has underdeveloped database access layers. This renders it a less-than-perfect selection for immense information applications.

And then, well, of course. Being easy makes it addictive. Once a Python-coder, always a Python coder.

So while it has problems, it is also a wonderful tool for a lot of things. Refer to Python Advantages and Disadvantages.

These are the Advanced Python Interview queries and Answers for experienced people, however, they can also refer to the basic Python Interview Questions and Answers for Freshers for basic knowledge.

Q.21. What does the function zip() do?

Answer: One of the less common functions with beginners, zip() returns an iterator of tuples.

>>> list(zip([‘a’,’b’,’c’],[1,2,3]))

[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be a list.

>>> list(zip((‘a’,’b’,’c’),(1,2,3)))

[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Q.22. If you are ever stuck in an infinite loop, how will you break out of it?

Answer: For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to demonstrate this.

>>> def counterfunc(n):

while(n==7):print(n)

>>> counterfunc(7)

  1. Explain Python’s parameter-passing mechanism.

Answer: To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter within a function, the change reflects in the calling function. This is its default behavior. However, when we pass literal arguments like strings, numbers, or tuples, they pass by value. This is because they are immutable.

  1. How will you find, in a string, the first word that rhymes with ‘cake’?

Answer: For our purpose, we will use the function search(), and then use group() to get the output.

>>> import re

>>> rhyme=re.search(‘.ake’,’I would make a cake, but I hate to bake’)

>>> rhyme.group()

‘make’

And as we know, the function search() stops at the first match. Hence, we have our first rhyme to ‘cake’.

  1. How is a .pyc file different from a .py file?

Answer: While both files hold byte code, .pyc is the compiled version of a Python file. It has platform-independent byte code, hence, we can execute it on any platform that supports the .pyc format. Python mechanically generates it to enhance performance (in terms of load time, not speed).

  1. How do you create your own package in Python?

Answer: We know that a package may contain sub-packages and modules. A module is nothing but Python code.

To create a package of our own, we create a directory and create a file __init__.py in it. We leave it empty. Then, in that package, we create a module(s) with whatever code we want. For a close clarification with footage, refer toPython Packages.

  1. How do you calculate the length of a string?

Answer: This is simple. We call the function len() on the string we want to calculate the length of.

>>> len(‘Ayushi Sharma’)

>>> len(‘Ayushi Sharma’)

  1. How are arguments passed – by reference of by value?

Answer: Simply put “no”, in fact, this way is called ” call by object ” or ” call by sharing ” (note: can also be called ” call by object reference “, more info ). In more detail, this term does not accurately describe how Python works. In Python, everything is an object, so variables are just references to objects, and the values of those references are passed to the function. So we can’t change the value of the reference but can change the value of the object. Remember: numbers, strings, and tuples are immutable, and list and dicts are mutable.

If the function receives a reference to a mutable object (such as a dictionary or list), it can modify the original value of the object — equivalent to passing the object by “passing the reference”. If the function receives a reference to an immutable object (such as a number, character, or tuple), you can’t directly modify the original object — equivalent to passing the object by “passing the value.”

Any variable in python is an object, so the parameter only supports the reference delivery mode. That is, the name of the actual parameter is bound to the name of the formal parameter by the mechanism of name binding. The formal parameter and the actual parameter point to the same storage space in the memory.

 

  1. Do you know what list and dict comprehensions are? Can you give an example?

Answer: List or dictionary derivation is a grammatical structure that is used to make lists or dictionaries easier based on existing iterable objects. According to the third edition of “Learning Python,” list comprehensions are usually faster than normal loops, and there may be differences between different versions.

 

  1. Do you know what the difference between lists and tuples is? Can you offer me an example for his or her usage?

Answer: Definition:

**list : ** linked list, ordered items, search by index, use square brackets “[]”;

**tuple : **tuple, tuples group diverse objects together, can’t be modified, Find by index, use parentheses “()”;

**dict : ** dictionary, a combination of a set of keys and values, search by key, no order, use braces ””;

**set : **Collection, unordered, element only appears once, automatically deduplicated, using “set([])”

application scenario:

**list : ** Simple data collection, can use index ;

**tuple : **, use some data as a whole, can’t be modified;

**dict : ** data associated with key values and values;

**set : ** data only appears once, only data Whether it appears or not, does not care about its location.

 

  1. Range returns a list, xrang returns a (builder) xrang object. What do you have to say about it?

Answer: Range returns all generated elements (which is very time consuming and memory), and xrang is one for each iteration.

 

  1. Explain what is the common way for the Flask script to work?

Answer: The common manner for the flask script to figure is

Either it ought to be the import path for your application

Or the path to a Python file.

 

  1. Explain how you can access sessions in Flask?

Answer: A session essentially permits you to recollect data from one request to a different. In a flask, it uses a signed cookie that the user will investigate the session contents and modify. The user will modify the session if solely it’s the key Flask.secret_key.

 

  1. How do I copy a file?

Answer: The shutil module contains a copyfile() function.

 

  1. How do I read (or write) binary data?

Answer: It’s best to use the struct module. It permits you to require a string containing binary information (usually numbers) and convert it to Python objects; and contrariwise.

 

  1. How do I delete a file?

Answer: Use os.remove(filename) or os.unlink(filename)

 

  1. How do I run a subprocess with pipes connected to both input and output?

Answer: Use the popen2 module. For example:

import popen2

fromchild, tochild = popen2.popen2(“command”)

tochild.write(“input\n”)

tochild.flush()

output = fromchild.readline()

 

  1. How do I build a Python script viable on UNIX?

Answer: you wish to try and do 2 things: the script file’s mode should be viable and also the initial line should begin with #! followed by the path of the Python interpreter.

The first is completed by execution chmod +x scriptfile or maybe chmod 755 scriptfile.

The second may be done in a variety of ways. The most straightforward way is to write:

#!/usr/local/bin/python as the very initial line of your file, using the pathname for where the Python interpreter is installed on your platform.

 

  1. How do I test a Python program or component?

Answer: Python comes with two testing frameworks. The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring.

The unittest module may be an admirer testing framework modeled on Java and Smalltalk testing frameworks.

For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program ought to have most practicality encapsulated in either functions or category strategies — and this generally has the stunning and pleasant impact of constructing the program run faster (because native variable accesses are quicker than world accesses). Furthermore, the program ought to avoid betting on mutating world variables since this makes testing much more difficult to do.

 

  1. How do I parcel out work among a bunch of worker threads?

Answer: Use the Queue module to make a queue containing an inventory of jobs. The Queue category maintains an inventory of objects with .put(obj) to add an item to the queue and .get() to return an item. The class can pay attention to the locking necessary to confirm that every job is handed out specifically once.

0 Comments

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.