Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame). Python can also be translated into binary code like java.
Here are some of the latest Interview Questions and Answers for Python
1) What is Python? What are the benefits of using Python?
Answer: Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
2) What is PEP 8?
Answer: PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
3) What is pickling and unpickling?
Answer: 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.
4) How Python is interpreted?
Answer: Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
5) How memory is managed in Python?
Answer: 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.
6) What are the tools that help to find bugs or perform static analysis?
Answer: 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.
7) What are Python decorators?
Answer: A Python decorator is a specific change that we make in Python syntax to alter functions easily.
8) What is the difference between list and tuple?
Answer: The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
9) How are arguments passed by value or by reference?
Answer: Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
10) What is Dict and List comprehensions are?
Answer: They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
11) What are the built-in type does python provides?
Answer: There are mutable and Immutable types of Pythons built in types Mutable built-in types
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
Numbers
12) What is namespace in Python?
Answer: In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
13) What is lambda in Python?
Answer: It is a single expression anonymous function often used as inline function.
14) Why lambda forms in python does not have statements?
Answer: A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
15) What is pass in Python?
Answer: Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
16) In Python what are iterators?
Answer: In Python, iterators are used to iterate a group of elements, containers like list.
17) What is unittest in Python?
Answer: A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
18) In Python what is slicing?
Answer: A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
19) What are generators in Python?
Answer: The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
20) What is docstring in Python?
Answer: A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.
21) How can you copy an object in Python?
Answer: To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
22) What is negative index in Python?
Answer: Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
23) How you can convert a number to a string?
Answer: In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
24) What is the difference between Xrange and range?
Answer: Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
25) What is module and package in Python?
Answer: In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
26) Mention what are the rules for local and global variables in Python?
Answer: Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
27) How can you share global variables across modules?
Answer: To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
28) Explain how can you make a Python Script executable on Unix?
Answer: To make a Python Script executable on Unix, you need to do two things,
Script file’s mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
29) Explain how to delete a file in Python?
Answer: By using a command os.remove (filename) or os.unlink(filename)
30) Explain how can you generate random numbers in Python?
Answer: To generate random numbers in Python, you need to import command as
import random
random.random()
This returns a random floating point number in the range [0,1)
31) Explain how can you access a module written in Python from C?
Answer: You can access a module written in Python from C by following method,
Module = =PyImport_ImportModule(“<modulename>”);
32) Mention the use of // operator in Python?
Answer: It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
33) Mention five benefits of using Python?
Answer: Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
Provide easy readability due to use of square brackets
Easy-to-learn for beginners
Having the built-in data types saves programming time and effort from declaring variables
34) Mention the use of the split function in Python?
Answer: The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.
35) Explain what is Flask & its benefits?
Answer: Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.
36) Mention what is the difference between Django, Pyramid, and Flask?
Answer: Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
Like Pyramid, Django can also used for larger applications. It includes an ORM.
37) Mention what is Flask-WTF and what are their features?
Answer: Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are
Integration with wtforms
Secure form with csrf token
Global csrf protection
Internationalization integration
Recaptcha supporting
File upload that works with Flask Uploads
38) Explain what is the common way for the Flask script to work?
Answer: The common way for the flask script to work is
Either it should be the import path for your application
Or the path to a Python file
39) Explain how you can access sessions in Flask?
Answer: A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
40) Is Flask an MVC model and if yes give an example showing MVC pattern for your application?
Answer: Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example
from flask import Flask
app = Flask(_name_)
@app.route(“/”)
Def hello():
return “Hello World”
app.run(debug = True)
In this code your,
Configuration part will be
from flask import Flask
app = Flask(_name_)
View part will be
@app.route(“/”)
Def hello():
return “Hello World”
While you model or main part will be
app.run(debug = True)
41) Explain database connection in Python Flask?
Answer: Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.
Flask allows to request database in three ways
before_request() : They are called before a request and pass no arguments
after_request() : They are called after a request and pass the response that will be sent to the client
teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.
42) You are having multiple Memcache servers running Python, in which one of the memcacher server fails, and it has your data, will it ever try to get key data from that one failed server?
Answer: The data in the failed server won’t get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.
43) Explain how you can minimize the Memcached server outages in your Python Development?
Answer: When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact
Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address
Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work
Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached
44) Explain what is Dogpile effect? How can you prevent this effect?
Answer: Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value.
45) Explain how Memcached should not be used in your Python project?
Answer: Memcached common misuse is to use it as a data store, and not as a cache
Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
Memcached does not offer any form of security either in encryption or authentication
46) What Are The Rules For Local And Global Variables In Python?
Answer: In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
47) How Do I Share Global Variables Across Modules?
Answer: 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
48) How Do I Copy An Object In Python?
Answer: 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[:]
49) How Can I Find The Methods Or Attributes Of An Object?
Answer: For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.
50) Is There An Equivalent Of C’s “?:” Ternary Operator?
Answer: No
51) How Do I Convert A Number To A String?
Answer: To convert, e.g., the number 144 to the string ‘144’, use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. “%04d” % 144 yields ‘0144’ and “%.3f” % (1/3.0) yields ‘0.333’.
52) What’s A Negative Index?
Answer: Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].
Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.
53) How Do I Apply A Method To A Sequence Of Objects?
Answer: Use a list comprehension:
result = [obj.method() for obj in List]
54) What Is A Class?
Answer: A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.
A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessor methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various specific mailbox formats.
55) What Is A Method?
Answer: A method is a function on some object x that you normally call as x.name(arguments…). Methods are defined as functions inside the class definition:
class C:
def meth (self, arg):
return arg*2 + self.attribute
56) What Is Self?
Answer: Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).
57) How Do I Call A Method Defined In A Base Class From A Derived Class That Overrides It?
Answer: If you’re using new-style classes, use the built-in super() function:
class Derived(Base):
def meth (self):
super(Derived, self).meth()
If you’re using classic classes: For a class definition such as class Derived(Base): … you can call method meth() defined in Base (or one of Base’s base classes) as Base.meth(self, arguments…). Here, Base.meth is an unbound method, so you need to provide the self argument.
58) How Do I Find The Current Module Name?
Answer: A module can find out its own module name by looking at the predefined global variable __name__. If this has the value ‘__main__’, the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:
def main():
print ‘Running test…’
…
if __name__ == ‘__main__’:
main()
__import__(‘x.y.z’) returns
Try:
__import__(‘x.y.z’).y.z
For more realistic situations, you may have to do something like
m = __import__(s)
for i in s.split(“.”)[1:]:
m = getattr(m, i)
59) Where Is The Math.py (socket.py, Regex.py, Etc.) Source File?
Answer: There are (at least) three kinds of modules in Python:
1. modules written in Python (.py);
2. modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
3. modules written in C and linked with the interpreter; to get a list of these, type:
import sys
print sys.builtin_module_names
60) How Do I Delete A File?
Answer: Use os.remove(filename) or os.unlink(filename);
61) How Do I Copy A File?
Answer: The shutil module contains a copyfile() function.
62) How Do I Run A Subprocess With Pipes Connected To Both Input And Output?
Answer : Use the popen2 module. For example:
import popen2
fromchild, tochild = popen2.popen2(“command”)
tochild.write(“input\n”)
tochild.flush()
output = fromchild.readline()
63) How Do I Avoid Blocking In The Connect() Method Of A Socket?
Answer : The select module is commonly used to help with asynchronous I/O on sockets.
64) Are There Any Interfaces To Database Packages In Python?
Answer : Yes.
Python 2.3 includes the bsddb package which provides an interface to the BerkeleyDB library. Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python.
65) How Do I Generate Random Numbers In Python?
Answer : The standard module random implements a random number generator. Usage is simple:
import random
random.random()
This returns a random floating point number in the range [0, 1).
66) Can I Create My Own Functions In C?
Answer: Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C.
67) Can I Create My Own Functions In C++?
Answer: Yes, using the C compatibility features found in C++. Place extern “C” { … } around the Python include files and put extern “C” before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.
68) How Can I Execute Arbitrary Python Statements From C?
Answer: The highest-level function to do this is PyRun_SimpleString() which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including SyntaxError).
69) How Can I Evaluate An Arbitrary Python Expression From C?
Answer: Call the function PyRun_String() from the previous question with the start symbol Py_eval_input; it parses an expression, evaluates it and returns its value.
70) How Do I Interface To C++ Objects From Python?
Answer: Depending on your requirements, there are many approaches. To do this manually, begin by reading the “Extending and Embedding” document. Realize that for the Python run-time system, there isn’t a whole lot of difference between C and C++ — so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.
Answer: On Windows 2000, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:Program FilesPythonpython.exe “%1” %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.
On Windows NT, the steps taken by the installer as described above allow you to run a script with ‘foo.py’, but a longtime bug in the NT command processor prevents you from redirecting the input or output of any script executed in this way. This is often important.
The incantation for making a Python script executable under WinNT is to give the file an extension of .cmd and add the following as the first line:
@setlocal enableextensions & python -x %~f0 %* & goto :EOF
72) How Do I Debug An Extension?
Answer: When using GDB with dynamically loaded extensions, you can’t set a breakpoint in your extension until your extension is loaded.
In your .gdbinit file (or interactively), add the command:
br _PyImport_LoadDynamicModule
Then, when you run GDB:
$ gdb /local/bin/python
gdb) run myscript.py
gdb) continue # repeat until your extension is loaded
gdb) finish # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue
73) Where Is Freeze For Windows?
Answer: “Freeze” is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler; your programs don’t run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU.
74) Is A *.pyd File The Same As A Dll?
Answer: Yes .
75) How Do I Emulate Os.kill() In Windows?
Answer: Use win32api:
def kill(pid):
“””kill function for Win32″””
import win32api
handle = win32api.OpenProcess(1, 0, pid)
return (0 != win32api.TerminateProcess(handle, 0))
76) Explain About The Programming Language Python?
Answer: Python is a very easy language and can be learnt very easily than other programming languages. It is a dynamic object oriented language which can be easily used for software development. It supports many other programming languages and has extensive library support for many other languages.
77) Explain About The Use Of Python For Web Programming?
Answer: Python can be very well used for web programming and it also has some special features which make you to write the programming language very easily. Some of the features which it supports are Web frame works, Cgi scripts, Webservers, Content Management systems, Web services, Webclient programming, Webservices, etc. Many high end applications can be created with Python because of the flexibility it offers.
78) State Some Programming Language Features Of Python?
Answer: Python supports many features and is used for cutting edge technology. Some of them are
1) A huge pool of data types such as lists, numbers and dictionaries.
2) Supports notable features such as classes and multiple inheritance.
3) Code can be split into modules and packages which assists in flexibility.
4) It has good support for raising and catching which assists in error handling.
5) Incompatible mixing of functions, strings, and numbers triggers an error which also helps in good programming practices.
6) It has some advanced features such as generators and list comprehensions.
7) This programming language has automatic memory management system which helps in greater memory management.
79) How Is Python Interpreted?
Answer: Python has an internal software mechanism which makes your programming easy. Program can run directly from the source code. Python translates the source code written by the programmer into intermediate language which is again translated it into the native language of computer. This makes it easy for a programmer to use python.
80) Does Python Support Object Oriented Scripting?
Answer: Python supports object oriented programming as well as procedure oriented programming. It has features which make you to use the program code for many functions other than Python. It has useful objects when it comes to data and functionality. It is very powerful in object and procedure oriented programming when compared to powerful languages like C or Java.
81) Describe About The Libraries Of Python?
Answer: Python library is very huge and has some extensive libraries. These libraries help you do various things involving CGI, documentation generation, web browsers, XML, HTML, cryptography, Tk, threading, web browsing, etc. Besides the standard libraries of python there are many other libraries such as Twisted, wx python, python imaging library, etc.
82) State And Explain About Strings?
Answer: Strings are almost used everywhere in python. When you use single and double quotes for a statement in python it preserves the white spaces as such. You can use double quotes and single quotes in triple quotes. There are many other strings such as raw strings, Unicode strings, once you have created a string in Python you can never change it again.
83) Explain About Classes In Strings?
Answer: Classes are the main feature of any object oriented programming. When you use a class it creates a new type. Creating class is the same as in other programming languages but the syntax differs. Here we create an object or instance of the class followed by parenthesis.
84) What Is Tuple?
Answer: Tuples are similar to lists. They cannot be modified once they are declared. They are similar to strings. When items are defined in parenthesis separated by commas then they are called as Tuples. Tuples are used in situations where the user cannot change the context or application; it puts a restriction on the user.
85) Explain And Statement About List?
Answer: As the name specifies list holds a list of data items in an orderly manner. Sequence of data items can be present in a list. In python you have to specify a list of items with a comma and to make it understand that we are specifying a list we have to enclose the statement in square brackets. List can be altered at any time.
86) Explain About The Dictionary Function In Python?
Answer: A dictionary is a place where you will find and store information on address, contact details, etc. In python you need to associate keys with values. This key should be unique because it is useful for retrieving information. Also note that strings should be passed as keys in python. Notice that keys are to be separated by a colon and the pairs are separated themselves by commas. The whole statement is enclosed in curly brackets.
87) Explain About Indexing And Slicing Operation In Sequences?
Answer: Tuples, lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular item in the sequence and slicing operation allows you to retrieve an item from the list of sequence. Python starts from the beginning and if successive numbers are not specified it starts at the last. In python the start position is included but it stops before the end statement.
88) Explain About Raising Error Exceptions?
Answer: In python programmer can raise exceptions using the raise statement. When you are using exception statement you should also specify about error and exception object. This error should be related to the derived class of the Error. We can use this to specify about the length of the user name, password field, etc.
89) What Is A Lambda Form?
Answer: This lambda statement is used to create a new function which can be later used during the run time. Make_repeater is used to create a function during the run time and it is later called at run time. Lambda function takes expressions only in order to return them during the run time.
90) Explain About Assert Statement?
Answer: Assert statement is used to assert whether something is true or false. This statement is very useful when you want to check the items in the list for true or false function. This statement should be predefined because it interacts with the user and raises an error if something goes wrong.
91) Explain About Pickling And Unpickling?
Answer: Python has a standard module known as Pickle which enables you to store a specific object at some destination and then you can call the object back at later stage. While you are retrieving the object this process is known as unpickling. By specifying the dump function you can store the data into a specific file and this is known as pickling.
92) What Is The Difference Between A Tuple And A List?
Answer: A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.
Other significant difference is of the syntax. A list is defined as
list1 = [1,2,5,8,5,3,]
list2 = [“Sachin”, “Ramesh”, “Tendulkar”]
A tuple is defined in the following way
tup1 = (1,4,2,4,6,7,8)
tup2 = (“Sachin”,”Ramesh”, “Tendulkar”)
93) If Given The First And Last Names Of Bunch Of Employees How Would You Store It And What Datatype?
Answer: Either a dictionary or just a list with first and last names included in an element.
94) How Do We Write A Function In Python?
Answer: We can create a Python function in the following manner.
Step-1: to begin the function, start writing with the keyword def and then mention the function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for execution.
95) What Is A Function Call Or A Callable Object In Python?
Answer: A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fits in the same category.
96) What Is The Return Keyword Used For In Python?
Answer: The purpose of a function is to receive the inputs and return some output.
The return is a Python statement which we can use in a function for sending a value back to its caller.
97) What Is “Call By Value” In Python?
Answer: In call-by-value, the argument whether an expression or a value gets bound to the respective variable in the function.
Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.
98) What Is “Call By Reference” In Python?
Answer: We use both “call-by-reference” and “pass-by-reference” interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.This scheme also has an advantage of bringing more time and space efficiency because it leaves the need of creating local copies.
On the contrary, the disadvantage could be that a variable can get changed accidentally during a function call. Hence, the programmers need to handle in the code to avoid such uncertainty.
99) What Is The Return Value Of The Trunc() Function?
Answer: The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.
100) Is It Mandatory For A Python Function To Return A Value?
Answer: It is not at all necessary for a function to return any value. However, if needed, we can use None as a return value.
101) Write a Python program to count the number of lines in a text file.
Answer: def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(“Number of lines in the file: “,file_lengthy(“test.txt”))
Recent Comments