How Do I Share Global Variables Across Modules?
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.
For example:
config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
import config
config.x = 1
main.py:
import config
import mod
print config.x
How Do I Copy An Object In Python?
In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a copy() method:
newdict = olddict.copy()
Sequences can be copied by slicing:
new_l = l[:]
What Are The Built-In Types Available In Python?
Here is the list of most commonly used built-in types that Python supports:
Immutable built-in types of Python
Numbers
Strings
Tuples
Mutable built-in types of Python
List
Dictionaries
Sets
How To Find Bugs Or Perform Static Analysis In A Python Application?
You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
When Is The Python Decorator Used?
Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.
What Is The Key Difference Between A List And The Tuple?
List Vs Tuple.
The major difference between a list and the tuple is that the list is mutable while tuple is not. A tuple is allowed to be hashed, for example, using it as a key for dictionaries.
How Does Python Handle The Memory Management?
Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
And it’s the Python memory manager that handles the Private heap. It does the required allocation of the heap for Python objects.
Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.
What Are The Principal Differences Between The Lambda And Def?
Lambda Vs Def.
def can hold multiple expressions while lambda is a uni-expression function.
def generates a function and designates a name so as to call it later. lambda forms a function and returns the function itself.
def can have a return statement. lambda can’t have return statements
lambda supports to get used inside a list and dictionary.
Write A Reg Expression That Confirms An Email Id Using The Python Reg Expression Module <Re>?
Python has a regular expression module <re>.
Check out the <re> expression that can check the email id for .com and .co.in subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
What Do You Think Is The Output Of The Following Code Fragment? Is There Any Error In The Code?
list = ['a', 'b', 'c', 'd', 'e']
print (list[10:])
The result of the above lines of code is []. There won’t be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that exceeds the member count (for example, attempting to access list[10] as given in the question) would yield an IndexError. By the way, retrieving only a slice at an opening index that surpasses the no. of items in the list won’t result in an IndexError. It will just return an empty list.
Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For The Same?
No, Python does not have a Switch statement, but you can write a Switch function and then use it.
What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence?
range() generates a list of numbers, which is used to iterate over for loops.
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
range(stop)
stop: It is the no. of integers to generate and starts from zero. eg. range(3) == [0, 1, 2].
range([start], stop[, step])
start: It is the starting no. of the sequence.
stop: It specifies the upper limit of the sequence.
step: It is the incrementing factor for generating the sequence.
Points to note:
Only integer arguments are allowed.
Parameters can be positive or negative.
The <range()> function in Python starts from the zeroth index.
What Are The Optional Statements That Can Be Used Inside A <Try-Except> Block In Python?
There are two optional clauses you can use in the <try-except> block.
The <else> clause
It is useful if you want to run a piece of code when the try block doesn’t create any exception.
The <finally> clause
It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.
How Does The Ternary Operator Work In Python?
The ternary operator is an alternative for the conditional statements. It combines of the true or false values with a statement that you need to test. The syntax would look like the one given below.
[onTrue] if [Condition] else [onFalse]
x, y = 35, 75
smaller = x if x < y else y
print(smaller)
What Does The <Self> Keyword Do?
The <self> keyword is a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as hidden parameter.
What Are Different Methods To Copy An Object In Python?
There are two ways to copy objects in Python.
copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.
What Is The Purpose Of Doc Strings In Python?
In Python, documentation string is popularly known as doc strings. It sets a process of recording Python functions, modules, and classes.
Which Python Function Will You Use To Convert A Number To A String?
For converting a number into a string, you can use the built-in function <str()>. If you want an octal or hexadecimal representation, use the inbuilt function <oct()> or <hex()>.
How Do You Debug A Program In Python? Is It Possible To Step Through Python Code?
Yes, we can use the Python debugger (<pdb>) to debug any Python program. And if we start a program using <pdb>, then it let us even step through the code.
List Down Some Of The PDB Commands For Debugging Python Programs?
Here are a few PDB commands to start debugging Python code.
Add breakpoint – <b>
Resume execution – <c>
Step by step debugging – <s>
Move to next line – <n>
List source code – <l>
Print an expression – <p>
What Is The Command To Debug A Python Program?
The following command helps run a Python program in debug mode.
$ python -m pdb python-script.py
Why And When Do You Use Generators In Python?
A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.
We can replace loops with generators for efficiently calculating results involving large data sets.
Generators are useful when we don’t want all the results and wish to hold back for some time.
Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
What Does The <Yield> Keyword Do In Python?
The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.
See the example below.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
output: sun mon
How To Convert A List Into Other Data Types?
Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.
Turn A List Into A String.
We can use the <”.join()> method which combines all elements into one and returns as a string.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)
output: sun mon tue wed thu fri sat
Turn A List Into A Tuple.
Call Python’s <tuple()> function for converting a list into a tuple. This function takes the list as its argument. But remember, we can’t change the list after turning it into a tuple because it becomes immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
Turn A List Into A Set.
Converting a list to a set poses two side-effects.
Set doesn’t allow duplicate entries, so the conversion will remove any such item if found.
A set is an ordered collection, so the order of list items would also change.
However, we can use the <set()> function to convert a list to a set.
weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
Turn A List Into A Dictionary.
In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.
However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.
Passing the tuples into the <dict()> function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}
How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?
Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.
Count The Occurrences Of An Individual Item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
output: 3
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.
For example:
config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
import config
config.x = 1
main.py:
import config
import mod
print config.x
How Do I Copy An Object In Python?
In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a copy() method:
newdict = olddict.copy()
Sequences can be copied by slicing:
new_l = l[:]
What Are The Built-In Types Available In Python?
Here is the list of most commonly used built-in types that Python supports:
Immutable built-in types of Python
Numbers
Strings
Tuples
Mutable built-in types of Python
List
Dictionaries
Sets
How To Find Bugs Or Perform Static Analysis In A Python Application?
You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
When Is The Python Decorator Used?
Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.
What Is The Key Difference Between A List And The Tuple?
List Vs Tuple.
The major difference between a list and the tuple is that the list is mutable while tuple is not. A tuple is allowed to be hashed, for example, using it as a key for dictionaries.
Intuit Most Frequently Asked Latest Python Interview Questions Answers |
How Does Python Handle The Memory Management?
Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
And it’s the Python memory manager that handles the Private heap. It does the required allocation of the heap for Python objects.
Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.
What Are The Principal Differences Between The Lambda And Def?
Lambda Vs Def.
def can hold multiple expressions while lambda is a uni-expression function.
def generates a function and designates a name so as to call it later. lambda forms a function and returns the function itself.
def can have a return statement. lambda can’t have return statements
lambda supports to get used inside a list and dictionary.
Write A Reg Expression That Confirms An Email Id Using The Python Reg Expression Module <Re>?
Python has a regular expression module <re>.
Check out the <re> expression that can check the email id for .com and .co.in subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
What Do You Think Is The Output Of The Following Code Fragment? Is There Any Error In The Code?
list = ['a', 'b', 'c', 'd', 'e']
print (list[10:])
The result of the above lines of code is []. There won’t be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that exceeds the member count (for example, attempting to access list[10] as given in the question) would yield an IndexError. By the way, retrieving only a slice at an opening index that surpasses the no. of items in the list won’t result in an IndexError. It will just return an empty list.
Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For The Same?
No, Python does not have a Switch statement, but you can write a Switch function and then use it.
What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence?
range() generates a list of numbers, which is used to iterate over for loops.
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
range(stop)
stop: It is the no. of integers to generate and starts from zero. eg. range(3) == [0, 1, 2].
range([start], stop[, step])
start: It is the starting no. of the sequence.
stop: It specifies the upper limit of the sequence.
step: It is the incrementing factor for generating the sequence.
Points to note:
Only integer arguments are allowed.
Parameters can be positive or negative.
The <range()> function in Python starts from the zeroth index.
What Are The Optional Statements That Can Be Used Inside A <Try-Except> Block In Python?
There are two optional clauses you can use in the <try-except> block.
The <else> clause
It is useful if you want to run a piece of code when the try block doesn’t create any exception.
The <finally> clause
It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.
How Does The Ternary Operator Work In Python?
The ternary operator is an alternative for the conditional statements. It combines of the true or false values with a statement that you need to test. The syntax would look like the one given below.
[onTrue] if [Condition] else [onFalse]
x, y = 35, 75
smaller = x if x < y else y
print(smaller)
What Does The <Self> Keyword Do?
The <self> keyword is a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as hidden parameter.
What Are Different Methods To Copy An Object In Python?
There are two ways to copy objects in Python.
copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.
What Is The Purpose Of Doc Strings In Python?
In Python, documentation string is popularly known as doc strings. It sets a process of recording Python functions, modules, and classes.
Which Python Function Will You Use To Convert A Number To A String?
For converting a number into a string, you can use the built-in function <str()>. If you want an octal or hexadecimal representation, use the inbuilt function <oct()> or <hex()>.
How Do You Debug A Program In Python? Is It Possible To Step Through Python Code?
Yes, we can use the Python debugger (<pdb>) to debug any Python program. And if we start a program using <pdb>, then it let us even step through the code.
List Down Some Of The PDB Commands For Debugging Python Programs?
Here are a few PDB commands to start debugging Python code.
Add breakpoint – <b>
Resume execution – <c>
Step by step debugging – <s>
Move to next line – <n>
List source code – <l>
Print an expression – <p>
What Is The Command To Debug A Python Program?
The following command helps run a Python program in debug mode.
$ python -m pdb python-script.py
Why And When Do You Use Generators In Python?
A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.
We can replace loops with generators for efficiently calculating results involving large data sets.
Generators are useful when we don’t want all the results and wish to hold back for some time.
Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
What Does The <Yield> Keyword Do In Python?
The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.
See the example below.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
output: sun mon
How To Convert A List Into Other Data Types?
Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.
Turn A List Into A String.
We can use the <”.join()> method which combines all elements into one and returns as a string.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)
output: sun mon tue wed thu fri sat
Turn A List Into A Tuple.
Call Python’s <tuple()> function for converting a list into a tuple. This function takes the list as its argument. But remember, we can’t change the list after turning it into a tuple because it becomes immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
Turn A List Into A Set.
Converting a list to a set poses two side-effects.
Set doesn’t allow duplicate entries, so the conversion will remove any such item if found.
A set is an ordered collection, so the order of list items would also change.
However, we can use the <set()> function to convert a list to a set.
weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
Turn A List Into A Dictionary.
In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.
However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.
Passing the tuples into the <dict()> function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}
How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?
Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.
Count The Occurrences Of An Individual Item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
output: 3
Post a Comment