0% found this document useful (0 votes)
2 views

Python (1)

The document provides a comprehensive overview of Python programming, covering fundamental concepts such as variables, data types, operators, and functions. It explains the features of Python, including its simplicity, readability, and versatility for various applications. Additionally, it outlines differences between various data structures in Python, such as lists, tuples, sets, and dictionaries, along with their mutability and usage.

Uploaded by

Satyajit Ligade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python (1)

The document provides a comprehensive overview of Python programming, covering fundamental concepts such as variables, data types, operators, and functions. It explains the features of Python, including its simplicity, readability, and versatility for various applications. Additionally, it outlines differences between various data structures in Python, such as lists, tuples, sets, and dictionaries, along with their mutability and usage.

Uploaded by

Satyajit Ligade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

PYTHON

Q.1 What is programming?


Q.2 What is Python?
Q.3 What are the Features of Python?
Q.4 What is Variable?
Q.5 What are Identifiers?
Q.6 What are the reserved Keywords in Python?
Q.7 What is the difference between IS operator and == operator?
Q.8 Explain about Ternary Operator or Conditional operator?
Q.9 What are various inbuilt data types available in python?
Q.10 Explain mutability and immutability with an example?
Q.11 In python which objects are mutable and which objects are immutable?
Q.12 Explain the differences between list and tuple?
Q.13 What is the difference between set and frozen set?
Q.14 What is the difference between list & Dict?
Q.15 In Dict duplicate key is not allowed. But values can be duplicated. If we trying to add new entry
(Key-value pair) with duplicate key what will be happened?
Q.16 What is the difference between list and set?
Q.17 How to reverse string by using slice operator?
Q.18 Explain Slice operator and its syntax?
Q.19 What are the various differences between Normal function and Lambda Function (Anonymous)?
Q.20 What is functions in python?
Q.21 How Memory is managed in Python?
Q.22 What is the difference between *args and **kwargs?
Q.23 What is Lambda Function or Anonymous function?
Q.24 Explain about filter function?
Q.25 What is Dynamically typed language in Python?
Q.26 Explain about map () function?
Q.27 Explain about reduce () function?
Q.28 Explain about generator () Function?
Q.29 Explain about decorator () function?
Q.30 List Comprehension and Dictionary Comprehension in python?
Q.31 File Handling in Python?
Q.32 Exception Handling in Python?
Q.33 Explain Pandas and Numpy?
Q.34 Local and Global Variable?
Q.35 How to convert tuple into list?
Q.36 Multithreading in Python?
Q.37 Explain Typecasting in Python
Q. 1 What Is Programming?
Ans: Just like we use English, Hindi, Marathi to communicate with each other, we use programming
language like python to communicate with computer, programming is the way to instruct the
computer to perform various task.
Q.2 What is Python?
Ans: Python is very simple and easy to understandable language which feels like reading simple English
statements. This Pseudo code nature of python make it easy to learn and understandable by
beginners.
It can be Used for:
Console Applications
Windows / Desktop Applications
Web Applications
Machine Learning
Apart from these types of application mentioned above it can be used for many more types of
applications.
Python is created by Guido Rossum in 1989.
The Idea of python started in early 1980’s but the real implementation started in 1989 and It was
finally published in 1991 (27 Feb 1991).
Q.3 What are the Features of Python?
Ans: Python is simple, easy to learn, read and write.
Python language is freely available and source code is also available. So, it is an open-source
programming language.
Python Language is more expressive than most of the language, means it is more understandable
and readable.
Python can run equally on different platforms, such windows, Linux, Unix and Macintosh etc. so we
can say that python is portable language.
High level Language.
Python supports procedure-oriented programming as well as object-oriented programming l
Python has large and broad library which provides rich set of modules and functions for rapid
application development.
Q.4 What is Variable?
Ans: A variable is the name given to a memory allocations in a program.
A variable is a container to store values.
Ex: a = 234, B = “Umesh” ,C = 24.56
Where A, B and C are the variables that store respective data
Q.5 What are Identifiers?
Ans: An identifier can denote various entities like variable type, subroutines, labels, functions, packaging
and so on.
Ex: a = “Umesh Rathod” Where a is an Identifier or a Variable.

