0% found this document useful (0 votes)
111 views88 pages

Oops Notes

The document discusses object-oriented programming concepts like classes, objects, inheritance, encapsulation, polymorphism and abstraction. It explains what they are, their characteristics and provides examples to illustrate various OOP concepts.

Uploaded by

sivareddy.looker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views88 pages

Oops Notes

The document discusses object-oriented programming concepts like classes, objects, inheritance, encapsulation, polymorphism and abstraction. It explains what they are, their characteristics and provides examples to illustrate various OOP concepts.

Uploaded by

sivareddy.looker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 88

Oops (object oriented programming)

1. What is oops ?

 Ans : Oops is a type of programming that is based on objects rather than


just function and procedures.

 Individual objects are grouped into class.

OOPs are like

1. Encapsulation

2. Abstraction

3. Inheritance

4. Polymorphism

2. What is class?

 Ans: A class is a blueprint for creating objects.

 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.,

 Integers strings, floating-point numbers, even arrays and dictionaries, are


all objects
An object is an instance of a class. It represents a specific entity with its own
unique attributes and behaviors.

class Dog:

attr1 = "mammal"

attr2 = "dog"

def fun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)

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?

 Ans: It is represented by the attributes of an object.

 It also reflects the properties of an object


7. What is a behavior?

 Ans: It is represented by the methods of an objects.

 It is also reflects the response of an object to other object.

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):

print('I am Parent class')

class Child(Parent):

def M1(self):

print('I am CHild class')

# super().M1()

ob1 = Child()

ob1.M1()

DIFFERENT TYPES OF INHERITANCE

 Single Inheritance: Single-level inheritance enables a derived class to


inherit characteristics from a single-parent class

 When a child class inherits only a single parent class


class Parent:

def Method1(self):

print('I am a parent class')

class Child(Parent):

def method2(self):

print('I am Child class')

ob1 = Child()

ob1.method2()

ob1.Method1()

 Multiple inheritance : Multiple-level inheritance enables one derived class


to inherit properties from more than one base class

 When a child class inherits from more than one parent class

# I am child class

class Parent1:

def Property2(self):

print('I am Parent1 class')

class Parent2:

def Property2(self):

print('I am Parent2 class')

class Parent3:

def Property3(self):

print('I am Parent3 class')

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):

print('I am Parent1 class')

class Parent2:

def Property2(self):

print('I am Parent2 class')

class Parent3:

def Property3(self):

print('I am Parent3 class')

class Child(Parent1,Parent2,Parent3):

def Property4(self):

print('I am child class')

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

 Multi-level inheritance :- Multi-level inheritance enables a derived class to


inherit properties from an immediate parent class which in turn inherits
properties from a parent class

 When a child class becomes a parent class for another child class

# Grandfather---> Father ---> child

class GrandFather:

def M1(self):

print('I am GrandParent')

class Parent(GrandFather):

def M2(self):

print('I am Parent class')

class Child(Parent):

def M3(self):

print('I am Child class')


ob1 = Child()

ob1.M1()

ob1.M2()

ob1.M3()

# I am GrandParent

# I am Parent class

# I am Child class

 Hierarchical inheritance:- Hierarchical inheritance refers to inheritance


where one base class has more than subclasses. For example, the vehicle
class can have car, bike, etc as its subclasses

 Hierarchical inheritance involves multiple inheritance from the


same base or parent class

 Hybrid inheritance: Hybrid inheritance is a combination of multiple and


multi-level inheritance

9. What is a super class?

 Ans :A super class or base class is a class that acts as a parent to some other
class or classes

 For example, the vehicle class is a super class of class car.

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):

print('Oppo battery capacity 400mah')

def RAM(self):

print('Oppo RAM is 4GB')

def Display(self):

print('Oppo Dispaly width 5.6 inches')

def Camera(self):

print('Oppo FC : 40Mpx,BC : 100Mpx')

#Concrete (Normal)Methods

def Normal(self):

print('THis is a Electronic Device')

class Production(Oppo):

#Concreate method # Oppo class method overriding


def Battery(self):

super().Battery()

def RAM(self):

super().RAM()

ob1 = Production()

ob1.Battery()

ob1.RAM()

# Oppo battery capacity 400mah

# Oppo RAM is 4GB

10. What is a sub class?

 Ans :A class that inherits from another class is called the subclass

 For example, the class car is a subclass or a derived of vehicle class.

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.

12. What is the __init__ method used for?

 Ans : The __init__ method is a special method in python classes that is


called when an object is created.

 It is used to initialize the object’s attributes.

