Oops Notes
Oops Notes
1. What is oops ?
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
2. What is class?
It is defines the attributes (data) and method (function) that all objects
class Dog:
sound = "bark"
3. What is an object?
Ans: The object is an entity that has a state and behavior associated with it.
It may be any real-world object like a mouse, keyboard, chair, table, pen,
etc.,
class Dog:
attr1 = "mammal"
attr2 = "dog"
def fun(self):
Rodger = Dog()
print(Rodger.attr1)
Rodger.fun()
4. What is a attributes?
Ans : Attributes are variables that store data associated with a class or
object.
5. What is a methods?
Ans: Methods are functions defined inside a class that perform operations
on class attributes
6. What is a state?
8. What is a inheritance?
Ans :Inheritance allows us to define a class that inherits all the methods
and properties from another class
Parent class is the class being inherited from also called base class
Child class is the class that inherits from another class, also called derived
class
class Parent:
def M1(self):
class Child(Parent):
def M1(self):
# super().M1()
ob1 = Child()
ob1.M1()
def Method1(self):
class Child(Parent):
def method2(self):
ob1 = Child()
ob1.method2()
ob1.Method1()
When a child class inherits from more than one parent class
# I am child class
class Parent1:
def Property2(self):
class Parent2:
def Property2(self):
class Parent3:
def Property3(self):
class Child(Parent1,Parent2,Parent3):
def Property4(self):
print('I am child class')
ob1 = Child()
ob1.Property2()
ob1.Property3()
# ob1.Property4()
output
# I am Parent1 class
# I am Parent3 class
class Parent1:
def Property1(self):
class Parent2:
def Property2(self):
class Parent3:
def Property3(self):
class Child(Parent1,Parent2,Parent3):
def Property4(self):
ob1 = Child()
ob1.Property1()
ob1.Property2()
ob1.Property3()
ob1.Property4()
output
# I am Parent1 class
# I am Parent2 class
# I am Parent3 class
# I am child class
When a child class becomes a parent class for another child class
class GrandFather:
def M1(self):
print('I am GrandParent')
class Parent(GrandFather):
def M2(self):
class Child(Parent):
def M3(self):
ob1.M1()
ob1.M2()
ob1.M3()
# I am GrandParent
# I am Parent class
# I am Child class
Ans :A super class or base class is a class that acts as a parent to some other
class or classes
class Mobile(ABC):
@abstractmethod
def Battery(self):
pass
@abstractmethod
def RAM(self):
pass
@abstractmethod
def Display(self):
pass
@abstractmethod
def Camera(self):
pass
class Oppo(Mobile):
def Battery(self):
def RAM(self):
def Display(self):
def Camera(self):
#Concrete (Normal)Methods
def Normal(self):
class Production(Oppo):
super().Battery()
def RAM(self):
super().RAM()
ob1 = Production()
ob1.Battery()
ob1.RAM()
Ans :A class that inherits from another class is called the subclass
11.What is an encapsulation?
Ans: Encapsulation is the building of data and methods that operate on the
data into a single unit (class).
It hides the internal state of an object from the outside and only exposes a
public interface for interacting with the object.
When defining method in a class, self must be the first parameter of each
method, although it is not explicitly passed when calling the method.
class Employee(object):
# Every class in Python has a constructor, but it's not required to define it.
# def __init__(self):
def __init__(self,Ename,Eage,Esalary,Edomain,Elocation):
#self.New_variable_name = parameter
# object.NewVariable_name = Parameter
self.age = Eage # 20
self.salary = Esalary
self.domain = Edomain
self.location = Elocation
print(self.name)
print(self.age)
print(self.domain)
print(self.salary)
print(self.location)
print()
Employee('vikas',20,20000,'PFS','Kerala')
14.What is method overloading?
Unlike some other languages like java, python does not allow defining
multiple methods with the same name but different signatures.
class Compact:
def Method1(self,a,b):
return a + b
def Method1(self,a,b,c):
return a + b +c
def Method1(self,a,b,c,d):
return a + b + c +d
ob1 = Compact()
ob1.Method1(1,2)
The subclass method overrides the superclass method with the same name.
It does not have access to self / cls and can be called without creating an
instance of the class
class MyClass:
self.value = value
@staticmethod
return max(x, y)
obj = MyClass(10)
print(MyClass.get_max_value(20, 30))
print(obj.get_max_value(20, 30))
Ans :A class method is a method that takes the class as the first argument
rather than the instance.
It's defined with the @classmethod decorator and can access and modify
class state.
class MyClass:
self.value = value
def get_value(self):
return self.value
obj = MyClass(10)
print(obj.get_value()) # Output: 10
18.What is an abstract?
Ans : Abstraction in OOP refers to hiding the complex reality while exposing
only the necessary parts.
It means that the user interacts with only the necessary attributes and
methods of an object.
Abstract Class:
Abstract classes are created by subclassing the ABC (Abstract Base Class)
class from the abc module.
from abc import ABC,abstractmethod
class Mobile(ABC):
@abstractmethod
def Battery(self):
pass
@abstractmethod
def RAM(self):
pass
@abstractmethod
def Display(self):
pass
@abstractmethod
def Camera(self):
pass
class Oppo(Mobile):
def Battery(self):
def RAM(self):
def Display(self):
def Camera(self):
#Concrete (Normal)Methods
def Normal(self):
Abstract Method:
An abstract method is a method declared in an abstract class but does not
contain an implementation.
20.What is a constructor?
Ans : A constructor is a special type of method that has the same name as
the class and is used to initialize objects of that class.
21. What is a base class and a derived class?
Base Class:
A base class is a class that provides the initial structure, attributes, and
behaviors that other classes can inherit from.
Base classes can contain methods, properties, and attributes that can be
inherited by subclasses.
Base classes can be instantiated, but they are often designed to be abstract,
meaning they contain one or more abstract methods that must be
implemented by subclasses.
Base classes are not required to inherit from any other class.
Derived Class:
Derived classes can also define their own methods, properties, and
attributes in addition to those inherited from the base class.
Derived classes can further serve as base classes for other classes, forming
a hierarchical structure of inheritance.
Derived classes are created by specifying the base class in parentheses after
the derived class name.
What is a __next__?
__next__() must return the next item in the sequence. On reaching the end,
and in subsequent calls, it must raise StopIteration.
What is a __iter__?
1) IndexError
3) Stop Iteration
The Stop Iteration is thrown when the next() function goes beyond the iterator
items.
4) Type Error
print("5" + 3)
5) Value Error
int("hello")
6) Name Error
print(non_existent_variable)
The Zero Division Error is thrown when the second operator in the division is zero.
print(5 / 0)
8) Indentation errors:
if True:
print("Indentation error")
The Key board Interrupt is thrown when the user hits the interrupt key (normally
Control-C) during the execution of the program.
try:
ignored = input()
else:
Memory Error:
def fact(a):
factors = []
if a%i == 0:
factors.append(i)
return factors
num = 600851475143
print (fact(num))
Data types in Python
Answer:
Variables in Python are reserved memory locations that store values.
Whenever a variable is created, some space is reserved in the memory.
How can we assign the same value to multiple variables in one single go?
Answer:
The same value can be assigned to multiple variables in one single go as shown in
the following code:
>>> a = b = c = "Hello World ! ! ! "
>>> a
>>> b
' Hello World ! ! ! '
>>> c
>>>
Numbers
Types of numbers supported are as follows:
Signed integers int: these can be +ve or -ve and do not have any decimal
point
24.What are the methods available for the conversion of numbers from one
type to another?
Answer:
The following functions are available to convert numbers from one form to
another.
Answer:
To work with random numbers you will have to import a random
module. .The following functions can be used:
26.What are number data types in Python?
Answer:
Number data types are the one which is used to store numeric values such
as:
integer
long
float
complex
Whenever you assign a number to a variable it becomes a numeric data
type.
27.How will you convert float value 12.6 to integer value?
Answer:
Float value can be converted to an integer value by calling int() function.
>>> a = 12.6
>>> type(a)
>>> int(a)
12
>>>
Question 11.
How will you convert real numbers to complex numbers?
Answer:
Real numbers can be converted to complex numbers as shown in the following
code:
>>> a = 7
>>> b = -8
>>> x = complex(a,b)
>>> x.real
7.0
>>> x.imag
-8.0
Keywords
t of
the python keywords, Enter any keyword to get more help.
Identifiers
>>> b = 'Hi'
>>> type(a)
<class 'str'>
>>> type(b)
>>>
>>> c = """Once upon a time in a land far far away there lived a king"""
>>> type(c)
<class 'str'>
Answer:
Concatenation of Strings can be performed using the following techniques:
1. + operator
>>>
2. Join ( ) function
The join( ) function is used to return a string that has string elements joined by a
separator. The syntax for using join( ) function, string_name.j oin(sequence)
>>> print(string1.joint(sequence))
1-2-3-4
3. % operator
>>> string1 = "HI"
>>> string3 ,
'HI THERE'
4. format( ) function
>>> string1 = "HI"
>>> string3
'HI THERE'
5. f-string
>>> string3
'HI THERE'
>>> string1*3
>>>
Question 21.
What would be the output for the following lines of code?
Answer:
'HAPPY BIRTHDAY!!!
HAPPY BIRTHDAY!!!
HAPPY BIRTHDAY!!!'
Question 22.
What is the simplest way of unpacking single characters from string “HAPPY”?
Answer:
This can be done as shown in the following code:
>>> a
'H'
>>> b
'A'
>>> c
'P'
>>> d
'P'
>>> e
'Y'
>>>
What would be the output for the following code?
>>> string1[-1:-9:-2]
Answer:
‘!!AH’
Answer:
We can retrieve a chunk of string based on the delimiters that we provide. The
split( ) operation returns the substrings without the delimiters.
Example
>>> string1.split ( )
['Happy', 'Birthday' ]
Example
>>> hr_str
'17'
>>> min_str
'06'
>>> sec_str
'56'
You can also specify, how many times you want to split the string.
>>> date_string.split("-" , 1)
['MM', 'DD-YYYY']
>>>
In case you want Python to look for delimiters from the end and then split
the string then you can use the rsplit( ) method.
>>> date_string.split("-" , 1)
['MM-DD', 'YYYY']
36. What is the difference between the splif() and partltion( ) function?
Answer:
The result of a partition function is a tup1e and it retains the delimiter.
>>> date_string.partition("-" , 1)
The partition ( ) function on the other hand looks for the delimiter from the
other end.
>>> date_string.rpartition("-")
String Methods
1) capitalize ( )
Will return a string that has first alphabet capital and the rest are in lower
case, ‘
>>> string1.capitalize ( )
'Happy birthday'
2) casefold( )
Removes case distinction in string. Often used for caseless matching. ‘
>>> string1.casefold()
'happy birthday'
3) centre( )
The function takes two arguments: (1) length of the string with padded characters
(2) padding character (this parameter is optional)
4) count( )
>>> string1.count("P")
You can also provide the start index and ending index within the string where the
search ends.
5) encode( )
Allows you to encode Unicode strings to encodings supported by python.
>>> string1.encode( )
b'HAPPY BIRTHDAY'
>>> string1.endswith('Y')
True
>>> string1.endswith('i')
False
6) endswith( )
It returns true if a string ends with the substring provided else it will return
false.
True
7) find( )
Get the index of the first occurrence of a substring in the given string.
8) format( )
The format() method formats the specified value(s) and insert them inside
the string's placeholder.
The placeholder is defined using curly brackets: {}. Read more about the
placeholders in the Placeholder section below.
The format() method returns the formatted string.
Example
Example
Example
9) index( )
It provides the position of the first occurrence of the substring in the given string.
>>> string1.index('not')
10) isalnum( )
>>> string1.isalnum( )
False
>>> string1.isalnum()
True
11) isalpha( )
>>> string1.isalpha( )
False
>>> string1.isalpha( )
True
12) isdeimal( )
>>> string1.isdecimal()
True
13) isdigit( )
>>> string1.isdigit()
False
14) islower( )
>>> string1.islower()
False
15) isnumeric( )
Returns true if the string is not empty characters of a string are numeric.
>>> string1.isnumeric()
False
16) isspace( )
>>> string1.isspace()
True
17) lower( )
>>> string1.lower()
'tiger'
18) swapcase( )
>>> string1
'TiGER'
19) Upper().
The upper() method returns a string where all characters are in upper case.
x = txt.upper()
print(x)
20) Zfill()
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the
specified length.
txt = "50"
x = txt.zfill(10)
print(x)
If the value of the len parameter is less than the length of the string, no filling is
done.
a = "hello"
b = "welcome to the jungle"
c = "10.000"
print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
21) expandtabs()
The expandtabs() method sets the tab size to the specified number of
whitespaces.
txt = "H\te\tl\tl\to"
x = txt.expandtabs(2)
print(x)
22) Tanslate()
The translate() method returns a string where some specified characters are
replaced with the character described in a dictionary, or in a mapping table.
print(txt.translate(mydict))
print(txt.translate(mytable))
x = "mSa"
y = "eJo"
mytable = str.maketrans(x, y)
print(txt.translate(mytable))
x = "mSa"
y = "eJo"
z = "odnght"
mytable = str.maketrans(x, y, z)
print(txt.translate(mytable))
If you use a dictionary, you must use ascii codes instead of characters.
mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104: None,
116: None}
print(txt.translate(mydict))
23) Title()
The title() method returns a string where the first character in every word is
upper case. Like a header, or a title.
x = txt.title()
print(x)
If the word contains a number or a symbol, the first letter after that will be
converted to upper case.
x = txt.title()
print(x)
24) Strip
Leading means at the beginning of the string, trailing means at the end.
txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt")
print(x)
You can specify which character(s) to remove, if not, any whitespaces will be
removed.
x = txt.strip()
The startswith() method returns True if the string starts with the specified value,
otherwise False
x = txt.startswith("Hello")
print(x)
x = txt.startswith("wel", 7, 20)
print(x)
26) Splitlines()
The splitlines() method splits a string into a list. The splitting is done at line breaks.
x = txt.splitlines()
print(x)
27) Rstrip()
The rstrip() method removes any trailing characters (characters at the end a
string),
txt = "banana,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x)
x = txt.rstrip()
39.What is a list?
Answer: Answer: list are used to store the multiple values in a single
variable.
List is a collection of which is ordered and changeable.
It is allow the duplicate value.
It is used to mutable. They can be change after creation
It is denoted by square brackets[]
>>> list1 = [ ]
>>> list1
[]
>>>list2
[12 , 'apple' , 90.6]
a) Append
The append() method appends an element to the end of the list.
a.append(b)
print(a)
b) Clear()
fruits.clear()
print(fruits)
c) Copy()
The copy() method returns a copy of the specified list.
x = fruits.copy()
print(x)
d) Count()
The count() method returns the number of elements with the specified
value.
x = fruits.count("cherry")
print(x)
e) Extend()
The extend() method adds the specified list elements (or any iterable) to
the end of the current list.
fruits.extend(cars)
print(fruits)
f) Index()
The index() method returns the position at the first occurrence of the
specified value
x = fruits.index("cherry")
print(x)
g) Insert()
The insert() method inserts the specified value at the specified position.
fruits.insert(1, "orange")
print(fruits)
h) Pop()
The pop() method removes the element at the specified position
fruits.pop(1)
print(fruits)
i) Remove()
The remove() method removes the first occurrence of the element with the
specified value.
fruits.remove("banana")
print(fruits)
j) Reverse()
The reverse() method reverses the sorting order of the elements.
fruits.reverse()
print(fruits)
k) Sort()
cars.sort()
print(cars)
40.list1 = [“l”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
What would be the value for the following?
list1[-3:] = [‘H’,’O’,’N’]
list1[4::3]
41.list1 = [“I”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
list2 = [‘O’,’N’,’L’ , ‘Y’]
Concatenate the two strings.
Answer:
>>> list1
['I' list1 , 'L' 'O' 'V' 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' , 'O' , 'N' , 'L' , 'Y' ]
>>>
42.list1 =[1,2,78,45,93,56,34,23,12,98,70]
list1[6:9]=[2,2,2]
What is the new value of list1?
Answer:
[1,2, 78, 45, 93, 56, 2, 2, 2, 98, 70]
43.What is the difference between append( ) and extend( ) function for lists?
Answer:
The append( ) function allows you to add one element to a list whereas
extending ( ) allows you to add more than one element to the list.
>>> list1 = [1,2, 78,45,93,56,34,23,12,98,70]
>>> list1.append(65)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, -3, -5, -7, -5]
45.list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 +=[87]
What is the value of list1?
Answer:
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, 87]
46.list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 -=[65]
What will be the output?
Answer:
The output will be TypeError: unsupported operand type(s) for -=: ‘list’
and ‘list’
47.list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
How will you delete second element from the list?
Answer:
An element can be deleted from a list using the ‘del’ keyword.
>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1
[1, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>
>>> list1 = [1, 2, ‘78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> len(list1)
12
49.list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Remove the value 78 from list1.
Answer:
A specific element can be removed from a list by providing the value to
remove( ) function.
>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1
>>> tup1[-7]
56
>>> tup1[-15]
tup2[:-l] = (1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70)
tup2[-l:] = (65,)
Dictionary
54.What is a dictionary?
Dictionary are used to store a data values in a key-value pair
Dictionary is a collection which is ordered and changeable.
It is not allow duplicate value .
It is used to mutable .They can be change after creation
It is denoted by curly braces{}.
>>> dictl = { }
>>> type(dict1)
<class 'dict'>
>>> dict2 = {'key1' :'value1', 'key2': 'value2', 'key3': 'value3', ' key4': ' value4'}
>>> dict2
>>> type(dict2)
<class 'diet'>
>>> dict3 = diet({'key1': 'value1', 'key2':' value2', 'key3': 'value3', ' key4 ':' value4' })
A. Clear()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
car.clear()
print(car)
B. Copy ()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.copy()
print(x)
C. Fromkeys()
The fromkeys() method returns a dictionary with the specified keys and the
specified value.
y=0
thisdict = dict.fromkeys(x, y)
print(thisdict)
D. Get()
The get() method returns the value of the item with the specified key.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.get("model")
print(x)
E. Item()
The items() method returns a view object. The view object contains the key-value
pairs of the dictionary, as tuples in a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.items()
print(x)
The view object will reflect any changes done to the dictionary, see example
below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.items()
car["year"] = 2018
print(x)
F. Keys()
The keys() method returns a view object. The view object contains the keys of the
dictionary, as a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.keys()
print(x)
The view object will reflect any changes done to the dictionary, see example
below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.keys()
car["color"] = "white"
print(x)
G. Pop()
The pop() method removes the specified item from the dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
car.pop("model")
print(car)
The value of the removed item is the return value of the pop() method, see
example below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.pop("model")
print(x)
H. Popitem()
The popitem() method removes the item that was last inserted into the
dictionary. In versions before 3.7, the popitem() method removes a random item.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
car.popitem()
print(car)
The removed item is the return value of the popitem() method, as a tuple, see
example below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.popitem()
print(x)
I. Setdefault()
The setdefault() method returns the value of the item with the specified key.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.setdefault("model", "Bronco")
print(x)
If the key does not exist, insert the key, with the specified value, see example
below
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.setdefault("color", "white")
print(x)
J. Update()
The specified items can be a dictionary, or an iterable object with key value pairs.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
car.update({"color": "White"})
print(car)
K. Values()
The values() method returns a view object. The view object contains the values of
the dictionary, as a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.values()
print(x)
The view object will reflect any changes done to the dictionary, see example
below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.values()
car["year"] = 2018
print(x)
Sets
56.What is a set ?
Set are used to store the multiple items in a single variable.
List is a collection which is unordered and unchangeable.
It is not allow duplicate values
It is used to mutable. They can be change after creation
It is denoted by curly braces{}.
Set can also be created using the inbuilt set() function
>>> set1
{8, 9, 10}
>>>
i. Add()
The add() method adds an element to the set.
thisset.add("orange")
print(thisset)
If the element already exists, the add() method does not add the element.
thisset.add("apple")
print(thisset)
>>> set1
ii. Clear ()
The clear() method removes all elements in a set.
fruits.clear()
print(fruits)
x = fruits.copy()
print(x)
iv. Difference()
The difference() method returns a set that contains the difference between two
sets.
z = x.difference(y)
print(z)
Meaning: The returned set contains items that exist only in the first set, and not
in both sets.
z = y.difference(x)
print(z)
v. Difference_update()
The difference_update() method removes the items that exist in both sets.
x.difference_update(y)
print(x)
y.difference_update(x)
print(y)
vi. Discard()
The discard() method removes the specified item from the set.
thisset.discard("apple")
print(thisset)
This method is different from the remove() method, because the remove()
method will raise an error if the specified item does not exist, and the discard()
method will not.
thisset.discard("banana")
print(thisset)
vii. Intersection()
The intersection() method returns a set that contains the similarity between two
or more sets.
x = {"apple", "banana", "cherry"}
z = x.intersection(y)
print(z)
Meaning: The returned set contains only items that exist in both sets, or in all sets
if the comparison is done with more than two sets.
result = x.intersection(y, z)
print(result
viii. Intersection_update()
The intersection_update() method removes the items that is not present in both
sets (or in all sets if the comparison is done between more than two sets).
x.intersection_update(y)
print(x)
print(result
ix. Isdisjoint ()
The isdisjoint() method returns True if none of the items are present in both sets,
otherwise it returns False.
z = x.isdisjoint(y)
print(z) #True
z = y.isdisjoint(x)
print(z)
x. Issubset()
The issubset() method returns True if all items in the set exists in the specified set,
otherwise it returns False.
z = x.issubset(y)
print(z) # True
print(z) #False
xi. Issuperset()
The issuperset() method returns True if all items in the specified set exists in the
original set, otherwise it returns False.
z = x.issuperset(y)
print(z)
z = x.issuperset(y)
print(z)
xii. Pop()
fruits.pop()
print(fruits)
x = fruits.pop()
print(x)
xiii. Remove()
The remove() method removes the specified element from the set.
This method is different from the discard() method, because the remove()
method will raise an error if the specified item does not exist, and the discard()
method will not
fruits.remove("banana")
print(fruits)
symmetric_difference()
The symmetric_difference() method returns a set that contains all items from
both set, but not the items that are present in both sets.
z = x.symmetric_difference(y)
print(z)
Meaning: The returned set contains a mix of items that are not present in both
sets.
x.symmetric_difference(y)
print(x)
Multiple values can be added using update( ) function.
>>> set1
>>>
Question 90.
What methods are used to remove value from sets?
Answer:
(1) discard( )
(2) remove ( )
Pop()
CONTROL FLOW
1. What are control flow statements in Python?
if statements execute code conditionally based on a boolean expression.
while loops repeatedly execute a block of code until a specific condition
becomes false.
for loops iterate over a sequence of elements and execute a block of code
for each element.
2. What are control flow statements in Python?
Control flow statements control the execution flow of your program based
on conditions and loops. They allow you to make decisions and perform
repetitive tasks efficiently.
3. What are the different types of control flow statements in Python?
if statements: Execute code blocks based on boolean conditions.
else statements: Execute code blocks if an if statement condition is
False.
elif statements: Combine multiple if statements with additional
conditions.
while loops:
for loops:
break statements: Exit a loop prematurely.
continue statements: Skip the current iteration and continue to the next
in a loop.
pass statements: Act as placeholders for empty code blocks.
4. How do you use if statements and conditional operators?
Use if statements with comparison operators like ==, <, >, <=, >=, and !=
to check conditions and execute relevant code blocks.
5. How do you use while and for loops?
Use while loops when the number of iterations is unknown and for loops
when iterating over a sequence of elements with a known length.
6. How do you use break and continue statements inside loops?
Use break to exit a loop early and continue to skip the current iteration
and move to the next.
Functions:
7. What are functions in Python?
Functions are reusable blocks of code that perform specific tasks and
can be called multiple times throughout your program. They help to
modularize your code, improve its organization, and promote code
reuse.
4th. ascii()
Returns String Containing Printable Representation
5th. bin()
this function is used to convert an integer to the equal binary string
6th. bool()
Converts the given Value to Boolean
Python bool() is one of the Python programming language‘s data types.
Booleans are derived from mathematics and arithmetic and are used to
represent truth value
7th. bytearray()
the method is used to return an array of given byte size
8th. bytes()
the method is used to return an immutable bytes object
9th. callable()
this method checks if the Object is Callable
10th. chr()
From an Integer, this function returns a Character (a string).
11th. classmethod()
for a given function, returns the class method
12th. compile()
This method returns a Python code object.
In python, if the user has a string of Python code that he wants to compile so that
it can be run it later.
This is done through the python compile method.
It accepts source code as the input, and the output will be a code object that is
ready to run.
13th. complex()
Creates a Complex Number
The python complex function converts the strings or numbers into complex
integers.
14th. delattr()
Removes an attribute from an object.
delattr () is an in-built method in Python that is used to delete any attribute
present in a class.
15th. dict()
Creates a Dictionary
What does dict () do in Python?
The dict () method in Python is a constructor that is used to create
dictionaries.
Depending upon the parameters that are passed in the function, a
dictionary of any length can be created using the constructor.
What is __dict__ in Python?
The __dict__ in Python is a dictionary or other such mapping objects that
are used to store the attributes of an object.
Every object that contains an attribute in Python can be denoted by
__dict__. This object dict will contain all the attributes that are used or
defined for any object
16th. dir()
Tries to Return Attributes of Object
The function dir python is responsible for returning the valid list of the
attributes for the objects in the current local scope.
17th. divmod()
Returns a Quotient and Remainder Tuple.
18th. enumerate()
Returns an Enumerate Object
19th. eval()
Runs Python Code Within Program
20th. exec()
Executes a Program That Was Created Dynamically
21st. filter()
Python filter is a built-in function that is used to filter the unwanted element from
the given list.
22nd. float()
returns floating-point number from number, string
23rd. format()
returns a formatted representation of a value
24th. frozenset()
Python has an inbuilt function called frozenset() that takes an iterable object as
input and makes it immutable.
Simply put, the Python Frozenset renders iterable objects unchangeable by
freezing them.
25th. getattr()
returns the value of an object’s named attribute
26th. globals()
returns dictionary of the current global symbol table
27th. hasattr()
returns whether the object has a named attribute
28th. hash()
returns hash value of an object
29th. help()
Invokes the built-in Help System
30th. hex()
Converts to Integer to Hexadecimal
The python hex function is used to convert an integer to is an equivalent
hexadecimal string.
31st. id()
Returns Identify of an Object
32nd. input()
reads and returns a line of string
33rd. int()
from a number or string, returns an integer
34th. isinstance()
Checks if an Object is an Instance of Class
The isinstance Python is an in-built function that is based on the concept of
objects.
Python is an object-oriented language in which classes can be created.
35th. issubclass()
Checks if a Class is Subclass of another Class
36th. iter()
returns an iterator
37th. len()
Returns Length of an Object
38th. list()
creates a list in Python
39th. locals()
The dictionary of a current local symbol table is returned.
40th. map()
Applies Function and Returns a List
41st. max()
returns the largest item
42nd. memoryview()
returns an argument’s memory view
43rd. min()
returns the smallest value
44th. next()
Retrieves next item from the iterator
we can use the next() function to return the next item in the sequence.
45th. object()
creates a featureless object
46th. oct()
returns an integer’s octal representation
The Python oct() function in Python is a built-in function. This function takes an
integer as its argument and returns its equivalent string format.
47th. open()
Returns a file object
48th. ord()
returns an integer of the Unicode character
49th. pow()
returns the power of a number
50th. print()
Prints the Given Object
51st. property()
returns the property attribute
52nd. range()
between start and stop, return a sequence of numbers
53rd. repr()
returns the object’s printed representation
54th. reversed()
returns the sequence’s reversed iterator
55th. round()
rounds a number to specified decimals
56th. set()
constructs and returns a set
57th. setattr()
sets the value of an attribute of an object
58th. slice()
returns a slice object
59th. sorted()
from the specified iterable, returns a sorted list
60th. staticmethod()
transforms a method into a static method
61st. str()
returns the string version of the object
62nd. sum()
Adds items of an Iterable
63rd. super()
Returns a proxy object of the base class
64th. tuple()
Returns a tuple
65th. type()
Returns the type of the object
66th. vars()
Returns the __dict__ attribute
67th. zip()
Returns an iterator of tuples
68th. __import__()
A function called by the import statement
8. How do you define and call functions in Python?
Use the def keyword to define a function and specify its name,
parameters, and code block.
Call the function by its name with optional arguments.
9. What are the different types of function arguments?
Required arguments: These arguments are mandatory and must be
provided when calling the function.
Optional arguments: These arguments have default values and are not
required to be provided when calling the function.
Keyword arguments: These arguments are passed by name with
keyword-value pairs, allowing you to specify the argument name
explicitly.
Variable-length arguments: These arguments allow you to pass a
variable number of arguments to the function using *args or **kwargs.
10. How do you return values from functions?
Use the return statement to return values from a function to the caller.
Scope:
11.What is the scope of a variable in Python?
The scope of a variable defines where it is accessible and usable within your
program. Different scopes have different levels of accessibility.
12.What are the different types of scope in Python?
Local Scope: Variables defined inside a function are only accessible within
that function. They are destroyed when the function exits.
Global Scope: Variables defined outside any function are accessible from
any part of your program, including inside functions.
Enclosing Scope: Nested functions can access variables defined in their
enclosing functions, but not in other enclosing functions.
13.How do you define the scope of a variable?
Use the global keyword inside a function to access a global variable defined
outside the function.
Use nonlocal keyword in nested functions to access variables defined in the
enclosing function, not the global scope.
14.Why is understanding scope important?
Avoiding accidental variable conflicts and unexpected behavior.
Writing clean and well-organized code by clearly defining variable
accessibility.
Debugging issues related to variable access from different parts of your
program.
Local Variables:
15.What are local variables?
Local variables are defined inside a function and are only accessible within
that function. They are created when the function is called and destroyed
when the function exits.
Reduced clarity: Overuse can make code less readable and harder to debug,
obscuring data dependencies.
Potential side effects: Modifying enclosing function data can have
unexpected consequences if not managed carefully.
Non-Local Variables:
17.What are non-local variables?
Non-local variables are defined inside a nested function and access
variables defined in the enclosing function, not the global scope.
18.How do you define a non-local variable?
You define a non-local variable inside a nested function by using the
nonlocal keyword before assigning a value to it.
19.Advantages of using non-local variables:
Share data efficiently: Avoid passing large data structures between
functions.
Modify enclosing function data: Allow nested functions to update their
parent's variables.
Global Variables:
20.What are global variables?
Global variables are defined outside any function and are accessible from
any part of your program, including inside functions.
21.How do you define a global variable?
You define a global variable by declaring it outside any function block, and
you can access it using its name anywhere in your code.
22.Disadvantages of using global variables:
Increase coupling: Tightly linking functions to global data makes them less
modular and reusable.
Difficult to debug: Global variable changes can have unexpected
consequences, making debugging complex.
Built-in Variables:
23.What are built-in variables?
Built-in variables are special variables pre-defined within the Python interpreter
and available to all your code. These variables contain information about the
context and environment your program runs in.
Scope: Non-local variables have higher priority than global variables but
lower than local variables within the same enclosing function.
Lifetime: They live as long as their enclosing function, not the nested
function.
Modification: Modifying them in the nested function persists their changed
value even after the nested function exits.
Use cautiously: Overuse can reduce code clarity and introduce potential
side effects.
global variables
28.What are global variables in Python?
Variables defined outside any function are globally accessible throughout your
program.
You can access them directly from any function or code block.
Key Rules:
Built in rules
Key Rules:
lambda
29.What is a lambda function?
A lambda function is an anonymous function. This means it doesn't have a
defined name and is typically used for small, one-line tasks.
30.How do you define a lambda function?
A lambda function is defined using the keyword lambda followed by
arguments, a colon, and the expression to be evaluated. For example:
31.When should you use a lambda function?
Use lambdas for short, inline functions that are only needed once or within
a single line. They can be useful for:
Filtering lists: data = [item for item in data if item % 2 == 0]
Sorting lists: data.sort(key=lambda x: x.age)
Passing functions as arguments: func(lambda x: x * 2)
32.What are the limitations of lambda functions?
Lambdas cannot be recursive (call themselves).
They are less readable than named functions, especially for complex logic.
They limit code reuse through naming.
33.What are the differences between a lambda function and a regular function?
Lambdas are anonymous and one-line, while regular functions have names
and can be multi-line.
Lambdas are less versatile and reusable compared to regular functions.
34. How do you use anonymous functions in Python?
Use lambda expressions to define anonymous functions that are often used
for short inline functions.
map
35.What is the map() function in Python?
map() is a built-in function that applies a given function to every element in an
iterable (like a list) and returns an iterator containing the results.
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x * x, numbers) # Applies the square function to
each element
print(list(squares)) # Output: [1, 4, 9, 16, 25]
Use code with caution. Learn more
37.When should you use map()?
Use map() when you need to apply the same operation to every element in
a sequence in a concise and efficient way.
It can be helpful for things like:
Calculating squares or other mathematical operations on each element.
Converting data types (e.g., strings to integers).
Filtering items based on a condition.
38.What are the limitations of map()?
It only applies the function once to each element.
It returns an iterator, which might require additional steps to work with
(e.g., converting to a list).
It might not be the most efficient solution for very large datasets.
39.Alternatives to map()?
List comprehensions can achieve similar functionality in some cases and can
be more readable for some tasks.
Loops can also be used, but map() offers conciseness and efficiency
benefits.
Filter
40.What is the filter() function in Python?
filter() is a built-in function that iterates through an iterable (like a list) and
returns a new iterable containing only elements that satisfy a given
condition.
41.How do you use filter()?
It takes two arguments:
Function: The function to test each element against (typically a predicate).
Iterable: The list or sequence to filter through.
The returned iterator needs to be converted to a concrete data type like a
list using list().
Example of using filter():
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers) # Keeps only even
numbers
print(list(even_numbers)) # Output: [2, 4]
42.When should you use filter()?
Use filter() when you need to remove unwanted elements from a sequence
based on a specific condition.
It can be helpful for things like:
Filtering even numbers from a list.
Selecting products with a specific price range.
Removing empty strings from a dataset.
43.What are the limitations of filter()?
It only checks each element against the given condition, it doesn't perform
any complex operations.
It returns an iterator, which might require additional steps to work with
(e.g., converting to a list).
For complex filtering logic, list comprehensions or dedicated libraries might
be more efficient.
44.Alternatives to filter()?
List comprehensions can achieve similar filtering in some cases, often with
more concise syntax.
Loops with conditional statements can also be used, but filter() offers
conciseness and efficiency benefits.
Reduces
45.What is the purpose of reduce in functional programming?
reduce takes a binary function and an iterable, applying the function
cumulatively to pairs of elements. It iterates through the iterable, starting
with the first two elements, combines them using the function, then uses
that result and the next element, and so on until only one element remains,
representing the final accumulated value.
46.Why doesn't Python have a built-in reduce?
Python prioritizes code readability and safety. reduce can be prone to
errors, especially in nested expressions, and its behavior with empty
iterables isn't always intuitive.
47.How can you achieve reduction functionality in Python?
Several methods offer similar functionality to reduce:
functools.reduce: This module provides a safe and optimized reduce
implementation, recommended for advanced use cases.
Loops: You can write a loop that iterates through the iterable, applying the
function cumulatively. Although less concise than other methods, it offers
clear control over the reduction process.
List comprehensions: In specific cases, you can use list comprehensions
with nested expressions to achieve reduction-like functionality.
Example using functools.reduce:
Package
53.What is a package in Python?
A package is a collection of related modules organized into a directory
structure. It can contain several modules, sub-packages, and other files like
documentation or data. Packages help group related functionalities and
provide a single import point for the entire set.
54.Why use packages?
There are several advantages to using packages:
Improved organization: Dividing large projects into packages increases code
modularity and maintainability.
Code reuse: Modules within a package can be easily shared and reused
throughout the project.
Reduced redundancy: Packages prevent repeating the same code across
different parts of the project.
Centralized dependencies: Managing package dependencies becomes
easier by grouping them within a single package.
1. What is a python ?
Python is a high level language. It was created by guido van rossum and released
in 1991
2. What are the uses of python language?
It is used to :-
4 Why python?
Python's syntax is clear and readable, making it easy for both beginners and
experienced developers to write and maintain code
Versatility:
Python is a versatile language that can be used for various applications, including web
development, data science, artificial intelligence, machine learning, automation, and
more.
Python comes with a comprehensive standard library that provides modules and
packages for a wide range of functionalities, reducing the need for additional third-
party libraries.
Python has a large and active community of developers. This community support is
beneficial for solving problems, sharing knowledge, and contributing to the language's
growth.
Ease of Learning:
Python is known for its simplicity and readability, making it accessible to beginners. The
syntax resembles pseudo-code, making it easier to understand and learn.
Open Source:
Python is open-source, allowing users to access and modify the source code according
to their needs. This fosters collaboration and continuous improvement.
Portability:
Interpreted Language:
Python is an interpreted language, which means that code can be executed directly without the need for
compilation. This leads to faster development cycles and easier debugging.
Python can easily integrate with other languages and technologies, making it a great
choice for building complex systems that require components in multiple languages.
Dynamic Typing:
Python uses dynamic typing, which allows developers to write code more quickly and
adapt to changes more easily.
High-Level Language:
Install Python:
You can download Python from the official website and follow the installation
instructions.
Use Python syntax to write your programs. Python is known for its readability and
simplicity. You can start with basic scripts and gradually move on to more complex
projects.
You can execute Python scripts or programs from the command line or within
your chosen IDE or text editor.
8 Why Python:
Readability and Simplicity:
Versatility:
Python comes with a vast standard library that includes modules and packages
for a wide range of tasks. This minimizes the need for external libraries for many
common programming tasks.
Python has a large and active community of developers. This means there are
abundant resources, tutorials, and libraries available. If you encounter a problem,
chances are someone has already faced it and there is a solution.
Cross-Platform Compatibility:
Python is cross-platform, meaning you can write code on one operating system
and run it on another without modification. This makes it easy to develop and deploy
applications on different platforms.
Open Source:
Python is open source, meaning its source code is freely available. This
encourages collaboration and innovation, and it allows developers to modify and
distribute the language.
Python is widely used in data science and machine learning. It has a rich
ecosystem of libraries such as NumPy, pandas, scikit-learn, TensorFlow, and PyTorch
that make it a preferred choice for these fields.
Use the # symbol for single-line comments and triple-quotes ''' or """ for multi-line
comments.
11 .What is PEP 8?