Q.6 What are the reserved Keywords in Python?


Ans: Reserved words in python known as Keyword’s, they can’t be used as variable names as their
meaning is already reserved.
Example to see all the keywords: Import keywords
Print (Keywords.kwlist)
Q.7 What is the difference between IS operator and == operator?
In general, is operator meant for reference comparison or address comparison. i.e. if two
references are pointing the same object, then only is operator returns True.
== operator meant for content comparison. i.e. even though objects are different, if the content is
the same then == operator returns True.
Example:
L1 = [10,20,30,40]
L2 = [10,20,30,40]
Print (L1 is L2) # False
Print (L1 = = L2) # True
L3 = L1
Print (L1 is L3) #True
Print (L1 == L3) #True
Q.8 Explain about Ternary Operator or Conditional operator?
x = First value if Condition else Second value
If condition is True first value will be considered, otherwise second value will be considered
Ex:
# Find max of 2 given numbers
A = int (input (‘Enter first value:’))
B = int (input (‘Enter second value:’))
Max = A if A>B else B
Print (‘Maximum value:’, max)
#Find Biggest of 3 numbers
A = int (input (‘Enter first value:’))
B = int (input (‘Enter second value:’))
C = int (input (‘Enter third value:’))
Biggest_value = A if A>B and A>C else B if B>C else C
Print (f’ Biggest value: {Biggest_value})
# Nesting of Ternary operator is possible.
Q.9 What are various inbuilt data types available in python?
1. int
2. float
3. complex
4. str(string)
5. bool
6. list
7. tuple
8. set
9. dict
10. frozenset
11. bytes
12. bytearray
13. range
# The first five data types are considered as Fundamental datatypes of python.
Q.10 Explain mutability and immutability with an example?
Mutable means changeable whereas immutable means non changeable.
Once we create an object, if we are allowed to change its content that object is said to be mutable
Mutable datatypes Such as: List [], SET (), and Dictionary {}
Example:
L = [10,20,30,40]
Print (‘Before modification:’, L)
Print (‘address of list before modification:’, id(L))
L (2) = 7777
Print (‘after modification:’, L)
Print (‘address of list after modification:’, id(L))
Once we create object, we are not allowed to change its content then that object is said to
immutable datatypes such as: string, number, Tuple ().
Example:
T = (10,20,30,40)
T (2) = 457 # Type Error: ‘tuple’ object does not support item assignment
Example:
# String object is immutable
S = ‘abcdef’
S [0] = ‘x’ # type Error: ‘str’ object does not support item assignment
Q.11 In python which objects are mutable and which objects are immutable?
Ans: 1. int ---> Immutable
2. float ---> Immutable
3. complex ---> Immutable
4. str(string) ---> Immutable
5. bool ---> Immutable
6. list ---> mutable
7. tuple ---> Immutable
8. set --->mutable
9. dict ---> Immutable
10. frozenset ---> Immutable
11. bytes ---> mutable
12. bytearray ---> Immutable
# All fundamental datatypes objects in python are immutable
*Q.12 Explain the differences between list and tuple?
LIST TUPLE
List is a group of commas separated values Tuple is a group of commas separated values within
within square brackets and square brackets parenthesis and parenthesis are optional Ex: t =
are mandatory (10,20,30,40)
Ex: l = [10,20,30,40] Ex: t = 10,20,30,40
List objects are mutable. i.e. once we create Tuple objects are immutable. i.e once we create tuple
list object, we can change its content object, we are not allowed to change its content
Ex: l [0] = 7546 Ex: t[0] = 7546 #type Error