13.What is the self keyword in python?

 Ans: Self is a reference to the current instance of the class.


 It is used to access variables and method within the class.

 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):

# A constructor is optional, and if we do not provide any constructor, then


Python provides the default constructor.

# Every class in Python has a constructor, but it's not required to define it.

# def __init__(self):

# # body of the constructor

def __init__(self,Ename,Eage,Esalary,Edomain,Elocation):

#self.New_variable_name = parameter

# object.NewVariable_name = Parameter

self.name = Ename # vikas

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?

 Ans: Method overloading is not directly supported in python.

 Unlike some other languages like java, python does not allow defining
multiple methods with the same name but different signatures.

 However, you can achieve similar behavior using default arguments or


variable-length arguments.

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)

# TypeError: Method1() missing 2 required positional arguments: 'c' and 'd'

15.What is method overriding?

 Ans : Method overriding occurs when a subclass provides a specific


implementation of a method that is already defined in its superclass.

 The subclass method overrides the superclass method with the same name.

16.What is a static method?


 Ans : A static method is a method that is bound to a class rather than an
instance of the class.

 It does not have access to self / cls and can be called without creating an
instance of the class

class MyClass:

def __init__(self, value):

self.value = value

@staticmethod

def get_max_value(x, y):

return max(x, y)

# Create an instance of MyClass

obj = MyClass(10)

print(MyClass.get_max_value(20, 30))

print(obj.get_max_value(20, 30))

17.What is a class method in Python?

 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:

def __init__(self, value):

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.

19.Explain the concept of abstract classes and abstract methods.

 Ans : An abstract class is a class that consists of abstract methods.

 These methods are basically declared but not defined.

 If these methods are to be used in some subclass, they need to be


exclusively defined in the subclass.

Abstract Class:

 An abstract class is a class that contains one or more abstract methods.

 It serves as a template for other classes, providing a common interface that


subclasses must adhere to.

 Abstract classes cannot be instantiated directly. They are designed to be


subclassed, with the subclass providing implementations for the abstract
methods.

 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):

print('Oppo battery capacity 400mah')

def RAM(self):

print('Oppo RAM is 4GB')

def Display(self):

print('Oppo Dispaly width 5.6 inches')

def Camera(self):

print('Oppo FC : 40Mpx,BC : 100Mpx')

#Concrete (Normal)Methods

def Normal(self):

print('THis is a Electronic Device')

Abstract Method:
 An abstract method is a method declared in an abstract class but does not
contain an implementation.

 Subclasses of the abstract class must provide implementations for all


abstract methods, or they themselves will be considered abstract.

 Abstract methods are declared using the @abstractmethod decorator from


the abc module.

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:

 Also known as a parent class or superclass.

 A base class is a class that provides the initial structure, attributes, and
behaviors that other classes can inherit from.

 Base classes are typically designed to be general and reusable, providing


common functionality to multiple subclasses.

 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:

 Also known as a child class or subclass.


 A derived class is a class that inherits attributes and behaviors from a base
class.

 Derived classes extend or specialize the functionality of the base class by


adding new methods, properties, or attributes, or by overriding existing
ones.

 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__?

 __iter__() returns the iterator object itself. If required, some initialization


can be performed.

1) IndexError

The IndexError is thrown when trying to access an item at an invalid index.

2) Module Not Found Error


The Module Not Found Error is thrown when a module could not be found.

3) Stop Iteration

The Stop Iteration is thrown when the next() function goes beyond the iterator
items.

The StopIteration error is raised by built-in function next() and an iterator‘s


__next__() method to signal that all items are produced by the iterator

4) Type Error

The Type Error is thrown when an operation or function is applied to an object of


an inappropriate type.

print("5" + 3)

5) Value Error

The Value Error is thrown when a function's argument is of an inappropriate type

int("hello")

6) Name Error

The Name Error is thrown when an object could not be found.

print(non_existent_variable)

7) Zero Division Error

The Zero Division Error is thrown when the second operator in the division is zero.

print(5 / 0)

8) Indentation errors:

Problems with indentation, as Python uses it to determine code structure.

if True:
print("Indentation error")

9) Key board Interrupt

The Key board Interrupt is thrown when the user hits the interrupt key (normally
Control-C) during the execution of the program.

try:

print ('Press Return or Ctrl-C:',)

ignored = input()

except Exception, err:

print ('Caught exception:', err)

except KeyboardInterrupt, err:

print ('Caught KeyboardInterrupt')

else:

print ('No exception')

Memory Error:

This error is raised when an operation runs out of memory.

