You are on page 1of 6

Q) List, tuple.

List:
List is a collection of objects, enclosed in square brackets and separated by commas. A
sequence data type used to store the collection of data. Lists are the simplest containers. Lists
are heterogeneous which makes it the most powerful tool in python. A single list may contain
datatypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be
altered even after their creation. Lists can be created by just placing the sequence inside the
square brackets. Lists are one of the mostly used and versatile built in types, allowing us to
store multiple items in a single variable. We can access list elements with index.
Var = ["Geeks", "for", "Geeks"]

print(Var)
Characteristics: ordered, mutable, allows duplicates.

Tuple:
Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a list
in terms of indexing, nested objects, and repetition. Tuples are immutable. Elements will be
stored in round brackets.
var = ("Geeks", "for", "Geeks")

print(var)
Characteristics: ordered, immutable, allows duplicates, can’t be appended, can’t remove
items, find items.

Dictionary:
Dictionaries are used to store data values in key: value pairs. A dictionary is a collection which
is ordered, changeable and do not allow duplicates.
When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change. Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created. Dictionaries cannot have two items with
the same key.
thisdict={
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict) Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Dictionary length: To determine how many items a dictionary has, use the len() function:
print(len(thisdict))
The values in dictionary items can be of any data type.
Q) Difference between function and method.
Method Function
Can’t be called by their names alone. Can be.
Can directly access attributes and Can’t.
properties of an object.
Must have at least 1 arg. There can be 0 arg.
Dependent on class. Independent.
Always have self as first parameter. Doesn’t have.
A method is a function that is associated A Function is a block of code that is defined
with a class or an object. outside of any class.

Q) Anonymous function.
A lambda function is a small anonymous function. A lambda function can take any number of
arguments, but can only have one expression, which is evaluated and returned. It’s a
function without a name. As we already know the def keyword is used to define a normal
function in Python. Similarly, the lambda keyword is used to define an anonymous function in
python.
Syntax: lambda arguments: expression
lambda: print ('Hello World')
Here, we have created a lambda function that prints 'Hello World'.
x = lambda a: a + 10
print (x (5)) Output: 15
x = lambda a, b: a * b
print (x (5, 6)) Output: 30

Q) Exception and exception handling.


Error: Errors are problems in a program due to which the program will stop the execution.
Exception: Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it. Errors detected during execution are called exceptions.
When a Python code throws an exception, it has two options: handle the exception
immediately or stop and quit.
Here are some of the most common types of exceptions in Python:
SyntaxError: The interpreter encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
TypeError: An operation or function is applied to an object of the wrong type, such as adding
a string to an integer.
NameError: A variable or function name is not found in the current scope.
IndexError: An index is out of range for a list, tuple, or other sequence types.
KeyError: Key isn’t found in a dictionary.
ValueError: Value isn’t found in a dictionary.
AttributeError: An attribute isn’t found on an object.
IOError: An I/O operation, such as reading or writing a file, fails.
ZeroDivisionError: An attempt is made to divide a number by zero.
ImportError: An import statement fails to find or load a module.

Exception handling: If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try: block. After the try: block,
include an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
The try: block contains statements which are susceptible for exception. If exception occurs,
the program jumps to the except: block. If no exception in the try: block, the except: block is
skipped.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions. You can also provide a
generic except clause, which handles any exception.

Q) Access specifiers.
Access modifiers are used by object-oriented programming languages like C++, java, python
etc. to restrict the access of the class member variable and methods from outside the class.
Encapsulation is an OOPs principle which protects the internal data of the class using Access
modifiers like Public, Private and Protected.
Python supports three types of access modifiers which are public, private and protected.
These access modifiers provide restrictions on the access of member variables and
methods of the class from any object outside the class.
Public: By-default the member variables and methods are public which means they can be
accessed from anywhere outside or inside the class. No public keyword is required to make
the class or methods and properties public.
Private: Class properties and methods with private access modifier can only be accessed
within the class where they are defined and cannot be accessed outside the class. In Python
private properties and methods are declared by adding a prefix with two underscores (‘__’)
before their declaration.
Protected: Class properties and methods with protected access modifier can be accessed
within the class and from the class that inherits the protected class. In python, protected
members and methods are declared using single underscore (‘_’) as prefix before their names.