List objects require more memory Tuple objects require less memory
Ex: Ex:
Import sys Import sys
l = [10,20,30,40,50,60,70,80,90] t = (10,20,30,40,50,60,70,80,90)
print (‘The size of List:’, sys.getsize (l)) print (‘The size of tuple:’, sys.getsize (t))
O/P: The size of List: 136 O/P: The size of tuple: 120
If the content is not fixed and keep on If content is fixed and never changes then we should go for
changing then it is recommended to go for tuple objects.
list objects. Ex: To store YouTube Ex: Allowed input values for vendor machine.
comments Ex: 2
Ex: 2 t1 = (10,20,30,40,50,60,70,80,90)
l1 = [10,20,30,40,50,60,70,80,90] t2 = (10,20,30,40,50,60,70,80,90)
l2 = [10,20,30,40,50,60,70,80,90] print(id(t1))
print(id(l1)) print(id(t2))
print(id(l2)) O/P:
O/P: 2274228629056
2274230408512 2274228629056
2274230411520
List objects won’t be reusable tuple objects are reusable

Performance of list is low, i.e. operations on Performance of tuple is high, i.e. operations on tuple
list object require more time object require less time
Comprehension concept is applicable for Comprehension concept is not applicable for tuple
list
List objects are unhashable type and hence tuple objects are hash able type and hence we can store in
we cannot store in set and in Dict keys set and in Dict keys
Unpacking is possible in list but packing is Both packing and unpacking is possible in tuple
not possible

Q.13 What is the difference between set and frozen set?

SET FROZENSET
Set is mutable Frozenset is immutable
Ex: Ex:
S = {10,20,30,40} s = {10,20,30,40}
S.add (50) fs = frozenset(s)
Print(S) # {40,10,50,20,30} fs.add (50)
Print(fs) # Attribute Error: ‘frozen set’ Object has no
attribute ‘add’
We can add new elements to the set as it is As Frozen set is immutable, add, remove such type of
mutable terminology is not applicable
Q.14 What is the difference between list & Dict?
Ans:
LIST DICT
list is a comma group separated individual Dict is a group of commas separated key – value pairs
objects within square bracket within Curley braces
Example: l = [10,20,30,40] Example: D = {‘A’: ‘Apple’, ‘B’: ‘Banana’, ‘C’: ‘Carrot’}

In list, Insertion order is preserved. In Dict, all key value will be stored based on hash code of
keys hence Insertion order is not preserved. But from 3.7
version onwards, the Dict functionality internally replaced
with order Dict functionality. Hence 3.7 version onwards in
case of normal Dict also insertion order can be
guaranteed.

In list duplicate objects are allowed. In Dict duplicate keys are not allowed. But values can be
duplicated. If we trying to add new entry (Key-value pair)
with duplicate key then old value will be replaced with
new value.
In list we can access objects by using index, In Dict we can access values by using keys
which is zero based. i.e index of first object
is zero.
Example: d[10]

In list, object need not to be hashable In Dict, all keys must be hashable.

Q.15 In Dict duplicate key is not allowed. But values can be duplicated. If we trying to add new entry
(Key-value pair) with duplicate key what will be happened?
Ans: In Dict duplicate keys are not allowed. But values can be duplicated. If we trying to add new entry
(Key-value pair) with duplicate key then old value will be replaced with new value.
Example:
D = {}

Q.16 What is the difference between list and set?


Ans:
LIST SET
list is a group comma separated individual Set is a group comma separated individual objects within
objects within square bracket Curley bracket
Eg: L = [10,20,30,40] Eg: S = {10,20,30,40}

In list, Duplicates are allowed In set, Duplicates are not allowed


In list, Insertion order is preserved In set, objects will be inserted based on hash code hence
Insertion order is not preserved
In list, Objects need not be hash able In Set, Objects should be hash able
In list, Indexing and slicing are applicable. In Set, indexing and slicing are not applicable

Q.17 How to reverse string by using slice operator?


