A1: high-level,interpreted, general-purpose programming language.
python supports objects,modules, threads, exception-handling,automatic memory management.
A2:
Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution
PEP---> Python Enhancement Proposal
PEP 8 is especially important since it documents the style guidelines for python code.
A scope is a block of code where an object in Python remain relevant.
the key difference betwen the two?
The pass keyword represents a null operation in Python.
- def myEmptyFunc():
- # do nothing
- pass
-
- myEmptyFunc() # nothing happens
modules and packages allow for modular programming
Modularizing have several advantages:
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.
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.
- # 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?
- 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
Script file must begin with #!/usr/bin/env python
# pound 井号
/ slash, divide, oblique 斜线,斜杠,除号
! exclamation mark (英式英语)
- 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
A namespace ensures that object names in a program are unique and can be used without conflict.
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' ]
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]
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]
- 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
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.
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.
.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.
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.
- 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]
Use command os.remove(file_name)
- import os
- os.remove("ChangedFile.csv")
- print("File Removed!")
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.
*args
- 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
- 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
- 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