Q) Arguments in functions.
Information can be passed into functions as arguments. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not more,
and not less. If you try to call the function with 1 or 3 arguments, you will get an error.
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", "Refsnes")
Default: Default values indicate that the function argument will take that value if no argument
value is passed during the function call. The default value is assigned by using the assignment
(=) operator. Default arguments are the values provided while defining the function. They
become optional when calling function. If we provide a value to a default argument during
function call, it overrides default value. Function can have any number of default arguments.
def add (a, b=5, c=10):
return (a +b +c)
print (add (3)) Output:18
Keyword: During a function call, values passed through arguments don’t need to be in the
order of parameters in the function definition. This can be achieved by keyword arguments.
def add (a, b=5, c=10):
return (a +b +c)
print (add (b=10, c=15, a=20))
Positional: During a function call, values passed through arguments should be in the order of
parameters in the function definition. This is called positional arguments.
def add (a, b, c):
return (a +b +c)
print (add (10,20,30))
Q) OOPS concepts.
OOP is a programming paradigm that uses objects and classes in programming. It aims to
implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the
programming. The main concept of oops in Python is to bind the data and the functions that
work together as a single unit so that no other part of the code can access this data.
OOPs concepts:
Class: A class is a collection of objects. A class contains the blueprints or the prototype. It is
a logical entity that contains some attributes and methods. Classes are created by keyword
class. Attributes are the variables that belong to a class.
class Classname:
#statements
Objects: The object is an entity that has a state and behaviour associated with it. It may be
any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-
point numbers, even arrays, and dictionaries, are all objects. More specifically, any single
integer or any single string is an object. The number 12 is an object, the string “Hello, world”
is an object, a list is an object that can hold other objects, and so on. You’ve been using objects
all along and may not even realize it.
obj = objName()
Inheritance: Inheritance is the capability of one class to derive or inherit the properties from
another class. The class that derives properties is called the derived class or child class and
the class from which the properties are being derived is called the base class or parent class.
The benefits of inheritance are: It provides the reusability of a code. We don’t have to write
the same code again and again. Also, it allows us to add more features to a class without
modifying it.
 Types:
Single Multilevel Hierarchical Multiple

Polymorphism: Polymorphism simply means having many forms. As part of polymorphism,


a Python child class has methods with the same name as a parent class method. It includes:

 Function overloading: Function overloading is a powerful concept in programming


that allows a programmer to define multiple functions with the same name but different
parameters or argument types. Function overloading enables code reusability, and
flexibility.
def add (a, b):
p=a + b
print(p)
def add (a, b, c):
p=a + b
print(p)
add (1,2,3) Output: 6
 Operator overloading: we can change the way operators work. For example,
the + operator will perform arithmetic addition on two numbers, merge two lists, or
concatenate two strings. This feature in Python that allows the same operator to have
different meaning according to the context is called operator overloading.
print (1 + 2)
print (“Hello” + “world”) Output: 3
Hello world
Encapsulation: It describes the idea of wrapping data and the methods that work on data
within one unit. This puts restrictions on accessing variables and methods directly. To prevent
accidental change, an object’s variable can only be changed by an object’s method. Those
types of variables are known as private variables.
Abstraction: It hides unnecessary code details from the user. Also, when we do not want to
give out sensitive parts of our code implementation and this is where data abstraction came.
Data Abstraction in Python can be achieved by creating abstract classes.

Q) Exception function handling.


Function handling in Python refers to the ability to pass functions as arguments to other
functions, return functions from functions, and assign functions to variables. This capability is
a result of Python treating functions as first-class citizens, meaning they can be manipulated
and used in the same way as any other data type.
Here are some common ways function handling is used in Python: Passing Functions as
Arguments: Functions can be passed as arguments to other functions, allowing for greater
flexibility and code reusability. Returning Functions from Functions: Functions can also return
other functions.
This is particularly useful for creating functions dynamically or based on certain conditions.
Assigning Functions to Variables: Functions can be assigned to variables, making them
callable through those variables.
Anonymous Functions (Lambda Functions): Python supports the creation of anonymous
functions using the lambda keyword. These functions are often used for short, onetime
operations. Higher-Order Functions: Higher-order functions are functions that either take one
or more functions as arguments or return a function as a result. Python provides several built-
in higher-order functions such as map(), filter(), and sorted().

You might also like