Ans: S [ : : -1]
Eg: S = ‘abcdefg’
Print (‘original String’, S)
Print (‘Reversed string’, S [ : : -1])
Q.18 Explain Slice operator and its syntax?
If we want to access part (piece, slice or element) of given sequence then we should go for slice
operator. The sequence can be list, tuple or string etc.
Syntax:
S [Begin: end: step]
Step value can be either +ve or -ve but not zero
If step value is +ve then we have to consider from begin index to end-1 index in forward direction.
If step value is -ve then we have to consider from end index to end+1 index in backward direction.
Note:
1.In forward direction if end value is zero then the result is always empty.
2.In backward direction if end value is -1 then the result is always empty.
Example:
S = ‘abcdefghij’
S [1:6:2] === > ‘bdf’
S [4:7:-1] === > hgf
Q.19 What are the various differences between Normal function and Lambda Function (Anonymous)?
Ans:
NORMAL FUNCTION LAMBDA FUNCTION (ANONYMOUS)
It is a named function and we can define by It is a nameless (Anonymous) function and we can define
using def keyword. by using lambda keyword.
We have to write return statement We are not required to write return statement explicitly
explicitly to return some value. to return some value, because lambda function internally
has return statement.
If we want to use function multiple times If we want a function just for instant use (i.e.one time
then we should go for Normal function. usage) then we should go for lambda function.
Length of code is more and hence Length of code is very less (concise code) and hence
readability is reduced. readability is improved.

Q.20 What is functions in python?


Ans: A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result. In Python, a function is a group
of related statements that performs a specific task. Functions help break our program into smaller
and modular chunks. As our program grows larger and larger, functions make it more organized and
manageable. Furthermore, it avoids repetition and makes the code reusable.
sExample: Def myfunction ():

Print ("Hello World")


myfunction ()

Q.21 How Memory is managed in Python?


Ans: Internally managed by the Heap data structure.
“Heap” memory, also known as “dynamic” memory.
is an alternative to local stack memory.
Heap space in Python primarily maintains all objects and data structures.
stack space, contains all the references to the objects in heap space.
*Q.22 What is the difference between *args and **kwargs?
Ans:
*ARGS **KWARGS
*args ------ > variable length argument **kwargs ----- > variable length keyword arguments
f1 (*args): f1 (**kwargs):

If function with *args argument, then we We can call this function by passing any number of
can call that function by passing any keyword arguments including zero number and with all
number of values including zero number. these keyword arguments, a dictionary will be created.
With all these values, tuple will be created.

Eg: 1 Eg: 1
def f1 (*args): def f1 (**kwargs):
print (args) print (kwargs)
f1 () f1 (name ='Umesh', roll No='100', marks='90')
f1 (10)
f1 (10,20)
f1 (10,20,30)
Eg: 2
def sum (*args):
total = 0
for x in args:
total = total + x
print ('The sum: ', total)
sum ()
sum (10)
sum (10,20)

Q.23 What is Lambda Function or Anonymous function?


Ans: Sometimes we declare a function without any name, such type of nameless function is called
lambda function or anonymous function.
The main objective of anonymous function is just for instant use.
Normal Function:
We can define normal function by using def keyword
Def squareit (n):
Return n*n
Lambda Function:
We can define anonymous function by using lambda keyword
Lambda n: n*n
Syntax:
lambda argument_list: expression
By using lambda function, we can write very concise code, so that readability of code will be
improved.
Example: Create a lambda function to find square of given number?
S = lambda n: n*n
Print (‘The square of 4:’, S (4))
Print (‘The square of 5:’, S (5))
O/P:
The square of 4: 16,
The square of 5 25
Q.24 Explain about filter function?
Ans: We can use filter () function to filter values from the given sequence based on some condition.
Filter (function, sequence)
Where argument function is responsible to perform conditional check and it should be Boolean
valued function.
For every element in the given sequence, this function will be applied and if it returns True then
only the value will be considered in the result.
Without Lambda Function:
Example:
def is_even (x):
if x%2 == 0:
return True
else:
return False
l1 = [0,10,15,20,23,30,35]
l2 = list (filter (is_even, l1))
print (l2)
O/P:
[0, 10, 20, 30]
With Lambda Function:
Example:
l1 = [0,10,15,20,23,30,35]
l2 = list (filter (lambda x: x%2 == 0, l1))
print (l2)
O/P:
[0, 10, 20, 30]

