Python Interview Question Summary

1, What is Python ? What are the benefits of using Python?

A1: high-level,interpreted, general-purpose programming language.

    python supports objects,modules, threads, exception-handling,automatic memory management.

A2:

  • simple, easy to learn syntax, readability, reduce the cost of program maintenance
  • dynamic typing and dynamic binding

2. What is a dynamically typed language?

Static - Data Types are checked before execution.

Dynamic - Data Types are checked during execution

3. What is an interpreted language?

  • language executes its statements line by line
  • run directly from the source code.

4.What is PEP 8 and why is it important?

PEP---> Python Enhancement Proposal

PEP 8 is especially important since it documents the style guidelines for python code.

5.What is Scope in Python?

A scope is a block of code where an object in Python remain relevant.

  • A local scope refers to the local objects available in the current function.
  • A global scope refers to the objects available throught the code execution since their inception.
  • A module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost-scope refers to all the built-in names callable in the program.

6, What are lists and tuples? What  is the key difference between the two?

  • Lists and tuples are both sequence data types that can store a collection of objects in python.
  • lists are represented with square brackets ['sara', 6, 0.19]
  • tuples are represented with parantheses ('ansh', 5, 0.97)

the key difference betwen the two?

  • lists are mutable, this means lists can be modified.append or sliced
  • tuples are immutable objects, this means tuples remain constant and cannot be modified in any manner.

7.What are the common built-in data types in Python?

  • Python provides type() and isinstance() functions to check the type of these variables.
  • None Type: None key represents the null values in Python.
  • Numeric Types: int ,float, complex, bool
  • Sequence Types :lists , tuples and range,str(text strings)
  • Mapping Types: dict(key-value)
  • Set Types: set(add(), remove()), fronzenset(immutable and can't be modified after creation)
  • Modules:
  • Callable Types:user-defined function,instance methods , generator functions,built-in functions, methods and classes.

8.What is pass in Python?

The pass keyword represents a null operation in Python.

def myEmptyFunc():
   # do nothing
   pass

myEmptyFunc()    # nothing happens

9.What are modules and packages in Python?

modules and packages allow for modular programming

Modularizing have several advantages:

  • Simplicity
  • Maintaninability
  • Reusability
  • Scoping

Modules: can be imported and initialized once using the import statement.
Packages:  allow using dot notation for module namespace.

Modules : help avoid clashes between global variable names.

Packages: help avoid clashes between module names.

10.What are global ,protected and private atttributes in Python?

  • Global : Public variables that are defined in the global scope. use the global keyword.
  • Protected : attributes defined with an underscore prefixed to their identifier. eg._sara.
  • Private: attributes with double underscore prefixed to their identifier. eg:__ansh.

11.What is the use of self in Python?

Self is used to represent the instance of the class. with this keyword, you can access the attributes and methods of the class in python.  self is not a keyword in Python.

12.What is __init__?

  • __init__ is a contructor method in Python
  • is automatically called to allocate memory when a new object /instance is created.
# class definition
class Student:
   def __init__(self, fname, lname, age, section):
       self.firstname = fname
       self.lastname = lname
       self.age = age
       self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")

13.What is break, continue  and pass in Python?

  • Break : Terminates the loop immediately and the control flows to the statement after the body of the loop.
  • Continue: Terminate the current iteration of the statement
  • Pass : fill up empty blocks
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
   pass
   if (p == 0):
       current = p
       break
   elif (p % 2 == 0):
       continue
   print(p)    # output => 1 3 1 3 1
print(current)    # output => 0

14.What are unit tests in Python?

  • Unit test is a unit testing framework of Python.
  • Unit testing means testing different components of software separately.

15. What is docstring in Python?

  • Documentation string or docstring is a multiline string used to document a specific code segment.
  • The docstring should describe what the function or method does.

16.What is slicing in Python?

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

17. Expalin how you can make a Python script executable on Unix?

Script file must begin with #!/usr/bin/env python

# pound 井号

/ slash, divide, oblique 斜线,斜杠,除号

! exclamation mark (英式英语)

18.What is the difference between Python Arrays and lists?

  • Arrays : Only contain emlements of same data types. data type of array should be homogeneous (同质的,同类的) comsume far less memory than lists.
  • Lists can contain elements of different data types. data type of lists can be heterogeneous(各种各样的).  consuming large memory.
import array
a = array.array('i', [1, 2, 3])
for i in a:
    print(i, end=' ')    #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string'])    #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
   print(i, end=' ')    #OUTPUT: 1 2 string

19. How is memory managed in Python?

  • Python Memory Manager(private heap space)
  • Python has an in-built garbage collection to recycle the unused memory for the private heap space.

20.What are Python namespaces? Why are they used?

A namespace ensures that object names in a program are unique and can be used without conflict.

  • Local Namespace : local names inside a function.
  • Global Namespace includes name from various imported /modules that are being used in the current project.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of executions.

21: What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself.

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]

