Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
81 views

Python

Python is an interpreted, high-level and general-purpose programming language. It is dynamically typed and garbage-collected. Some key benefits of Python include being easy to read and write, having extensive libraries, and being cross-platform. Python supports common data types like lists, tuples, dictionaries, strings and more. It uses namespaces to avoid naming conflicts. Functions and modules help with code organization and reuse. Python code is indented to specify blocks rather than using brackets.

Uploaded by

simeon paul seyi
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Python

Python is an interpreted, high-level and general-purpose programming language. It is dynamically typed and garbage-collected. Some key benefits of Python include being easy to read and write, having extensive libraries, and being cross-platform. Python supports common data types like lists, tuples, dictionaries, strings and more. It uses namespaces to avoid naming conflicts. Functions and modules help with code organization and reuse. Python code is indented to specify blocks rather than using brackets.

Uploaded by

simeon paul seyi
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

1.What is the difference between list and tuples in Python?

Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists
which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
2. What type of language is python? Programming or scripting?
Python is capable of scripting, but in general sense, it is considered as a
general-purpose programming language
3.Python an interpreted language. Explain.
An interpreted language is any programming language which is not in machine-level
code before runtime. Therefore, Python is an interpreted language.
4.What is pep 8?
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how
to format Python code for maximum readability.
5.What are the benefits of using Python?
The benefits of using python are-

Easy to use– Python is a high-level programming language that is easy to use, read,
write and learn.
Interpreted language– Since python is interpreted language, it executes the code
line by line and stops if an error occurs in any line.
Dynamically typed– the developer does not assign data types to variables at the
time of coding. It automatically gets assigned during execution.
Free and open-source– Python is free to use and distribute. It is open source.
Extensive support for libraries– Python has vast libraries that contain almost any
function needed. It also further provides the facility to import other packages
using Python Package Manager(pip).
Portable– Python programs can run on any platform without requiring any change.
The data structures used in python are user friendly.
It provides more functionality with less coding.
6.What are Python namespaces?
A namespace in python refers to the name which is assigned to each object in
python. The objects are variables and functions. As each object is created, its
name along with space(the address of the outer function in which the object is),
gets created. The namespaces are maintained in python like a dictionary where the
key is the namespace and value is the address of the object. There 4 types of
namespace in python-

Built-in namespace– These namespaces contain all the built-in objects in python and
are available whenever python is running.
Global namespace– These are namespaces for all the objects created at the level of
the main program.
Enclosing namespaces– These namespaces are at the higher level or outer function.
Local namespaces– These namespaces are at the local or inner function.
7.What are decorators in Python?
Decorators are used to add some design patterns to a function without changing its
structure. Decorators generally are defined before the function they are enhancing.
To apply a decorator we first define the decorator function. Then we write the
function it is applied to and simply add the decorator function above the function
it has to be applied to. For this, we use the @ symbol before the decorator.
8.What are Dict and List comprehensions?
Dictionary and list comprehensions are just another concise way to define
dictionaries and lists.

Example of list comprehension is-

x=[i for i in range(5)]


The above code creates a list as below-
[0,1,2,3,4]
Example of dictionary comprehension is-

x=[i : i+2 for i in range(5)]


The above code creates a list as below-

[0: 2, 1: 3, 2: 4, 3: 5, 4: 6]
9.What are the common built-in data types in Python?
The common built-in data types in python are-

Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1,
7.9,3+4i

List– An ordered sequence of items is called a list. The elements of a list may
belong to different data types. Eg. [5,’market’,2.4]

Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are


immutable, which means they can’t be changed. Eg. (3,’tool’,1)

String– A sequence of characters is called a string. They are declared within


single or double-quotes. Eg. “Sana”, ‘She is going to the market’, etc.

Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8}

Dictionary– A dictionary stores values in key and value pairs where each value can
be accessed through its key. The order of items is not important. Eg.
{1:’apple’,2:’mango}

Boolean– There are 2 boolean values- True and False.


10.What is the difference between .py and .pyc files?
The .py files are the python source code files. While the .pyc files contain the
bytecode of the python files. .pyc files are created when the code is imported from
some other source. The interpreter converts the source .py files to .pyc files
which helps by saving time.
11.What is slicing in Python?
Slicing is used to access parts of sequences like lists, tuples, and strings. The
syntax of slicing is-[start:end:step]. The step can be omitted as well. When we
write [start:end] this returns all the elements of the sequence from the start
(inclusive) till the end-1 element. If the start or end element is negative i, it
means the ith element from the end. The step indicates the jump or how many
elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-
1:2:2] will return elements starting from the last element till the third element
by printing every second element.i.e. [8,6,4].
12.What are Keywords in Python?
Keywords in python are reserved words that have special meaning.They are generally
used to define type of variables. Keywords cannot be used for variable or function
names. There are following 33 keywords in python-

And
Or
Not
If
Elif
Else
For
While
Break
As
Def
Lambda
Pass
Return
True
False
Try
With
Assert
Class
Continue
Del
Except
Finally
From
Global
Import
In
Is
None
Nonlocal
Raise
Yield
13.What are Literals in Python and explain about different Literals
A literal in python source code represents a fixed value for primitive data types.
There are 5 types of literals in python-

String literals– A string literal is created by assigning some text enclosed in


single or double quotes to a variable. To create multiline literals, assign the
multiline text enclosed in triple quotes. Eg.name=”Tanya”
A character literal– It is created by assigning a single character enclosed in
double quotes. Eg. a=’t’
Numeric literals include numeric values that can be either integer, floating point
value, or a complex number. Eg. a=50
Boolean literals– These can be 2 values- either True or False.
Literal Collections– These are of 4 types-
a) List collections-Eg. a=[1,2,3,’Amit’]