Q.25 What is Dynamically typed language in Python?


Ans: Yes, it is. Python is a dynamically typed language. We don't have to declare the type of variable while
assigning a value to a variable in Python. Other languages like C, C++, Java, etc.., there is a strict
declaration of variables before assigning values to them.
Python don't have any problem even if we don't declare the type of variable. It states the kind of
variable in the runtime of the program. So, Python is a dynamically typed language.
Example:
## assigning a value to a variable
X = [1,2,3,4]
## x is a list here
Print(type(x))
## reassigning a value to the ‘X’
X = True
## X is a bool here
Print(type(X))
Output:
< class ‘list’ >
< class ‘bool’ >
Q.26 Explain about map () function?
Ans: map () function returns a map object (which is an iterator) of the results after applying the given
function to each item of a given iterable (list, tuple etc.)
Syntax:
Map (Fun, iter)
Parameter:
Fun: It is a function to which map passes each element of given iterable.
Iter: It is iterable which is to be maped.
Example:
numbers = (1, 2, 3, 4)

result = map(lambda x: x + x, numbers)


print(list(result))
Q.27 Explain about reduce () function?
Ans: The reduce (fun, seq) function is used to apply a particular function passed in its argument to all
of the list elements mentioned in the sequence passed along. This function is defined in
“functools” module.
Working:
At first step, first two elements of sequence are picked and the result is obtained.
Next step is to apply the same function to the previously attained result and the number just
succeeding the second element and the result is again stored.
This process continues till no more elements are left in the container.
The final returned result is returned and printed on console.
Example:
Import functools
List = [1,2,3,4,5,6]
Print (“The sum of the list element is:”, end = “”)
Print (functools.reduce (lambda a, b: a if a > b, list))
*Q.28 Explain about generator () Function?
Ans: Generator-Function: A generator-function is defined like a normal function, but whenever it
needs to generate a value, it does so with the yield keyword rather than return. If the body of a
def contains yield, the function automatically becomes a generator function.
Generator-Object: Generator functions return a generator object. Generator objects are used
either by calling the next method on the generator object or using the generator object in a “for
in” loop.
Example: Fibonacci Numbers
Def fib (limit)
a, b = 0, 1
While a < limit:
Yield a
a, b = b, a + b
x = fib (5)
print (next (x))
print (next (x))
print (next (x))
print (next (x))
print (next (x))
OR
For i in fib (5):
Print(i)
*Q.29 Explain about decorator () function?
Ans: Decorators are a very powerful and useful tool in Python since it allows programmers to modify
the behaviour of a function or class. Decorators allow us to wrap another function in order to
extend the behaviour of the wrapped function, without permanently modifying it. But before
diving deep into decorators let us understand some concepts that will come in handy in learning
the decorators.
Example:
def hello_decorator (func):
def inner1 ():
print (“Hello, this is before function execution”)
func ()
print (“This is after function execution”)
return inner1
def function_to_be_used ():
print (“This is inside the function ! !”)
function_to_be_used = hello_decorator (function_to_be_used)
function_to_be_used
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
Q.30 List Comprehension and Dictionary Comprehension in python?
Ans: Python List comprehension provides a much shorter syntax for creating a new list based on the
values of an existing list.
Advantages of List Comprehension:
More time-efficient and space-efficient than loops
Require fewer lines of code
Transforms iterative statements into formula
Syntax of List Comprehension:
NewList = [ expression(element) for element in oldList if condition]
Example: Even list using list comprehension
List = [i for i in range (11) if i % 2 = = 0]
Print (list)
Dictionary Comprehension:
Python allows dictionary comprehensions. We can create dictionaries using simple expressions.
Syntax for Dict Comprehension: {key: value for (key, value) in iterable}
We have two lists’ names keys and value and we are iterating over them with the help of zip ()
function
Example:
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
myDict = {k:v for (k,v) in zip (keys, values)}
print (myDict)
Q.31 File Handling in Python?
Ans: Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files.
Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open () but at the time of opening, we have
to specify the mode, which represents the purpose of the opening file.
f = open (filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data, then it
will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.

Q.32 Exception Handling in Python?


Ans: Exception is an error that occurs during the execution of a program.
difference between error and exceptions:
ERROR: like hardware failures or syntax errors in our code.
Exceptions: we can write code to catch a ValueError exception
that might be raised if we try to convert a string to an int
and the string can’t be parsed as a valid integer.
Some examples of built-in exceptions in Python include the following:
1.ImportError: An error that occurs when a module or dependency cannot be found.
2.ValueError: An error that occurs when a built-in operation or function receives an argument that
has the right type but an inappropriate value.
3.KeyError: An error that occurs when a dictionary does not have a specific key.
4.IndexError: An error that occurs when a list or tuple is accessed with an index that is out of range.
How do you handle exceptions in Python?
exceptions can be handled using the try-except statement.
This statement allows you to catch errors and exceptions that might occur in your code, and then
handle them accordingly.
Example:
you might use the try-except statement to catch an error and then print out a message to the user.
Q.33 Explain Pandas and Numpy?

Ans: NumPy is a library for Python that adds support for large, multi-dimensional arrays and matrices,

along with a large collection of high-level mathematical functions to operate on these arrays.

Pandas is a high-level data manipulation tool that is built on the NumPy package. The key data

structure in Pandas is called the DataFrame. DataFrames are incredibly powerful as they allow you to

store and manipulate tabular data in rows of observations and columns.


Q.34 Local and Global Variable?
Ans: Global Variables:
Variables declared outside a function or in a 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.
Q.35 How to convert tuple into list?
Ans: call list () built in function and pass the tuple as argument to the function.
List () returns a new list generated from the items of the given tuple.
Example:
Tple = (1, 2, 3, 4)
lst = list (tple)
print (lst)
O/P: >> [1, 2, 3, 4]
Q.36 Multithreading in Python?
Ans: It just like multiprocessing,
multithreading is a way of achieving multitasking.
defined as the ability of a processor to execute multiple threads concurrently.
Multi-threading: Multiple threads can exist within one process where:
_Each thread contains its own register set and local variables (stored in stack).
_All threads of a process share global variables (stored in heap) and the program code.
Thread:
In computing, a process is an instance of a computer program that is being executed.
Any process has 3 basic components:
1. Executable program.
2. Associated data needed by the program (variables, work space, buffers, etc.)
3. Execution context of the program (State of process)
A thread is an entity within a process that can be scheduled for execution.
it is the smallest unit of processing that can be performed in an OS.
thread is a sequence of such instructions within a program that can be executed independently of
other code.
Q.37 Explain Typecasting in Python
Ans: Type Casting is the method to convert the variable data type into a certain data type in order to
the operation required to be performed by users.
Implicit Type Casting
Explicit Type Casting
Implicit Type Casting:
In this, methods, Python converts data type into another data type automatically. In this process,
users don’t have to involve in this process.
Explicit Type Casting:
In this method, Python need user involvement to convert the variable data type into certain data
type in order to the operation required.
Mainly in type casting can be done with these data type function:
 Int() : Int() function take float or string as an argument and return int type object.
 float() : float() function take int or string as an argument and return float type object.
 str() : str() function take float or int as an argument and return string type object

You might also like