def fact(a):

factors = []

for i in range(1, a+1):

if a%i == 0:

factors.append(i)

return factors

num = 600851475143

print (fact(num))
Data types in Python

22.Differentiate between mutable and immutable objects?


Answer:

Mutable Objects Immutable Objects


Can change their state or Cannot change their state or
contents contents
Type: list, diet, set Inbuilt types: int, float, bool,
string, Unicode, tuple
Easy to change Quick to access but making
changes require the creation
of a copy
Customized container like Primitive like data types are
types are mostly mutable immutable
 Mutable objects are recommended when one has the requirement to
change the size or content of the object

 The exception to immutability: tup1es are immutable but may contain


elements that are mutable

23.What is Variable 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

 ' Hello World ! ! ! '

 >>> b
 ' Hello World ! ! ! '

 >>> c

' Hello World ! ! ! '

>>>

Numbers


Types of numbers supported are as follows:

 Signed integers int: these can be +ve or -ve and do not have any decimal
point

 Long integers long: these are integers of unlimited size followed by


capital or lowercase ‘L’

 Float: are real numbers with decimal points

 Complex numbers: have real and imaginary parts

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.

25.What are the functions available to work with random numbers?

 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)

<class 'float' >

>>> int(a)

12

>>>

28.How can we delete a reference to a variable?


 Answer:
You can delete a reference to an object using the del keyword.
 >> a=5
 >>> a 5
 >>> del a
 >>> a
 Traceback (most recent call last):
 File "<pyshell#3>", line 1, in <module>
 a
 NameError: name 'a' is not defined

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, Identifiers, and Variables

Keywords

 Keywords are also known as reserved words.


 These words cannot be used as a name for any variable, class, or function.
 Keywords are all in lower case letters.
 Keywords form vocabulary in Python.
 The total number of keywords in Python is 33.
 help> keywords
Here is a lis

t of
the python keywords, Enter any keyword to get more help.

Identifiers

 Python Identifier is a name given to a variable, function, or class.


 As the name suggests identifiers provide an identity to a variable, function,
or class.
 An identifier name can start with upper or lower case letters or an
underscore followed by letters and digits.
 An identifier name cannot start with a digit.
 An identifier name can only contain letters, digits, and an underscore.
 special characters such as @,%,! , #,$,’.’ cannot be a part of the identifier
name.

29.What are tokens?


 Answer:
Tokens are the smallest units of the program in Python. There are
four types of tokens in Python:
 Keywords
 Identifiers
 Literals
 Operators
30.What are constants?
 Answer:
Constants (literals) are values that do not change while executing a
program.
31.What is a Strings?
 String is a sequence of character in a single quotation and double quotation
32.How can String literals be defined?
 Answer:
Strings can be created with single/double/triple quotes.

>>> a = "Hello World"

>>> b = 'Hi'

>>> type(a)

<class 'str'>

>>> type(b)

<class 'str' >

>>>

>>> c = """Once upon a time in a land far far away there lived a king"""

>>> type(c)

<class 'str'>

33.How can we perform concatenation of Strings?

 Answer:
Concatenation of Strings can be performed using the following techniques:

1. + operator

>>> string1 = "Welcome"

>>> string2 = " to the world of Python!!!"

>>> string3 = string1 + string2


>>> string3

'Welcome to the world of Python!!!'

>>>

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)

>>> string1 = "-"

>>> sequence = ( "1","2","3","4")

>>> print(string1.joint(sequence))

1-2-3-4

3. % operator
>>> string1 = "HI"

>>> string2 = "THERE"

>>> string3 = "%s %s" %(string1, string2)

>>> string3 ,

'HI THERE'

4. format( ) function
>>> string1 = "HI"

>>> string2 ="THERE"

>>> string3 = "{ } { }" . format (string1, string2)

>>> string3

'HI THERE'
5. f-string

>>> string1 ="HI"

>>> string2 = "THREE"

>>> string3 = f ' { string1} {string2} '

>>> string3

'HI THERE'

34.How can you repeat strings in Python?


 Answer:
Strings can be repeated either using the multiplication sign or by using for
loop.
 operator for repeating strings

>>> string1 = "Happy Birthday!!!"

>>> string1*3

'Happy Birthday!!!Happy Birthday!!!Happy Birthday!!!' *

>>>

for loop for string repetition

for x in range (0,3)

>>> for x in range(0,3):

print("HAPPY BIRTHDAY! ! !")

Question 21.
What would be the output for the following lines of code?

>>> string1 = "HAPPY "

