Python Interview Questions
1 .
What are local variables and global variables in Python?
Global Variables :
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables :
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
Example :
def add():
Output : 5
When you try to access the local variable outside the function add(), it will throw an error.
2 .
What is type conversion in Python?
Type conversion refers to the conversion of one data type iinto another.
int() : converts any data type into integer type
float() : converts any data type into float type
ord() : converts characters into integer
hex() : converts integers to hexadecimal
oct() : converts integer to octal
tuple() : This function is used to convert to a tuple.
set() : This function returns the type after converting to set.
list() : This function is used to convert any data type to a list type.
dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
str() : Used to convert integer into a string.
complex(real,imag) : This functionconverts real numbers to complex(real,imag) number.
3 .
What is the difference between Python Arrays and lists?
Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.
Example :
import array as arr
Output :
array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]
4 .
What is pass in Python?
The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.
def myEmptyFunc():
    # do nothing

myEmptyFunc()    # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
5 .
What is the difference between xrange and range in Python?
xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object.
So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object type generators and has been termed as "yielding".
Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).
for i in xrange(10):    # numbers from o to 9
    print i       # output => 0 1 2 3 4 5 6 7 8 9

for i in xrange(1,10):    # numbers from 1 to 9
    print i       # output => 1 2 3 4 5 6 7 8 9

for i in xrange(1, 10, 2):    # skip by two for next
    print i       # output => 1 3 5 7 9
Note : xrange has been deprecated as of Python 3.x. Now range does exactly the same what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.
6 .
What is pickling and unpickling?
Python library offers a feature - serialization out of the box. Serializing a object refers to transforming it into a format that can be stored, so as to be able to deserialize it later on, to obtain the original object. Here, the pickle module comes into play.
Pickling : Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions.
The function used for the above process is pickle.dump().
Unpickling : Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file, and loads the object to memory.
The function used for the above process is pickle.load().
7 .
What are generators in Python?
Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

Let's try and build a generator for fibonacci numbers :
## generate fibonacci numbers upto n
def fib(n):
    p, q = 0, 1
    while(p < n):
        yield p
        p, q = q, p + q

x = fib(10)    # create generator object 
## iterating using __next__(), for Python2, use next()
x.__next__()    # output => 0
x.__next__()    # output => 1
x.__next__()    # output => 1
x.__next__()    # output => 2
x.__next__()    # output => 3
x.__next__()    # output => 5
x.__next__()    # output => 8
x.__next__()    # error
## iterating using loop
for i in fib(10):
    print(i)    # output => 0 1 1 2 3 5 8
8 .
What is the difference between .py and .pyc files?
* .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.

* Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.

* Having .pyc file saves you the compilation time.
9 .
What is slicing in Python?
* As the name suggests, ‘slicing’ is taking parts of.
* Syntax for slicing is [start : stop : step]
* start is the starting index from where to slice a list or tuple
* stop is the ending index or where to sop.
* step is the number of steps to jump.
* Default value for start is 0, stop is number of items, step is 1.
* Slicing can be done on strings, arrays, lists, and tuples.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2])  #output : [2, 4, 6, 8, 10]​
10 .
What are negative indexes and why are they used?
* Negative indexes are the indexes from the end of the list or tuple or string.
* Arr[-1] means last element of array Arr[]

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

#get the last element
print(arr[-1]) #output 6

#get the second last element
print(arr[-2]) #output 5​