This is the second part of a series of Python interview questions. Like the previous part, you will learn both the basics and the advanced versions, covering scripting, Python coding, and data structures. If you missed it, check it out here.

Q 1. What data types does Python support?

This is the most basic Python interview question.

Python supports five data types:

Numbers — Hold Numbers

> > > a = 7.0 > > >Copy the code

2. Strings — A string is a sequence of characters. We declare strings in single or double quotes.

>>> title="Ayushi's Book"
Copy the code

Lists — Lists are an ordered collection of values that we declare with square brackets.

>>> colors=['red'.'green'.'blue'] > > >type(colors)
 <class 'list'>
Copy the code

4. Tuples — Tuples, like lists, are ordered collections of values, except that Tuples are immutable, meaning we cannot change the values inside them.

>>> name=('Ayushi'.'Sharma')
>>> name[0]='Avery'
Traceback (most recent call last):
File "<pyshell#129>", line 1, in <module>
name[0]='Avery'
Copy the code

TypeError: the ‘tuple’ object does not support item allocation

5. Dictionary — A Dictionary is a data structure that contains key-value pairs. We declare the dictionary with curly braces.

> > > squares = {1, 2:4 and, therefore, behold, they, 5:25} > > >type(squares)
<class 'dict'>
>>> type({})
<class 'dict'>
Copy the code

We can also use dictionary wizardry:

>>> squares={x:x**2 for x inRange (1, 6)} > > > squares {1, 1, 2, 4, 3, 9, 4:16, 5:25}Copy the code

Q 2. What is docString?

A Docstring is a Docstring that explains what a construct does. We describe its role by putting it first in a function, class, or method. We declare the docString with three single or double quotes.

>>> def sayhi():
    """Print Hi with this function"""
  print("Hi")   
>>> sayhi()
 
Hi
Copy the code

To get a function’s docString, we use its _doc_ property.

To get a function's docString, we use its _doc_ property. > > > sayhi. __doc__ '\ n \ tThisfunctionPrints the Hi \ n \ t 'Copy the code

Unlike annotations, docStrings are retained at run time.

Q 3. What is the PYTHONPATH variable?

PYTHONPATH is an important environment variable in Python that is used to search for paths when importing modules. It must therefore contain the Python source library directory as well as the directory containing Python source code. You can set PYTHONPATH manually, but usually the Python installer will render it. Q4 through Q20 are the basic Python interview questions.

Q4. What is slicing?

Slicing is a method in Python that allows us to retrieve only part of a list, element, or string. When slicing, we use the slicing operator [].

> > > (1, 2, 3, 4, 5) [then] (3, 4) > > >,6,8,5,9 [7] [2:] [8, 5, 9] > > >'Hello'[: 1] 'Hell'Copy the code

Q 5. What is a namedtuple?

Namedtuple lets us get the elements of a tuple by name/tag, which we import from the Collections module using the function Namedtuple ().

>>> from collections import namedtuple
>>> result=namedtuple('result'.'Physics Chemistry Maths') #format
>>> Ayushi=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple
>>> Ayushi.Chemistry
 
95
Copy the code

As shown above, it lets us use the Chemistry property of the object Ayushi to get the symbol in Chemistry. For more information about Namedtuples, see here.

Q 6. How do I declare a comment in Python?