23. What are Dict and List comprehensions?

Performing mathemaical operations on the entire list

my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list]    # list comprehension
# output => [4 , 9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list}    # dict comprehension
# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

Performing conditional filtering operations on the entire list.

my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one

a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)]  # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b]    # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)] 

Flattening a multi-dimensional list

my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

24.What is lambda in Python? Why is it used?

Lambda is an anomymous function in Python, That can accept any number of arguments, but can only have a single expression.

Assigning lambda function to a variable:

mul = lambda a, b : a * b
print(mul(2, 5))    # output => 10

Wrapping lambda functions inside another function:

def myWrapper(n):
 return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2))    # output => 10

25.How do you copy an object in Python?

use the copy module.

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object.

Deep Copy copies all values recursively from source to target object.

from copy import copy, deepcopy
list_1 = [1, 2, [3, 5], 4]
## shallow copy
list_2 = copy(list_1) 
list_2[3] = 7
list_2[2].append(6)
list_2    # output => [1, 2, [3, 5, 6], 7]
list_1    # output => [1, 2, [3, 5, 6], 4]
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
list_3    # output => [1, 2, [3, 5, 6, 7], 8]
list_1    # output => [1, 2, [3, 5, 6], 4]

26. What is the difference between xrange and range in Python?

  • xrange() and range() are quite similar in terms of functionality.
  • range() return a Python list. xrange() returns an xrange object.
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

27. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

28. What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

29.What is the difference between .py and .pyc files?

.py files contain the source code of a program.

.pyc file contain the bytecode of your program.

Having .pyc file saves you the compilation time.

30. How Python is interpreted?

Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation . Python is a bytecode interpreted generally.

Source code is a file with .py extension.

Python compiles the source code to a set of instructions for a virtual machine.

.py source code is first compiled to give .pyc which is bytecode.

31. How are arguments passed by value or by reference in python?

  • Pass by value : Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference : Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
def appendNumber(arr):
   arr.append(4)
arr = [1, 2, 3]
print(arr)  #Output: => [1, 2, 3]
appendNumber(arr)
print(arr)  #Output: => [1, 2, 3, 4]

32. What are iterators in Python?

  • An iterator is an object.
  • It remembers its state
  • __iter__() method initializes an iterator
  • __next__() method which returns the next item in iteration and points to the next element.

33.Explain how to delete a file in Python?

Use command os.remove(file_name)

import os
os.remove("ChangedFile.csv")
print("File Removed!")

34.Explain split() and join() functions in Python?

use split() function to split a string based on a delimiter to a list of strings.

use join() function to join a list of strings based on a delimiter to give a single string.

string = "This is a string."
string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.

35.What does *args and **kwargs mean?

*args

  • *args is a special syntax used in the function definition to pass variable-length arguments.
  • “*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):
   mul = a * b
   for num in argv:
       mul *= num
   return mul
print(multiply(1, 2, 3, 4, 5)) #output: 120

**kwargs

  • **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable that has a name when passed to a function.
  • It is actually a dictionary of the variable names and its value.
def tellArguments(**kwargs):
   for key, value in kwargs.items():
       print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

36. 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 the 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值