b) Tuple literals- Eg. a=(5,6,7,8)

c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’}

d) Set literals- Eg. {“Tanya”, “Rohit”, “Mohan”}

6. Special literal- Python has 1 special literal None which is used to return a
null variable.
14.How is memory managed in Python?
Memory is managed in Python in the following ways:

Memory management in python is managed by Python private heap space. All Python
objects and data structures are located in a private heap. The programmer does not
have access to this private heap. The python interpreter takes care of this
instead.
The allocation of heap space for Python objects is done by Python’s memory manager.
The core API gives access to some tools for the programmer to code.
Python also has an inbuilt garbage collector, which recycles all the unused memory
and so that it can be made available to the heap space.
15. What is namespace in Python?
A namespace is a naming system used to make sure that names are unique to avoid
naming conflicts.
16.What is PYTHONPATH?
It is an environment variable which is used when a module is imported. Whenever a
module is imported, PYTHONPATH is also looked up to check for the presence of the
imported modules in various directories. The interpreter uses it to determine which
module to load.
17.What are python modules? Name some commonly used built-in modules in Python?
Python modules are files containing Python code. This code can either be functions
classes or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:

os
sys
math
random
data time
JSON
18.What are local variables and global variables in Python?
Global Variables:

Variables declared outside a function or in global space are called global


variables. These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable
is present in the local space and not in the global space.
19. Is python case sensitive?
Yes. Python is a case sensitive language.
20.What is type conversion in Python?
Type conversion refers to the conversion of one data type into another.

int() – converts any data type into integer type

float() – converts any data type into float type

ord() – converts characters into integer

hex() – converts integers to hexadecimal

oct() – converts integer to octal

tuple() – This function is used to convert to a tuple.

set() – This function returns the type after converting to set.

list() – This function is used to convert any data type to a list type.

dict() – This function is used to convert a tuple of order (key, value) into a
dictionary.

str() – Used to convert integer into a string.


21.Is indentation required in python?
Indentation is necessary for Python. It specifies a block of code. All code within
loops, classes, functions, etc is specified within an indented block. It is usually
done using four space characters. If your code is not indented necessarily, it will
not execute accurately and will throw errors as well.
22.What is the difference between Python Arrays and lists
Arrays and lists, in Python, have the same way of storing data. But, arrays can
hold only a single data type elements whereas lists can hold any data type
elements.
23. What are functions in Python?
A function is a block of code which is executed only when it is called. To define a
Python function, the def keyword is used.
24.What is __init__?
__init__ is a method or constructor in Python. This method is automatically called
to allocate memory when a new object/ instance of a class is created. All classes
have the __init__ method
25.What is a lambda function?
An anonymous function is known as a lambda function. This function can have any
number of parameters but, can have just one statement.

Example:
a = lambda x,y : x+y
print(a(5, 6))
26.What is self in Python?
Self is an instance or an object of a class. In Python, this is explicitly included
as the first parameter. However, this is not the case in Java where it’s optional.
It helps to differentiate between the methods and attributes of a class with local
variables.

The self variable in the init method refers to the newly created object while in
other methods, it refers to the object whose method was called.
27.How does break, continue and pass work?
Break Allows loop termination when some condition is met and the control is
transferred to the next statement.
Continue Allows skipping some part of a loop when some specific condition is met
and the control is transferred to the beginning of the loop
Pass Used when you need some block of code syntactically, but you want to skip its
execution. This is basically a null operation. Nothing happens when this is
executed.
28. What does [::-1} do?
[::-1] is used to reverse the order of an array or a sequence.
29. What are python iterators?
Iterators are objects which can be traversed though or iterated upon.
30.How do you write comments in python?
Comments in Python start with a # character. However, alternatively at times,
commenting is done using docstrings(strings enclosed within triple quotes).
31.What are the generators in python?
Functions that return an iterable set of items are called generators.
32.What are docstrings in Python?
Docstrings are not actually comments, but, they are documentation strings. These
docstrings are within triple quotes. They are not assigned to any variable and
therefore, at times, serve the purpose of comments as well.
33.What does this mean: *args, **kwargs? And why would we use it?
We use *args when we aren’t sure how many arguments are going to be passed to a
function, or if we want to pass a stored list or tuple of arguments to a function.
**kwargs is used when we don’t know how many keyword arguments will be passed to a
function, or it can be used to pass the values of a dictionary as keyword
arguments. The identifiers args and kwargs are a convention, you could also use
*bob and **billy but that would not be wise.
34.Explain split(), sub(), subn() methods of “re” module in Python.
To modify the strings, Python’s “re” module is providing 3 methods. They are:

split() – uses a regex pattern to “split” a given string into a list.


sub() – finds all substrings where the regex pattern matches and then replace them
with a different string
subn() – it is similar to sub() and also returns the new string along with the no.
of replacements.
35.What are negative indexes and why are they used?
The sequences in Python are indexed and it consists of the positive as well as
negative numbers. The numbers that are positive uses ‘0’ that is uses as first
index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index
in the sequence and ‘-2’ as the penultimate index and the sequence carries forward
like the positive number.

The negative index is used to remove any new-line spaces from the string and allow
the string to except the last character that is given as S[:-1]. The negative index
is also used to show the index to represent the string in correct order.
36.How to remove values to a python array?
Array elements can be removed using pop() or remove() method. The difference
between these two functions is that the former returns the deleted value whereas
the latter does not.

You might also like