Unlike programming languages such as C++, Python does not have multi-line comments, only hash characters (#). Anything after the # is considered a comment and is automatically ignored by the interpreter.

>>> Comment line 1
>>> Comment line 2
Copy the code

You can actually insert comments anywhere in the code to explain the code.

Q 7. How do I convert a string to an integer in Python?

If a string contains only numeric characters, it can be converted to integers using the function int().

>>> int('227')
227
Copy the code

Let’s check the variable types:

>>> type('227')
<class 'str'>
>>> type(int('227'))
<class 'int'>
Copy the code

Q 8. How do I get input in Python?

We use the function input() to get input from the user. In Python 2, we have another function raw_input(). For example, input() takes the text and presents it as a parameter value:

>>> a=input('Enter a number')
Copy the code

Enter the number 7

But if you pay more attention, it takes input as a string.

>>> type(a)
<class 'str'>
Copy the code

Multiply this by 2 to get:

>>> A *=2 >>> A '77'Copy the code

What if you need to use integers?

We use the int() function.

>>> a=int(input('Enter a number'))
Copy the code

Enter the number 7.

Now when we multiply this by 2 we get:

>>> a*=2
>>> a
 
14
Copy the code

Q 9. What is an immutable set in Python?

We answer these Python interview questions with examples.

First, let’s talk about what a set is. A collection is a collection of data items without any copies. In addition, the set is unordered.

>>> mySet ={1,3,2,2} >>> mySet {1, 2, 3}Copy the code

That means we can’t index it.

>>> myset[0]
Traceback (most recent call last):
File "<pyshell#197>", line 1, in <module>
myset[0]
Copy the code

TypeError: ‘set’ does not support indexes. However, the set is mutable. An immutable set is immutable, which means that we cannot change its value and therefore cannot use it as a dictionary key.

> > > myset = frozenset (,3,2,2 [1]) > > > myset frozenset ({1, 2, 3}) > > >type(myset)
<class 'frozenset'>
Copy the code

For more on collections, see here.

Q 10. How do I generate a random number in Python?

To generate random numbers, we can import the function random() from the random module.

>>> from random import random
>>> random()
0.7931961644126482
Copy the code

Here we call help.

>>> help(random)
Copy the code

The help result of the built-in function random is:

The random (...). method of random.Random instance random() -> xin the interval [0, 1).
Copy the code

This means that random() returns a random number greater than or equal to 0 and less than 1.

We can also use the function randint(), which takes two arguments to represent an interval and returns a random integer within that interval.

>>> from random import randint
>>> randint(2,7)
6
 
>>> randint(2,7)
5
 
>>> randint(2,7)
7
 
>>> randint(2,7)
6
Copy the code

Q 11. How do I capitalize the first character in a string?

And the easiest way to do that is to capitalize().

>>> 'ayushi'Capitalize () 'Ayushi > > >type(str.capitalize)
<class 'method_descriptor'>
Copy the code

But it also capitalizes other letters.

>>> '@yushi'Capitalize () '@ yushi'Copy the code

Q 12. How do I check that all characters in a string are alphanumeric?

For this problem, we can use the isalnum() method.

>>> 'Ayushi123'.isalnum()
True
 
>>> 'Ayushi123! '.isalnum()
False
Copy the code

We can also use some other methods:

>>> '123.3'.isdigit()
False
 
>>> '123'.isnumeric()
True
 
>>> 'ayushi'.islower()
True
 
>>> 'Ayushi'.isupper()
False
 
>>> 'Ayushi'.istitle()
True
 
>>> ' '.isspace()
True
 
>>> '123F'.isdecimal()
False

Copy the code

Q 13. What is a concatenation in Python?

A concatenation in Python is a concatenation of two sequences, which we do using the + operator.

>>> '32'+'32''3232' > > > [1, 2, 3] + [4 and 6] [1, 2, 3, 4, 5, 6] > > > (2, 3) + (4) the Traceback (the most recent call last) : the File"<pyshell#256>", line 1, inThe < module > (2, 3) + (4)Copy the code

TypeError: Only tuples (not “integers”) can be connected to tuples.

Here 4 is viewed as an integer, so let’s do it again.

>>> (2,3)+(4,) (2,3, 4)Copy the code

Q 14. What is a function?

When we want to execute a series of statements, we can give them a name. Let’s define a function that takes two numbers and returns a larger number.

>>> def greater(a,b): return aif a>b elseB > > > greater,3.5 (3) 3.5Copy the code

You can create your own functions or use many of Python’s built-in functions, see here.

Q 15. Explain the Ramda expression. When will it be used?

If we need a function with a single expression, we can define it anonymously. Ramda expressions are usually used when a function is needed, but you don’t want to bother naming a function, i.e. anonymous functions.

If we wanted to define the function in Q14 above as a Ramda expression, we could enter the following code in the interpreter:

>>> (lambda a,b:a if a>b elseB) (3,3.5) 3.5Copy the code

Here, both a and b are inputs, a if a>b else b is the returned input, with parameters 3 and 3.5.

Of course, there may be no input at all.

>>> (lambda :print("Hi"))()
Hi
Copy the code

For more information on Ramda expressions, see here.

Q 16. What is recursion?

Recursion is when you call a function, directly or indirectly calling the function itself. But to avoid an infinite loop, an end condition is necessary, for example:

>>> def facto(n):
    if n==1: return 1
    return n*facto(n-1)
>>> facto(4)
24
Copy the code

Q 17. What is a generator?

A generator generates a set of values for iteration, which makes it an iterable. It evaluates the next element as it goes through the for loop and terminates the for loop under appropriate conditions.

We define a function that yields each value, and then iterate over it with a for loop.

>>> def squares(n):
    i=1
    while(i<=n):
        yield i**2
        i+=1
>>> for i in squares(7):
    print(i)
1
 
4
 
9
 
16
 
25
 
36
 
49
Copy the code

For more on generators, see here.

Q 18. What is an iterator?

Iterators are a way to access collection elements. Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward and not backward. We use the inter() function to create iterators.

Odds = iter (,3,5,7,9 [1])Copy the code

We call the next() function every time we want to get an object.

>>> next(odds)
1
 
>>> next(odds)
3
 
>>> next(odds)
5
 
>>> next(odds)
7
 
>>> next(odds)
9
Copy the code

Now we call it again, raising the StopIteration exception. This is because it has reached the end of the value to be iterated over.

>>> next(odds)
Traceback (most recent call last):
File "<pyshell#295>", line 1, in <module>
next(odds)
StopIteration
Copy the code

For more on iterators, see here.

Q19. Tell us the difference between generators and iterators

  • To use a generator, we create a function; When using iterators, we use the built-in functions iter() and next().

  • In generators, we use the keyword ‘yield’ to generate/return one object at a time.

  • You can define how many yield statements there are in the generator.

  • Each time ‘yield’ pauses the loop, the generator saves the state of the local variable. An iterator doesn’t use local variables, it just needs an iterable to iterate over.

  • You can implement your own iterators using classes, but you can’t implement generators.

  • Generators are fast, concise, and simpler.

  • Iterators save more memory.

For more on the comparison between generators and iterators, see here.

Q 20. We all know that Python is hot right now, but we need to know not only the advantages but also the disadvantages of a technology. Please talk about the disadvantages of Python.

Python has the following defects:

  • Python’s interpretable nature slows it down.

  • While Python performs well in many areas, it doesn’t perform well in mobile computing and browsers.

  • Because it is a dynamic language, Python uses duck typing, or duck-typing, which increases runtime errors.

Q 21 through Q 30 are advanced Python interview questions, but may also be useful for Python beginners.

Q 21. What does zip() do?

This function may not be familiar to new Python users, but zip() returns an iterator of tuples.

>>> list(zip(['a'.'b'.'c'],[1,2,3]) [(' a ', 1), (' b ',2), (' c ',3)]Copy the code

Here the zip() function pairs the data items in the two lists and uses them to create a tuple.

>>> list(zip(('a'.'b'.'c'),(1,2,3)))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Copy the code

Q. 22. If you’re stuck in a loop, how do you break it?

When this problem occurs, we can press Ctrl+C to interrupt the execution of the program. Let’s create an infinite loop to explain this.

>>> def counterfunc(n):
    while(n==7):print(n)
>>> counterfunc(7)
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
7
 
Traceback (most recent call last):
 File "<pyshell#332>", line 1, in <module>
   counterfunc(7)
 File "<pyshell#331>", line 2, in counterfunc
   while(n==7):print(n)
KeyboardInterrupt
 
>>>
Copy the code

Q 23. Explain Python’s argument passing mechanism

Python uses pass-by-reference to pass parameters to functions. If you change an argument in a function, it will affect the function call. This is the default in Python. However, if we pass literal arguments, such as strings, numbers, or tuples, they are passed by value because they are immutable.

Q 24. How do I use Python to find out which directory you are in?

We can import it from the module OS using the function/method getcwd().

>>> import os
>>> os.getcwd()
'C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32'
>>> type(os.getcwd)
<class 'builtin_function_or_method'>
Copy the code

We can also modify the current working directory with chdir().

>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.getcwd()
'C:\\Users\\lifei\\Desktop'
Copy the code

Q 25. How do you find the first word in a string that rhymes with ‘cake’?

We can use the function search() and then group() to get the output.

>>> import re
>>> rhyme=re.search('.ake'.'I would make a cake, but I hate to bake')
>>> rhyme.group()
'make'
Copy the code

We know that the function search() will stop running on the first match so that we can get the first word that rhymes with ‘cake’.

Q 26. How do I display the contents of a file in reverse order?

Let’s first go back to the desktop and use the chdir() function/method in the module OS.

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
Copy the code

The file we are going to use here is today.txt, which has the following contents:

OS, DBMS, DS, ADA

HTML, CSS, jQuery, JavaScript

Python, C++, Java

This sem’s subjects

Debugger

itertools

Container
Copy the code

We read the contents as a list and then call the reversed() function on it:

>>> for line in reversed(list(open('Today.txt'))) :print(line.rstrip())
container
 
itertools
 
Debugger
 
This sem’s subjects
 
Python, C++, Java
 
HTML, CSS, jQuery, JavaScript
 
OS, DBMS, DS, ADA
Copy the code

Without rstrip(), we would have blank lines in the output.

Q27. What is a Tkinter?

TKinter is a well-known Python library that allows you to create graphical user interfaces. It supports different GUI tools and widgets such as buttons, labels, text boxes, and so on. These tools and artifacts have different attributes, such as dimensions, colors, fonts, and so on.

We can also import the Tkinter module.

>>> import tkinter
>>> top=tkinter.Tk()
Copy the code

This will create a new window for you, on which you can then add widgets.

Q 28. Please talk about the differences between.pyc files and.py files

Although both of these files hold bytecode, a. Pyc file is a compiled version of a Python file that has platform-independent bytecode, so we can execute it on any platform that supports. Pyc files. Python generates it automatically to optimize performance (load time, not run speed).

Q 29. How do I create my own packages in Python?

Py and several module files. __init__.py can be an empty file, but it is recommended that all exported variables from the package be placed in __all__. This ensures that the interface to the package is clean and easy to use.

Q 30. How do I calculate the length of a string?

This one is also simpler, simply calling len() on the string we want to calculate the length of.

>>> len('Ayushi Sharma'13)Copy the code

In this article, we have summarized some other common Python interview questions. Of course, we can’t cover all the topics.