>>> string2 = "BIRTHDAY!!!"


>>> (string1 + string2)\n *3

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:

>>> string1 = "HAPPY"

>>> a,b,c,d,e = string1

>>> a

'H'

>>> b

'A'

>>> c

'P'

>>> d

'P'

>>> e

'Y'

>>>
What would be the output for the following code?

>>> string1 = "HAPPY-BIRTHDAY!!!"

>>> string1[-1:-9:-2]

Answer:

‘!!AH’

35.How does the split( ) function work with strings?

 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 = "Happy Birthday"

>>> string1.split ( )

['Happy', 'Birthday' ]

 Example

>>> time_string = "17:06:56"

>>> hr_str,min_str,sec_str = time_string. split (":")

>>> hr_str

'17'

>>> min_str

'06'

>>> sec_str

'56'
 You can also specify, how many times you want to split the string.

>>> date_string = "MM-DD-YYYY"

>>> 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 = "MM-DD-YYYY"

>>> 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 = "MM-DD-YYYY"

>>> date_string.partition("-" , 1)

('MM', ' - ' , 'DD-YYYY')

 The partition ( ) function on the other hand looks for the delimiter from the
other end.

>>> date_string = "MM-DD-YYYY"

>>> date_string.rpartition("-")

('MM-DD', '-', 'YYYY')

37.Name the important escape sequence in Python.


 Answer:
Some of the important escape sequences in Python are as follows:
\\: Backslash

\’: Single quote

\”: Double quote •

\f: ASCII form feed

\n: ASCII linefeed

\t: ASCII tab

\v: Vertical tab

String Methods

1) capitalize ( )
 Will return a string that has first alphabet capital and the rest are in lower
case, ‘

>>> string1 = "HAPPY BIRTHDAY"

>>> string1.capitalize ( )

'Happy birthday'

2) casefold( )
 Removes case distinction in string. Often used for caseless matching. ‘

>>> string1 = "HAPPY BIRTHDAY"

>>> 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)

>>> string1 = "HAPPY BIRTHDAY"


>>> new_string = string1.center(24)

>>> print("Centered String: ", new_string)

Centered String: HAPPY BIRTHDAY

4) count( )

Counts the number of times a substring repeats itself in the string.

>>> string1 = "HAPPY BIRTHDAY"

>>> 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 = "HAPPY BIRTHDAY"

>>> string1.encode( )

b'HAPPY BIRTHDAY'

By default, python uses utf-8 encoding.


It can take two parameters:
encoding – type a string has to be encoded to and
error- response when encoding fails

>>> string1 = "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.

>>> string1 = "to be or not to be"

>>> string1.endswith("not to be")

True

7) find( )

Get the index of the first occurrence of a substring in the given string.

>>> string1 = "to be or not to be"

>>> string1 .find ('be' )

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

>>> print("Happy Birthday { }".format("Alex"))

Happy Birthday Alex

Example

>>> print("Happy Birthday { }, have a { } day!!", format("Alex","Great"))

Happy Birthday Alex, have a Great day ! !


Values that exist in the format( ) are tup1e data types. A value can be called by
referring to its index value.

Example

>>> print("Happy Birthday {0}, have a {l} day!!", format("Alex","Great"))

Happy Birthday Alex, have a Great day!!

9) index( )

It provides the position of the first occurrence of the substring in the given string.

>>> string1 = "to be or not to be"

>>> string1.index('not')

10) isalnum( )

It returns true if a string is alphanumeric else it returns false.

>>> string1 = "12321$%%^&*"

>>> string1.isalnum( )

False

>>> string1 = "string1"

>>> string1.isalnum()

True

11) isalpha( )

It returns true if the whole string has characters or returns false.

>>> string1.isalpha( )
False

>>> string1 = "tobeornottobe"

>>> string1.isalpha( )

True

12) isdeimal( )

Returns true if the string has all decimal characters.

>>> string1 = "874873"

>>> string1.isdecimal()

True

13) isdigit( )

Returns true if all the characters of a string are digits:

>>> string1 = "874a873"

>>> string1.isdigit()

False

14) islower( )

>>> string1 = "tIger"

>>> string1.islower()

False

15) isnumeric( )

Returns true if the string is not empty characters of a string are numeric.

>>> string1 = "45.6"

>>> string1.isnumeric()
False

16) isspace( )

Returns true if the string only has space.

>>> string1 =" "

>>> string1.isspace()

True

17) lower( )

Converts upper case letters to lower case.

>>> string1 ="TIGER"

>>> string1.lower()

'tiger'

