The post holds my old notes and questions that have been asked during the era of python2.7. This is my interview prep guide.
Table of Contents
- What is python?
- What is the purpose of PYTHONSTARTUP environment variable?
- Is python a case sensitive language?
- What are 5 standard data types in python?
- What is PEP8?
- What is pickling and unpickling?
- How memory is managed in Python?
- What are the tools that help to find bugs or perform static analysis?
- How will you convert a string to an int in python?
- How will you convert a string to a float in python?
- How will you convert a object to a regular string representation in python?
- How will you convert a String to an object in python?
- How will you convert a string to a tuple in python?
- How will you convert a string to a list in python?
- How will you convert a string to a set in python?
- How will you create a dictionary using tuples in python?
- How will you convert a string to a frozen set in python?
- How will you convert an integer to a character in python?
- How will you convert an integer to an unicode character in python?
- How to convert ASCII to int and back?
- How will you convert an integer to hexadecimal string in python?
- How will you convert an integer to octal string in python?
- What is the purpose of ** operator?
- What is the purpose of // operator?
- Difference between is and == in python?
- Python Format Specifiers(python 2):
- Pick a random item from a list or tuple?
- Pick a random item from a range?
- How can you get a random number in python?
- How will you set the starting value in generating random numbers?
- How will you capitalizes first letter of string?
- How will you check in a string that all characters are alphanumeric?
- How will you check in a string that all characters are digits?
- How will you check in a string that all characters are in lowercase?
- How will you check in a string that all characters are in uppercase?
- How will you check in a string that all characters are numerics?
- How will you check in a string that all characters are whitespaces?
- How will you check in a string that it is properly titlecased?
- How will you replaces all occurrences of old substring in string with new string?
- How will you change case for all letters in string?
- How will you check in a string that all characters are decimal?
- What is the output of ['Hi!'] * 4?
- How will you get the max valued item of a list?
- How will you get the min valued item of a list?
- How will you get the index of an object in a list?
- How will you insert an object at given index in a list?
- How will you remove last object from a list?
- How your python code gets executed?
- Is .pyc created every time code is run?
- Different python complied extensions
What is python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
Following are some of the salient features of python −
- It supports functional and structured programming methods as well as OOP.
- It can be used as a scripting language or can be compiled to byte-code for building large applications.
- It provides very high-level dynamic data types and supports dynamic type checking.
- It supports automatic garbage collection.
- It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
What is the purpose of PYTHONSTARTUP environment variable?
PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH
Is python a case sensitive language?
Yes!!!
What are 5 standard data types in python?
The question is about the immutable datatypes.
- Numbers
- String
- List
- Tuple
- Dictionary
What is PEP8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )
# Load the dictionary back from the pickle
favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }
How memory is managed in Python?
Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap. The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code. Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
How will you convert a string to an int in python?
int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.
How will you convert a string to a float in python?
float(x) − Converts x to a floating-point number.
How will you convert a object to a regular string representation in python?
repr(x) − Converts object x to an expression string.
How will you convert a String to an object in python?
eval(str) − Evaluates a string and returns an object.
How will you convert a string to a tuple in python?
tuple(s) − Converts s to a tuple.
How will you convert a string to a list in python?
list(s) − Converts s to a list.
How will you convert a string to a set in python?
set(s) − Converts s to a set.
How will you create a dictionary using tuples in python?
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
How will you convert a string to a frozen set in python?
frozenset(s) − Converts s to a frozen set.
How will you convert an integer to a character in python?
chr(x) − Converts an integer to a character.
How will you convert an integer to an unicode character in python?
unichr(x) − Converts an integer to a Unicode character.
How to convert ASCII to int and back?
ord('a')
gives 97
And back to a string:
str(unichr(97))
gives 'a'
How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.
How will you convert an integer to octal string in python?
oct(x) − Converts an integer to an octal string.
What is the purpose of ** operator?
** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.
What is the purpose of // operator?
// Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.
Difference between is and == in python?
There is a simple rule of thumb to tell you when to use == or is. == is for value equality. Use it when you would like to know if two objects have the same value. ‘is’ is for reference equality. Use it when you would like to know if two references refer to the same object. is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True
Python Format Specifiers(python 2):
The %s specifier converts the object using str(), and %r converts it using repr().
Pick a random item from a list or tuple?
choice(seq) − Returns a random item from a list, tuple, or string.
Pick a random item from a range?
random.randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step).
How can you get a random number in python?
random.random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
How will you set the starting value in generating random numbers?
random.seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
How will you capitalizes first letter of string?
capitalize() − Capitalizes first letter of string.
How will you check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
How will you check in a string that all characters are digits?
isdigit() − Returns true if string contains only digits and false otherwise.
How will you check in a string that all characters are in lowercase?
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
How will you check in a string that all characters are in uppercase?
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
How will you check in a string that all characters are numerics?
isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.
How will you check in a string that all characters are whitespaces?
isspace() − Returns true if string contains only whitespace characters and false otherwise.
How will you check in a string that it is properly titlecased?
istitle() − Returns true if string is properly "titlecased" and false otherwise.
How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.
How will you change case for all letters in string?
swapcase() − Inverts case for all letters in string.
How will you check in a string that all characters are decimal?
isdecimal() − Returns true if a unicode string contains only decimal characters and false otherwise.
What is the output of ['Hi!'] * 4?
['Hi!', 'Hi!', 'Hi!', 'Hi!']
What is cmp(x, y)?
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.
How will you get the max valued item of a list?
max(list) − Returns item from the list with max value.
How will you get the min valued item of a list?
min(list) − Returns item from the list with min value.
How will you get the index of an object in a list?
list.index(obj) − Returns the lowest index in list that obj appears.
How will you insert an object at given index in a list?
list.insert(index, obj) − Inserts object obj into list at offset index.
How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.
How your python code gets executed?
The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.
Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code.
Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM (actually we call it interpreter, right?).
So for Cpython, we can say that its interpreted language. Aha, So that made to confuse you as Python is an "interpreted language"(which in term True for Cpython, a most famous implementation of python). So does pyc file contains cross platform code right?. Yes, bytecode is cross platform but its version dependent ( python 2.x or 3.x).
Is .pyc created every time code is run?
Answer is No. Actually it depends on your modification in py file. The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.
Basically the way the programs are run is always the same. The compiled code is interpreted. The way the programs are loaded differs. If there is a current pyc file, this is taken as the compiled version, so no compile step has to be taken before running the command. Otherwise the py file is read, the compiler has to compile it (which takes a little time) but then the compiled version in memory is interpreted just the same way as always.
Different python complied extensions
- .pyc - This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
- .pyc files contain byte code, which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine.
- .pyo - optimized pyc file- This is a *.pyc file that was created while optimizations (-O) was on
- .pyd - Python script made as a Windows DLL
When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode. A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
No comments:
Post a Comment