18) swapcase( )

Changes lower case letters in a string to upper case and vice-versa.

>>> string1 = "tiger"

>>> string1 = "tiger".swapcase()

>>> string1

'TiGER'

19) Upper().

The upper() method returns a string where all characters are in upper case.

Symbols and Numbers are ignored.

txt = "Hello my friends"

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.

#use a dictionary with ascii codes to replace 83 (S) with 80 (P):

mydict = {83: 80}


txt = "Hello Sam!"

print(txt.translate(mydict))

Use the maketrans() method to create a mapping table.

txt = "Hello Sam!"

mytable = str.maketrans("S", "P")

print(txt.translate(mytable))

txt = "Hi Sam!"

x = "mSa"

y = "eJo"

mytable = str.maketrans(x, y)

print(txt.translate(mytable))

If a character is not specified in the dictionary/table, the character will not be


replaced.

txt = "Good night Sam!"

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.

txt = "Good night Sam!"

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.

txt = "Welcome to my world"

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.

txt = "Welcome to my 2nd world"

x = txt.title()

print(x)

24) Strip

The strip() method removes any leading, and trailing whitespaces.

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.

txt = " banana "

x = txt.strip()

print("of all fruits", x, "is my favorite")


25) Startswith()

The startswith() method returns True if the string starts with the specified value,
otherwise False

txt = "Hello, welcome to my world."

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.

txt = "Thank you for the music\nWelcome to the jungle"

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)

space is the default trailing character to remove.

txt = " banana "

x = txt.rstrip()

print("of all fruits", x, "is my favorite")


38.What is a Lists?

• Lists are ordered and changeable collections of elements.

• Can be created by placing all elements inside a square bracket.

• All elements inside the list must be separated by a comma

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[]

>>> # Create empty list

>>> list1 = [ ]

>>> # create a list with few elements

>>> list 2 = [12, "apple" , 90.6,]

>>> list1

[]

>>>list2
[12 , 'apple' , 90.6]

a) Append
 The append() method appends an element to the end of the list.

a = ["apple", "banana", "cherry"]

b = ["Ford", "BMW", "Volvo"]

a.append(b)

print(a)

b) Clear()

 The clear() method removes all the elements from a list.

fruits = ["apple", "banana", "cherry"]

fruits.clear()

print(fruits)

c) Copy()
 The copy() method returns a copy of the specified list.

fruits = ["apple", "banana", "cherry"]

x = fruits.copy()

print(x)

d) Count()
 The count() method returns the number of elements with the specified
value.

fruits = ["apple", "banana", "cherry"]

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 = ['apple', 'banana', 'cherry']

cars = ['Ford', 'BMW', 'Volvo']

fruits.extend(cars)

print(fruits)

f) Index()
 The index() method returns the position at the first occurrence of the
specified value

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")

print(x)

g) Insert()
 The insert() method inserts the specified value at the specified position.

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")

print(fruits)

h) Pop()
 The pop() method removes the element at the specified position

fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)
print(fruits)

i) Remove()
 The remove() method removes the first occurrence of the element with the
specified value.

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

print(fruits)

j) Reverse()
 The reverse() method reverses the sorting order of the elements.

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

print(fruits)

k) Sort()

 The sort(() method sorts the list ascending by default.

You can also make a function to decide the sorting criteria(s).

cars = ['Ford', 'BMW', 'Volvo']

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 [5] = ‘p’


list1 [-5] = ‘Y’

list1 [3:6] = [‘V’, ‘E’, ‘p’]

list1 [:-3] =[‘I’, ‘L’ ,’O’,’V’,’E’,’p’,’Y’,’T’]

list1[-3:] = [‘H’,’O’,’N’]

list1 [:]= [“l”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]

list1 [1:8:2] = [‘L’,’V’,’p’,’T’]

list1 [::2] = [‘I’,’O’,’E’,’Y’,’H’,’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 = list1+list2

>>> 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.extend([-3,- 5, - 7 , -5] )

>>> list1

[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, -3, -5, -7, -5]

44. list1 = [“h”,”e”,”l”,”p”]


What would be the value of list1 *2?
 Answer:

[‘h’, ‘e’, T, ‘p’, ‘h’, ‘e’, ‘l’ , ‘p’]

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]

>>> del(list1 [1])

>>> list1

[1, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]

>>>

48.How would you find the length of o list?


 Answer:
The len( ) function is used to find the length of a string.

>>> 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 . remove (78)

>>> list1

[1,2,45, 93, 56, 34, 23, 12, 98, 70, 65]


Tuple
50.What is a tuple?
 Tuple are used to store multiple items in a single variable
 Tuple is a collection of which is ordered and unchangeable.
 It is allow duplicate values .
 It is used to immutable. They can’t be changed after creation
 It is denoted by rounded ()
51.tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56] What would be the value of
tup1 [1 ][0]Answer:
8
52.tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What is the value of tup1 [-7] and tup1 [-15]?
Answer:

>>> tup1[-7]

56

>>> tup1[-15]

File "<pyshell#2>", line 1, in <module> tup1 [-15]

IndexError: tup1e index out of range

53.tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]


tup2 = (1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
Find the value of:
 Answer

tup1[2:9] = ((4, 6, 5, 7), 9, 23, [98, 56])

tup2[:-l] = (1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70)

tup2[-l:] = (65,)

tup1[3:9:2] = (9, [98, 56])


tup2[3:9:2] = (45,56,23,)

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{}.

55. How can we create a dictionary object?


 Answer:
A dictionary object can be created in any of the following ways:

>>> dictl = { }

>>> type(dict1)

<class 'dict'>

>>> dict2 = {'key1' :'value1', 'key2': 'value2', 'key3': 'value3', ' key4': ' value4'}

>>> dict2

{'key1': 'value1', 'key2': 'value2', 'key3' : 'value3', 'key4': 'value4' }

>>> type(dict2)

<class 'diet'>

>>> dict3 = diet({'key1': 'value1', 'key2':' value2', 'key3': 'value3', ' key4 ':' value4' })

A. Clear()

The clear() method removes all the elements from a dictionary.

car = {
"brand": "Ford",

"model": "Mustang",

"year": 1964

car.clear()

print(car)

B. Copy ()

The copy() method returns a copy of the specified dictionary.

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.

x = ('key1', 'key2', 'key3')

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 update() method inserts the specified items to the dictionary.

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}

>>> set1

{8, 9, 10}

>>>

i. Add()
 The add() method adds an element to the set.

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

 If the element already exists, the add() method does not add the element.

thisset = {"apple", "banana", "cherry"}

thisset.add("apple")

print(thisset)

 Since sets are unordered, indexing does not work for it

>>> set1 ={12,34,43,2}

>>> set1 . add(32)

>>> set1

(32, 2, 34, 43, 12}

ii. Clear ()
The clear() method removes all elements in a set.

fruits = {"apple", "banana", "cherry"}

fruits.clear()

print(fruits)

iii. Copy(): The copy() method copies the set.

fruits = {"apple", "banana", "cherry"}

x = fruits.copy()

print(x)

iv. Difference()

The difference() method returns a set that contains the difference between two
sets.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

z = x.difference(y)

print(z)

Meaning: The returned set contains items that exist only in the first set, and not
in both sets.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

z = y.difference(x)

print(z)

v. Difference_update()

The difference_update() method removes the items that exist in both sets.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.difference_update(y)

print(x)

The difference_update() method is different from the difference() method,


because the difference() method returns a new set, without the unwanted items,
and the difference_update() method removes the unwanted items from the
original set.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

y.difference_update(x)

print(y)

vi. Discard()

The discard() method removes the specified item from the set.

thisset = {"apple", "banana", "cherry"}

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 = {"apple", "banana", "cherry"}

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"}

y = {"google", "microsoft", "apple"}

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.

x = {"a", "b", "c"}

y = {"c", "d", "e"}

z = {"f", "g", "c"}

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 = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

The intersection_update() method is different from the intersection() method,


because the intersection() method returns a new set, without the unwanted
items, and the intersection_update() method removes the unwanted items from
the original set.

x = {"a", "b", "c"}

y = {"c", "d", "e"}

z = {"f", "g", "c"}


result = x.intersection(y, z)

print(result

ix. Isdisjoint ()

The isdisjoint() method returns True if none of the items are present in both sets,
otherwise it returns False.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "facebook"}

z = x.isdisjoint(y)

print(z) #True

x = {"apple", "banana", "cherry"}

y = {"apple", "microsoft", "facebook"}

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.

x = {"a", "b", "c"}

y = {"f", "e", "d", "c", "b", "a"}

z = x.issubset(y)

print(z) # True

x = {"a", "b", "c"}

y = {"f", "e", "d", "b", "a"}


z = x.issubset(y)

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.

x = {"f", "e", "d", "c", "b", "a"}

y = {"a", "b", "c"}

z = x.issuperset(y)

print(z)

x = {"f", "e", "d", "c", "b", "a"}

y = {"a", "b", "c",”g”}

z = x.issuperset(y)

print(z)

xii. Pop()

The pop( ) function randomly removes an element from a set.

The pop() method removes a random item from the set.

fruits = {"apple", "banana", "cherry"}

fruits.pop()

print(fruits)

This method returns the removed item.

fruits = {"apple", "banana", "cherry"}

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 = {"apple", "banana", "cherry"}

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.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

z = x.symmetric_difference(y)

print(z)

Meaning: The returned set contains a mix of items that are not present in both
sets.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

x.symmetric_difference(y)

print(x)
Multiple values can be added using update( ) function.

>>> set1 ={12,34,43,2}

>>> set1.update( [76,84,14,56])

>>> set1

{2, 34, 43, 12, 76, 14, 84, 56}

>>>

Question 90.
What methods are used to remove value from sets?
Answer:
(1) discard( )
(2) remove ( )

Pop()

 The pop( ) function randomly removes an element from a set.

What is the difference between a tuple and a list?


Answer:
A tuple is immutable, it cannot be added to, rearranged, nor have items removed.
It is faster to access and use than a list but it cannot be manipulated.

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.

Python Built-in Functions


The built-in Python functions are pre-defined by the python interpreter. There are
68 built-in python functions. These functions perform a specific task and can be
used in any program, depending on the requirement of the user.
What are Python Functions?
There are three types of functions in the python programming language. These
are:
Built-in functions
User-defined functions
Anonymous functions
The pre-defined built-in function of the python programming language is given
below:
1st. abs()
this function is used to generate the absolute value of a number
2nd. all()
This python returns true when all the elements in iterable are true
3rd. any()
This method is used to check if any Element of an Iterable is True

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.

16.How do you define a local variable?


 You define a local variable by simply assigning a value to it inside a function
without using any special keywords.
Advantages of using local variables:
 Prevent accidental modification: They shield global variables from
unintended changes inside functions.
 Improve code clarity: Make the function's purpose and data usage more
explicit.
 Efficient memory usage: Local variables are destroyed when the function
exits, freeing up memory.
 Modular code: Local variables help separate data within functions,
promoting modularity and code reusability.
Disadvantages:

 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.

24.Examples of built-in variables:


 __name__: Contains the module name where your code is defined.
 __file__: Represents the path to the file containing your code.
 True, False, None: Boolean values and the null value.
25.Importance of built-in variables:
 Access system information without additional imports.
 Control program behavior based on the context.
 Improve code flexibility and adaptability.
LEGB Rule in Python:
 The LEGB rule is a fundamental concept in Python that governs the Local,
Enclosing, Global, and Built-in scope of variables. Mastering this rule is
crucial for freshers to write clean, efficient, and predictable Python code.

Local variable rules


 Variables defined inside a function are local to that function and have the
highest priority.
 They are only accessible within the function they are defined in and are
destroyed when the function
26.What are the key rules for local variables?
 Scope: Local variables are only accessible within the function they are
defined in. They are not visible to other functions or the main program.
 Lifetime: Local variables are created when the function is called and
destroyed when the function finishes execution. They do not exist outside
the function.
 Priority: In the LEGB rule (Local, Enclosing, Global, Built-in), local variables
have the highest priority. If a variable name exists both globally and locally
within the same scope, the local variable takes precedence.
 Modifiable data: Local variables can be modified within the function where
they are define

non-local variables rules


27.What are non-local variables in Python?
 Non-local variables are defined within a nested function but access
variables defined in the enclosing function, not the global scope. This allows
the nested function to directly modify the enclosing function's data
Key rules for non-local variables:

 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:

 Defined outside functions: Use the assignment operator outside any


function block to declare a global variable.
 Accessibility: Accessible throughout your program, regardless of scope.
 Modification: Can be modified from any function or the main program.
 Lifetime: Persists throughout the program's execution.
 Use cautiously: Overuse can lead to:
 Tightly coupled code: Functions become dependent on specific global
states, reducing modularity and reusability.
 Unexpected behavior: Changes in global variables can have unintended
consequences in different parts of your program.
 Difficulty debugging: Tracking down issues related to global variables can be
challenging.

Built in rules
Key Rules:

 Pre-defined by Python: No need to declare them within your code.


 Accessible everywhere: You can access them from any function or module
without restriction.
 Various types: Examples include __name__ (module name), __file__ (file
path), True, False, None (null value), mathematical constants, etc.
 Usefulness: Provide information about program execution, control program
behavior based on context, and improve code flexibility and adaptability.
 Limited modification: While some built-in variables like counters can be
updated, most are constants not meant to be changed directly.

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.

36.How do you use map()?


 It takes two arguments:
 Function: The function to be applied to each element.
 Iterable: The list or sequence of elements to apply the function to.
 The returned iterator needs to be converted to a concrete data type like a
list using list().
Example of using map():

 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:

 from functools import reduce


 numbers = [1, 2, 3, 4, 5]
 total = reduce(lambda x, y: x + y, numbers)
 print(total) # Output: 15
Example using a loop:
 total = 0
 for number in numbers:
 total += number
 print(total) # Output: 15
48.When to choose each method?
 Use functools.reduce if you need the efficiency and safety of a pre-defined
function for complex reductions.
 Use loops if you need fine-grained control over the reduction process or for
simple one-time operations.
 List comprehensions can be suitable for specific reduction patterns like
summing squares or extracting values.
49.What are modules and packages in Python?
 Modules: Reusable Python files containing functions, classes, and other
definitions.
 Packages: Collections of modules organized hierarchically.
50.What is a module in Python?
 A module is a file containing Python code that defines functions, classes,
and variables. It enables code reuse and organization by encapsulating
related functionality.
51.Why use modules?
 Modules improve code organization and readability by dividing complex
projects into smaller, modular units.
 They promote code reuse, avoiding duplicate code implementation across
different parts of your project.
 Modules allow sharing functionality with other Python programs through
importation.
52.How do you import a module?
 Use the import statement followed by the module name. For example,
import math imports the math module.

Different types of modules:


 Built-in modules: These are included with the Python interpreter and
contain basic functionalities like math, random, and os.
 Standard library modules: These are additional modules bundled with
Python but installed separately, encompassing diverse areas like datetime,
json, and urllib.
 Third-party modules: These are developed and distributed by external
communities, offering extensive functionalities for specific tasks like web
scraping, machine learning, and databases.

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 :-

 Web development (server-side)


 Mathematics
 Software development
 System scripting

3 . What can python do?


 Python can be used on a server to create web application.
 Python can be used along side software to create workflows
 Python can connect to database system
 It can also read and modify files
 Python can be used to handle big data and perform complex mathematics
 Python can be used for rapid prototyping, or for production-ready software
development

4 Why python?

 Python is a high level language and general-purpose programming language and


orinted programming language.
 Python works on different platforms(windows, linux, mac , raspberry pi, etc.)
 Python has a simple syntax similar to the english language.

5 How the strings get converted into numbers?

 Convert a string to float: float()


 Convert a string to int: int()
 Convert binary, octal, and hexadecimal strings to int
 Convert scientific notation strings to float

6 What are the advantages of Python?


 Readability:

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.

 Extensive Standard Library:

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.

 Community and Support:

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:

Python is platform-independent, meaning Python code can run on various operating


systems without modification.

 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.

 Large Ecosystem of Libraries and Frameworks:


Python has a rich ecosystem of libraries and frameworks that facilitate development in
different domains. For example, Django and Flask for web development, NumPy and
pandas for data science, TensorFlow and PyTorch for machine learning, and more.

 Strong Integration and Interoperability:

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:

Being a high-level language, Python abstracts many complex details, allowing


developers to focus more on solving problems rather than dealing with low-level details.

7 How to Use Python:

 Install Python:

You can download Python from the official website and follow the installation
instructions.

 IDEs and Text Editors:

Choose an Integrated Development Environment (IDE) or a text editor to write


and run your Python code. Examples include PyCharm, VSCode, Jupyter Notebooks, or
simple text editors like Sublime Text.

 Write Your Code:

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.

 Run Your Code:

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:

Python's syntax is designed to be readable and clean. This makes it easier to


write and maintain code. It's a great language for beginners and for large projects that
involve multiple developers.

 Versatility:

Python is a versatile language used in various domains such as web


development, data science, machine learning, artificial intelligence, automation,
scripting, and more. It can be used for both small scripts and large-scale applications.

 Large Standard Library:

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.

 Community and Support:

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.

 Popularity in Data Science and Machine Learning:

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.

9 What is the difference between Python 2 and Python 3?


• Answer: Python 3 is the latest version of Python and includes various syntax and
feature improvements. Python 2 is no longer supported. Key differences include print
function syntax, Unicode support, and integer division.

10 How do you comment in Python?

 Use the # symbol for single-line comments and triple-quotes ''' or """ for multi-line
comments.

11 .What is PEP 8?

 PEP 8 is the Python Enhancement Proposal that provides style guide


recommendations for writing clean and readable code.

You might also like