Python ALL Modules Merged[1]
Python ALL Modules Merged[1]
Introduction to Python
4. It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
7. Interpreted Language
Python is processed at runtime by python Interpreter
Module 1
Keywords:
1. Python keywords are reserved words that have special meaning and are
used to define the syntax and structure of the Python language.
2. These keywords cannot be used as identifiers (variable names,
function names, etc.). Python has 36 keywords as of version 3.10, such as
if, else, while, for, def, class, try, except, and with.
3. Each keyword serves a unique purpose, like def for defining functions,
if for conditional statements, and class for creating classes.
Understanding these keywords is essential for writing syntactically
correct Python code.
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
1. and
Definition: A logical operator used to combine conditional statements. It
returns True if both conditions are true.
Example:
x=5
y = 10
if x > 2 and y < 15:
print("Both conditions are true")
Output: Both conditions are true
2. as
Definition: Used to create an alias when importing a module or to handle
exceptions.
Example:
import math as m
print(m.sqrt(16))
Output: 4.0
3. assert
Definition: Used for debugging purposes, it tests if a condition is true. If
not, it raises an AssertionError.
Example:
assert 2 + 2 == 4, "Math is wrong!"
Output: No output (because the assertion is true)
4. break
Definition: Exits a loop prematurely when a condition is met.
Example:
Module 1
for i in range(5):
if i == 3:
break
print(i)
Output: 0 1 2
5. class
Definition: Used to define a new user-defined class.
Example:
class MyClass:
def __init__(self, name):
self.name = name
obj = MyClass("ChatGPT")
print(obj.name)
Output: ChatGPT
6. continue
Definition: Skips the current iteration of a loop and moves to the next
iteration.
Example:
for i in range(5):
if i == 3:
continue
print(i)
Output: 0 1 2 4
7. def
Definition: Used to define a function.
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
Module 1
Example:
fruits = ['apple', 'banana', 'cherry']
if 'apple' in fruits:
print("Apple is in the list")
Output: Apple is in the list
18. is
Definition: Tests for object identity, not equivalence.
Example:
x = [1, 2, 3]
y=x
print(x is y)
Output: True
19. lambda
Definition: Used to create small anonymous functions.
Example:
square = lambda x: x ** 2
print(square(5))
Output: 25
20. not
Definition: A logical operator used to reverse the logical state of its
operand.
Example:
x = False
print(not x)
Output: True
21. or
Definition: A logical operator used to combine conditional statements. It
returns True if at least one of the conditions is true.
Example:
Module 1
x=5
y = 10
if x > 2 or y > 15:
print("At least one condition is true")
Output: At least one condition is true
22. pass
Definition: A null statement, used as a placeholder in loops, functions,
and classes.
Example:
for i in range(5):
pass
23. return
Definition: Used to exit a function and optionally pass a value back to the
caller.
Example:
def add(x, y):
return x + y
print(add(5, 3))
Output: 8
24. while
Definition: Used to create a loop that continues running as long as the
condition is true.
Example:
i=1
while i < 4:
print(i)
i += 1
Output:
1
Module 1
2
3
25. with
Definition: Used to wrap the execution of a block of code in methods
defined by a context manager (commonly used for file operations).
Example:
with open('file.txt', 'r') as file:
content = file.read()
26. yield
Definition: Used to return a generator object and maintain the state of the
function.
Example:
def generator():
yield 1
yield 2
yield 3
for value in generator():
print(value)
Output:
1
2
3
# Importing modules
import math
Module 1
# Function definition
def check_number(value):
if value > 0:
return True
elif value == 0:
return None
else:
return False
# Class definition
class Number:
def __init__(self, value):
self.value = value
def display(self):
global is_positive
try:
assert isinstance(self.value, (int, float)), "Not a number"
print(f"Number: {self.value}")
except AssertionError as error:
print(f"Error: {error}")
if is_positive is True:
print("The number is positive.")
Module 1
Explanation:
import: Imports the math module.
def, return, global: Define a function check_number and return values.
class, self, init: Define a class Number with a method display.
if, elif, else, assert: Used in conditional statements.
for, while, break, continue: Demonstrate loops.
with, as: Use the context manager for file handling.
lambda, in: Create a lambda function and use it in list comprehension.
try, except, finally: Handle exceptions.
Output:
Number: 10
The number is positive.
Current value: 0
Current value: 1
Current value: 2
Squares: [0, 1, 4, 9, 16]
Cannot divide by zero.
Execution completed.
IDENTIFIERS:
Python Identifiers:
Identifiers in Python are names used to identify variables, functions,
classes, modules, and other objects. An identifier must start with a letter
(A-Z or a-z) or an underscore (_), followed by letters, digits (0-9), or
underscores. Identifiers are case-sensitive (myVar and myvar are
different). Keywords cannot be used as identifiers. There is no length
limit for identifiers, but they should be descriptive and readable.
Following the PEP 8 naming conventions, like using snake_case for
variables and functions, is recommended for clarity and consistency.
Module 1
No Reserved Keywords:
Identifiers cannot be the same as Python’s reserved keywords like class,
for, while, if, etc.
Example: while is invalid, but while_loop is valid.
Special Characters:
Identifiers cannot contain special characters like @, #, $, %, etc.
Example: my@variable is invalid.
Examples of Valid Identifiers:
variable1
totalSum
_name
Module 1
MAX_VALUE
Examples of Invalid Identifiers:
1variable (cannot start with a digit)
my-variable (hyphens are not allowed)
class (reserved keyword)
Best Practices:
Use meaningful names that describe the purpose of the variable or
function.
Follow a consistent naming convention, such as snake_case for variables
and functions, and PascalCase for classes.
Common Conventions:
snake_case: For variables and functions (e.g., total_sum, calculate_area).
PascalCase: For class names (e.g., StudentData, EmployeeRecord).
Uppercase: For constants (e.g., PI, MAX_SIZE).
Understanding these rules helps in writing clear and error-free Python
code.
Definition:
A variable in Python is a name that refers to a value stored in the memory.
Variables are used to store data that can be manipulated throughout a
program.
Explanation:
name, age, height, and is_student are variables storing different types of
data.
The print function is used to display the values of these variables.
Output:
Name: Alice
Age: 25
Height: 5.8
Is a student: True
Dynamic Typing:
Python is dynamically typed, meaning the type of a variable is
determined at runtime and can change as needed.
Module 1
x = 10 # x is an integer
x = "Ten" # Now x is a string
In the above example, the type of x changes from an integer to a string.
Data types:
The data stored in memory can be of many types. For example, a student
roll number is
stored as a numeric value and his or her address is stored as alphanumeric
characters. Python
has various standard data types that are used to define the operations
possible on them and
the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals,
of unlimited
length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
Module 1
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative,
containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of
10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2
2.0
Example:
x = 35e3
y = 12E4
Module 1
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
1. Strings in Python are identified as a contiguous set of characters
represented in the
quotation marks. Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example:
print("hello").
>>> print("mrcet college")
mrcet college
>>> type("mrcet college")
<class 'str'>
>>> print('mrcet college')
mrcet college
>>> " "
''
Module 1
If you want to include either type of quote character within the string, the
simplest way is to
delimit the string with the other type. If a string is to contain a single
quote, delimit it with
double quotes and vice versa:
>>> print("mrcet is an autonomous (') college")
mrcet is an autonomous (') college
>>> print('mrcet is an autonomous (") college')
mrcet is an autonomous (") college
Suppressing Special Character:
Specifying a backslash (\) in front of the quote character in a string
“escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply
as a literal single
quote character:
>>> print("mrcet is an autonomous (\') college")
mrcet is an autonomous (') college
>>> print('mrcet is an autonomous (\") college')
mrcet is an autonomous (") college
The following is a table of escape sequences which cause Python to
suppress the usual
special interpretation of a character in a string:
>>> print('a\
....b')
a....b
>>> print('a\
b\
c')
Key Points
Module 1
2. Multi-Paradigm
Python supports multiple programming paradigms. It allows developers
to choose the approach that best fits their specific project. Object-oriented
programming is supported in Python, which enables developers to create
reusable code. Procedural programming is also possible in Python. It
allows developers to break down a program into smaller, more
manageable parts. Additionally, Python supports functional programming,
which enables developers to write code in a declarative style.
3. Open Source
Python is an open-source language. It can be freely modified, used, and
distributed. This open-source nature of Python has made it popular
among developers. It allows for the creation of software without the need
for expensive licenses. The open-source community has also contributed
to the development of Python, with many libraries, tools, and frameworks.
Module 1
6. Dynamically Typed
Python is a dynamically typed language. In this, the type of a variable is
determined at runtime. Unlike statically typed languages, Python does not
require variable declarations or explicit type definitions. This feature
makes writing and maintaining code more accessible. The developers do
not have to worry about type errors and can focus on the code's
functionality.
8. Portable
Python code can be run on different operating systems and platforms,
making it a highly portable language. Python is supported on various
platforms like Linux, macOS, Windows, and mobile devices. The
portability of Python makes it ideal for developing cross-platform
applications.
9. Platform Independent
It is a platform-independent programming language that can run on
different operating systems and hardware architectures without
modification.
10. Scalable
Python can be used for both large-scale operations and small scripts. It
makes it a universal language. This scalability has made Python popular
among startups and small businesses.
12. Interpreted
Python is an interpreted language executed line by line by an interpreter.
This feature makes it easier to debug and test code. The errors can be
identified and corrected quickly. The interpreter provides immediate
feedback, which can be helpful in development.
Module 1
14. Cross-Platform
Python can run on various operating systems like Windows, Linux, and
macOS, making it a highly portable language.
15. Extensible
Python is highly extensible and can be integrated with C and C++. It
allows developers to write performance-critical code in these languages
and then call them from Python.
2. Multiple Assignment
Python allows multiple variables to be assigned values in a single
statement.
Example:
a, b, c = 1, 2, 3 # Assigns 1 to a, 2 to b, and 3 to c
You can also assign the same value to multiple variables simultaneously:
x = y = z = 100 # Assigns 100 to x, y, and z
b = 10
b %= 3 # Equivalent to b = b % 3; b is now 1
Exponentiation Assignment (**=)
c=2
c **= 3 # Equivalent to c = c ** 3; c is now 8
Floor Division Assignment (//=):
d = 17
d //= 4 # Equivalent to d = d // 4; d is now 4
Unpacking Assignment
Python allows for unpacking values from a collection (like a list or tuple)
directly into variables.
Expressions in Assignment Statements
An expression is any valid combination of operators, literals, and
variables that Python can evaluate to produce a value. Expressions are
often used on the right-hand side of an assignment statement.
x = 5 + 2 * 3 # The expression evaluates to 11 and is assigned to x
y = (x - 3) / 2 # The expression evaluates to 4.0 and is assigned to y
z = x > y # The expression evaluates to True (boolean) and is assigned to
z
1. The assignment operator = binds values to variables.
2. Augmented assignment operators simplify operations and assignments.
3. Multiple variables can be assigned values in a single statement.
4. Python expressions can involve a combination of operators and
variables to produce values that can be assigned to variables.
Operators and Expressions: Numeric Expressions in Python
Numeric expressions in Python involve the use of various arithmetic
operators to perform mathematical calculations. These expressions can be
Module 1
f = 17 % 3 # f is 2
Exponentiation (**): Raises the first number to the power of the second.
g = 2 ** 3 # g is 8
Comparison Operators
These operators compare two numbers and return a Boolean value (True
or False).
Equal to (==): Checks if two numbers are equal.
5 == 5 # True
Not equal to (!=): Checks if two numbers are not equal.
5 != 3 # True
Greater than (>): Checks if the first number is greater than the second.
7 > 5 # True
Less than (<): Checks if the first number is less than the second.
3 < 10 # True
Greater than or equal to (>=): Checks if the first number is greater than or
equal to the second.
7 >= 7 # True
Less than or equal to (<=): Checks if the first number is less than or equal
to the second.
4 <= 5 # True
Bitwise Operators
Bitwise operators work on the binary representations of numbers.
Associativity:
When two operators of the same precedence appear in an expression,
Python uses associativity rules to determine the order of evaluation:
Left-to-Right Associativity: Most operators (like +, -, *, /, etc.) are left-
associative, meaning they are evaluated from left to right.
Example: 5 - 3 + 2 is evaluated as (5 - 3) + 2.
Right-to-Left Associativity: Some operators, like exponentiation (**)
and assignment (=), are right-associative.
Module 1
3. Parentheses
Parentheses can be used to explicitly specify the order of evaluation.
Expressions within parentheses are evaluated first, regardless of operator
precedence.
Example: In (3 + 4) * 2, the expression inside the parentheses is
evaluated first, resulting in 7 * 2 = 14.
Function Calls
Function arguments are evaluated before the function is called.
Example: In print(3 + 4 * 2), 4 * 2 is evaluated first, then added to 3, and
finally, the result is passed to print().
5. Short-Circuit Evaluation
Logical operators like and and or use short-circuit evaluation. In and
expressions, if the first operand is false, Python skips evaluating the
second operand because the whole expression will be false. Similarly, in
or expressions, if the first operand is true, the second operand is not
evaluated.
Example: In x and y, if x is False, y is not evaluated.
Type Conversion
In programming, type conversion is the process of converting data of one
type to another. For example: converting int data to str.
integer_number = 123
float_number = 1.23
Then we added these two variables and stored the result in new_number.
As we can see new_number has value 124.23 and is of the float data type.
Note:
We get TypeError, if we try to add str and int. For example, '12' + 23.
Python is not able to use Implicit Conversion in such conditions.
Python has a solution for these types of situations which is known as
Explicit Conversion.
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to
required data type.
We use the built-in functions like int(), float(), str(), etc to perform
explicit type conversion.
This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
Data type of num_string before Type Casting: <class 'str'>
Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>
In the above example, we have created two variables: num_string and
num_integer with str and int type values respectively. Notice the code,
num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of
num_string to integer type.
Finally, we got the num_sum value i.e 35 and data type to be int.
1. Type Conversion is the conversion of an object from one data type to
another data type.
2. Implicit Type Conversion is automatically performed by the Python
interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
4. In Type Casting, loss of data may occur as we enforce the object to a
specific data type.
Module 1
Example:
x = 10 # integer
y = 3.5 # float
result = x + y
Integer to Float:
x=5
y = float(x)
print(y) # Output: 5.0
Float to Integer:
x = 3.9
y = int(x)
print(y) # Output: 3
Integer to String:
x = 10
y = str(x)
print(y) # Output: '10'
String to Integer:
x = "123"
y = int(x)
print(y) # Output: 123
Module 1
List to Tuple:
x = [1, 2, 3]
y = tuple(x)
print(y) # Output: (1, 2, 3)
Tuple to List:
x = (1, 2, 3)
y = list(x)
print(y) # Output: [1, 2, 3]
Important Considerations:
1. Input Statements
The input() function is used to take input from the user. By default, it
reads the input as a string.
Syntax:
variable = input(prompt)
prompt: A string that is displayed on the screen to ask for user input
(optional).
Examples:
Basic Input:
name = input("Enter your name: ")
print("Hello, " + name + "!")
Here, the program asks the user for their name and then prints a greeting.
Integer Input:
age = int(input("Enter your age: "))
print("You are", age, "years old.")
The input is converted to an integer using int() before storing it in the age
variable.
2. Output Statements
The print() function is used to display output to the screen.
Syntax:
Python
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
objects: The values to be printed.
Module 1
Basic Output:
print("Hello, World!")
This prints the string Hello, World!.
Custom Separator:
print("apple", "banana", "cherry", sep=", ")
This prints apple, banana, cherry.
Custom End:
print("Hello", end=" ")
print("World!")
This prints Hello World! on the same line.
3. Formatted Output
Python allows for formatted strings using the format() method or f-strings
(formatted string literals).
Using f-strings:
name = "Bob"
age = 30
print(f"{name} is {age} years old.")
This also prints Bob is 30 years old..
ummary
input(): Used for taking input from the user, with all input being treated
as strings by default.
print(): Used for outputting data to the screen, with options for
customizing the format.
Formatted Strings: Allow embedding expressions within string literals
using f-strings or the format() method.
Comments in python
Comments in Python
Comments in Python are used to explain the code, making it easier to
understand for anyone reading it. They are ignored by the Python
interpreter during execution.
1. Single-Line Comments
Single-line comments start with the # symbol. Anything following the #
on that line is treated as a comment.
Example:
python
# This is a single-line comment
print("Hello, World!") # This prints a message
2. Multi-Line Comments
Python does not have a specific syntax for multi-line comments, but you
can create them by using multiple single-line comments or by using
triple-quoted strings (''' or """). While triple-quoted strings are technically
string literals, they can be used as comments if they are not assigned to a
variable or used in any other way.
Module 1
python
# This is a multi-line comment
# Each line starts with a #
print("Hello, World!")
Using Triple-Quoted Strings:
python
"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Hello, World!")
3. Best Practices for Comments
Keep Comments Relevant: Comments should explain why something is
done, not what is being done. The code should be self-explanatory
whenever possible.
Avoid Redundant Comments: Comments that restate the obvious should
be avoided.
Update Comments: Ensure that comments are updated if the related code
changes.
Example of Good Commenting:
python
# Calculate the area of a circle
radius = 5
area = 3.14 * (radius ** 2) # Use the formula: πr^2
Module 1
print(area)
Summary
Single-Line Comments: Start with # and extend to the end of the line.
Multi-Line Comments: Use multiple # symbols or triple-quoted strings.
Best Practices: Keep comments concise, relevant, and up-to-date.
Sample Questions-Module 1
MODULE-2
Module 2
Loops and Control statements: if, elif , Nested if, for, while continue, Break,
Pass.
Functions : Advantages of Functions in python, creating a Function, Function
Calling, return Statement, Arguments in Function, Pass by object Reference,
Built in Functions, Lambda Functions,
Map, Filter, Reduce functions, Recursive functions.
Module 2
If statement in Python
In control statements, The if statement is the simplest form. It takes a
condition and evaluates to either True or False.
If the condition is True, then the True block of code will be executed,
and if the condition is False, then the block of code is skipped, and
The controller moves to the next line
Module 2
Python if statements :
Let’s see the example of the if statement. In this example, we will
calculate the square of a number if it greater than 5
Module 2
Example
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output
36
Next lines of code
If – else statement
The if-else statement checks the condition and executes the if block
of code when the condition is True, and if the condition is False, it
will execute the else block of code.
Syntax of the if-else statement
if condition:
statement 1
else:
Module 2
statement 2
If the condition is True, then statement 1 will be executed If the
condition is False, statement 2 will be executed. See the
following flowchart for more detail.
if password == "PYnative@#29":
print("Correct password")
else:
Module 2
print("Incorrect Password")
Output 1:
Enter password PYnative@#29
Correct password
Output 2:
Enter password PYnative
Incorrect Password
Chain multiple if statement in Python
In Python, the if-elif-else condition statement has an elif blocks to
chain multiple conditions one after another. This is useful when you
need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision.
The elif statement checks multiple conditions one by one and if the
condition fulfills, then executes that code.
Syntax of the if-elif-else statement:
if condition-1:
statement 1
elif condition-2:
stetement 2
Module 2
elif condition-3:
stetement 3
...
else:
statement
Example
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
Module 2
user_check(4)
Output:
Admin
Editor
Guest
Wrong entry
statement ot outer if
else:
Outer else
statement outside if block
Example: Find a greater number between two numbers
num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78
Loops In python
In Python, loops are used to repeat a block of code multiple times. Python
provides two primary types of loops: the for loop and the while loop. Each
loop type serves a different purpose and is suited to different kinds of
problems.
In programming, the loops are the constructs that repeatedly execute a piece
of code based on the conditions. These are useful in many situations like
going through every element of a list, doing an operation on a range of
values, etc.
There are two types of loops in Python and these are for and while loops.
Both of them work by following the below steps:
1. Check the condition
2. If True, execute the body of the block under it. And update the iterator/
the value on which the condition is checked.
3. If False, come out of the loop
Module 2
the first statement following the loop body, but there isn’t one in this
case.
Note that the controlling expression of the while loop is tested first, before
anything else happens. If it’s false to start with, the loop body will never be
executed at all:
Python
>>> n = 0
>>> while n > 0:
... n -= 1
... print(n)
...
In the example above, when the loop is encountered, n is 0. The controlling
expression n > 0 is already false, so the loop body never executes.
Here’s another while loop involving a list, rather than a numeric comparison:
Python
>>> a = ['foo', 'bar', 'baz']
>>> while a:
... print(a.pop(-1))
...
baz
bar
Module 2
foo
When a list is evaluated in Boolean context, it is truthy if it has elements in it
and falsy if it is empty. In this example, a is true as long as it has elements in
it. Once all the items have been removed with the .pop() method and the list
is empty, a is false, and the loop terminates.
pass
print(months)
Output
['January', 'June', 'March', 'April']The else Clause
Python allows an optional else clause at the end of a while loop. This is a
unique feature of Python, not found in most other programming languages.
The syntax is shown below:
Python
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
The <additional_statement(s)> specified in the else clause will be executed
when the while loop terminates.
About now, you may be thinking, “How is that useful?” You could accomplish
the same thing by putting those statements immediately after
the while loop, without the else:
Python
while <expr>:
<statement(s)>
<additional_statement(s)>
Module 2
For loop in Python works on a sequence of values. For each value in the
sequence, it executes the loop till it reaches the end of the sequence. The
syntax for the for loop is:
for iterator in sequence:
statement(s)
We use an iterator to go through each element of the sequence. For
example, let us use for loop to print the numbers from 0 to 4.
In the syntax, i is the iterating variable, and the range specifies how
many times the loop should run. For example, if a list contains
10 numbers then for loop will execute 10 times to print each number.
In each iteration of the loop, the variable i get the current value.
Functions in python :
Python Functions
A function is a block of code that performs a specific task.
Suppose we need to create a program to make a circle and colour it. We can
create two functions to solve this problem:
1. function to create a circle
2. function to colour the shape
Module 2
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Create a Function
Let's create our first function.
def greet():
print('Hello World!')
Here are the different parts of the program:
Calling a Function
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')
If we run the above code, we won't get an output.
It's because creating a function doesn't mean we are executing the code
inside it. It means the code is there for us to use if we want to.
To use this function, we need to call the function.
Function Call
greet()
print('Outside function')
Output
Module 2
Hello World!
Outside function
In the above example, we have created a function named greet(). Here's how
the control of the program flows:
Calling a Function
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')
If we run the above code, we won't get an output.
It's because creating a function doesn't mean we are executing the code
inside it. It means the code is there for us to use if we want to.
Module 2
print('Outside function')
# pass argument
Module 2
greet("John")
Sample Output 1
Hello John
Here, we passed 'John' as an argument to the greet() function.
We can pass different arguments in each call, making the function re-usable
and dynamic.
Let's call the function with a different argument.
greet("David")
Sample Output 2
Hello David
Output
Hello World!
Outside function
In the above example, we have created a function named greet(). Here's how
the control of the program flows:
# function call
square = find_square(3)
Module 2
print('Square:', square)
Output
Square: 9
In the above example, we have created a function named find_square().
The function accepts a number and returns the square of the number.
import math
# Output
(512, 384)
Module 2
Now, we shall unpack the tuple and store the values in two different
variables.
volume, area = cube(6.5)
print(f"Volume of the cube is {volume} cubic units and the total surface area
is {area} sq. units")
# Outputs
Volume of the cube is 274.625 cubic units and the total surface area is 253.5
sq. units
Pass by reference means that you have to pass the function (reference) to a
variable, which means that the variable already exists in memory.
Here, the variable( the bucket) is passed into the function directly. The
variable acts as a package that comes with its contents (the objects).
Module 2
In the above code image, both “list” and “my_list” are the same container
variable and therefore refer to the same object in the memory. Any
operation performed by the function on the variable or the object will be
directly reflected by the function caller. For instance, the function could
completely change the variable’s content, and point it at a completely
different object:
Also, the function can reassign the contents of the variable with the same
effect as below:
Module 2
To summarize, in pass-by-reference, the function and the caller use the same
variable and object.
Pass by Reference In Python Example
In this example, the function modify_list takes a list by reference. The
function adds the string “Geeks” to the passed list inside the function and
prints it. Since lists are mutable data types, the changes made to the list
inside the function are also reflected outside the function as you can see in
the output.
Python
def modify_list(x):
x.append("Geeks")
print("Inside function:", x)
modify_list(my_list)
print("Outside function:", my_list)
Output
Inside function: ['Geeks', 'for', 'Geeks']
Outside function: ['Geeks', 'for', 'Geeks']
Built in functions in Python :
Python has many built-in functions that you can use directly without
importing anything. These functions cover a wide variety of common
programming tasks that include performing math operations, working with
built-in data types, processing iterables of data, handling input and output in
your programs, working with scopes, and more.
Built-in Functions
A E L R
abs() enumerate() len() range()
aiter() eval() list() repr()
all() exec() locals() reversed()
anext() round()
any() F M
ascii() filter() map() S
float() max() set()
B format() memoryview() setattr()
bin() frozenset() min() slice()
bool() sorted()
breakpoint() G N staticmethod()
bytearray() getattr() next() str()
bytes() globals() sum()
O super()
C H object()
callable() hasattr() oct() T
chr() hash() open() tuple()
classmethod() help() ord() type()
Module 2
compile() hex()
complex() P V
I pow() vars()
D id() print()
delattr() input() property() Z
dict() int() zip()
dir() isinstance()
divmod() issubclass() _
iter() __import__()
Function Description
hasattr() Returns True if the specified object has the specified attribute
map() Returns the specified iterator with the specified function applie
Lambda Function :
In Python, a lambda function is a small, anonymous function defined using
the lambda keyword.
These functions are typically used for short, throwaway operations where a
full function definition might be overkill. They are called anonymous because
they do not require a name (although they can be assigned to a variable for
reuse).
Lambda functions excel in scenarios where you need a quick, simple function
for a brief period, and a full function definition would be excessive. This
makes them ideal for operations that are straightforward and can be written
in a single line, such as simple mathematical calculations or basic data
transformations.
They are particularly used in functional programming contexts with higher-
order functions like map, filter, and reduce where they are often passed as
arguments. Just remember that for more complex operations, regular
functions are preferred for their readability and maintainability.
Lambda Function Syntax and Basic Uses
lambda arguments: expression
def function_name(arguments):
return expression
Unlike regular functions defined with def, lambda functions are limited to a
single expression due to their design for simplicity and brevity. They can take
single or multiple arguments but cannot contain statements or multiple
expressions.
Lambda functions are intended for short, straightforward operations that can
be written in a single line.
Example:
# Regular function to find the average of three numbers
def average(x, y, z):
return (x + y + z) / 3
These are functions that take other functions as arguments. They help in
processing collections of data (like lists or tuples) in a functional
programming style.
Using lambda functions with map()
The map function applies a specified function to each item in an iterable (like
a list) and returns a new iterable with the updated items.
# syntax
map(function, iterable)
function here takes one argument and returns a value.
iterable's elements (for example, list, tuple) will be passed to the
function.
Example:
# List of pairs of numbers
pairs = [(2, 3), (4, 5), (6, 7)]
# Using lambda function with map to multiply each pair and print the result
list(map(lambda pair: print(f'{pair[0]} * {pair[1]} = {pair[0] * pair[1]}'), pairs))
Explanation: In this code, we use a lambda function to define a small,
anonymous function that takes each pair of numbers and prints their
multiplication.
The map function applies this lambda function to each pair (tuple) in the list.
Wrapping the map call with list ensures the lambda function is executed for
Module 2
each pair. As a result, the code prints the multiplication results for each pair
in the list, showing outputs like "2 3 = 6", "4 5 = 20", and "6 * 7 = 42".
filter(predicate, iterable)
Predicate is a function that takes one argument and returns a boolean value
(True or False). Iterable elements here will be tested by the predicate.
Example:
# List of ages
ages = [25, 30, 18, 42, 17, 50, 22, 19]
# Function to filter adults (age 18 and above) using filter with lambda
adults = filter(lambda age: age >= 18, ages)
print(list(adults)) # Output: [25, 30, 18, 42, 50, 22, 19]
Explanation: In this code, we start with a list of ages. We use a lambda
function to define a simple condition that checks if an age is 18 or older.
The filter function applies this lambda function to each age in the list,
filtering out any ages below 18. By converting the result of filter to a list, we
Module 2
obtain a list of ages that are 18 and above. Finally, we print this filtered list,
which results in the ages [25, 30, 18, 42, 50, 22, 19] being displayed, as these
are the ages that meet the criterion of being 18 or older.
Using lambda functions with reduce()
The reduce function applies a specified function to the elements of an
iterable cumulatively to reduce them to a single value. It is part of
the functools module.
# syntax
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Output: 15
Explanation: In this code, we start with a list of numbers. We use
the reduce function from the functools module to compute the sum of all
the numbers in the list. We use a lambda function to define a simple addition
operation that takes two arguments, x and y, and returns their sum.
The reduce function applies this lambda function cumulatively to the items
in the list, starting from the first pair and continuing through the entire list,
like this:
Initially, x is the first element of the list (1) and y is the second element
(2), resulting in 3.
This sum (3) then becomes x, and the next element in the list (3)
becomes y, yielding 6.
This process continues until all elements in the list have been summed.
Ultimately, the final result is 15, representing the sum of all the
numbers in the list [1, 2, 3, 4, 5].
print(sorted_cities)
# Output: ['America', 'Germany', 'India', 'Japan']
In this code, we have a list called cities containing the names of different
cities. We use the sorted function to sort these city names alphabetically,
ignoring case sensitivity. The key parameter in the sorted function allows us
to specify a function (in this case, a lambda function) to customize the
sorting order.
The lambda function lambda city: city.lower() converts each city name to
lowercase before sorting. This ensures that the sorting is case-insensitive, so
cities with different capitalization are treated the same way.
After sorting, the sorted list is assigned to the variable sorted_cities, and we
print the result. The output shows the sorted list of cities: ['America',
'Germany', 'India', 'Japan'], where the cities are arranged alphabetically
ignoring the case of the letters.
Lambda Functions in List Comprehensions:
Lambda functions can be used within list comprehensions to apply a function
to each element in a list.
Example:
# List of numbers
numbers = [1, 2, 3, 4, 5]
Conclusion
Lambda functions in Python provide a quick and concise way to create small,
throwaway functions. They're especially useful in functional programming
with higher-order functions like map, filter, and reduce.
While lambda functions are powerful and concise, make sure you balance
their use with code readability and maintainability. For more complex logic,
regular functions defined with def are preferred because they support
multiple expressions and statements, and you can include documentation.
By understanding and using lambda functions effectively, you can write more
concise and efficient Python code.
map() :
The map() function in python has the following syntax:
map(func, *iterables)
Where func is the function on which each element in iterables (as many as
they are) would be applied on. Notice the asterisk(*) on iterables? It means
there can be as many iterables as possible, in so far func has that exact
number as required input arguments. Before we move on to an example, it's
important that you note the following:
1. In Python 2, the map() function returns a list. In Python 3, however, the
function returns a map object which is a generator object. To get the
result as a list, the built-in list() function can be called on the map
object. i.e. list(map(func, *iterables))
2. The number of arguments to func must be the number
of iterables listed.
Let's see how these rules play out with the following examples.
Say I have a list (iterable) of my favourite pet names, all in lower case and I
need them in uppercase. Traditonally, in normal pythoning, I would do
something like this:
Example :
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = []
Module 2
print(uppered_pets)
output :
['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']
filter() :
While map() passes each element in the iterable through a function and
returns the result of all elements having passed through the function, filter(),
first of all, requires the function to return boolean values (true or false) and
then passes each element in the iterable through the function, "filtering"
away those that are false. It has the following syntax:
filter(func, iterable)
The following points are to be noted regarding filter():
1. Unlike map(), only one iterable is required.
2. The func argument is required to return a boolean type. If it
doesn't, filter simply returns the iterable passed to it. Also, as only one
iterable is required, it's implicit that func must only take one argument.
3. filter passes each element in the iterable through func and
returns only the ones that evaluate to true. I mean, it's right there in the
name -- a "filter".
Let's see some examples
Module 2
def is_A_student(score):
return score > 75
reduce() :
Reduce applies a function of two arguments cumulatively to the elements of
an iterable, optionally starting with an initial argument. It has the following
syntax:
reduce(func, iterable[, initial])
Where func is the function on which each element in the iterable gets
cumulatively applied to, and initial is the optional value that gets placed
before the elements of the iterable in the calculation, and serves as a default
when the iterable is empty. The following should be noted about reduce():
Module 2
1. func requires two arguments, the first of which is the first element
in iterable (if initial is not supplied) and the second element in iterable.
If initial is supplied, then it becomes the first argument to func and the first
element in iterable becomes the second element. 2. reduce "reduces" (I
know, forgive me) iterable into a single value.
As usual, let's see some examples.
Let's create our own version of Python's built-in sum() function.
The sum() function returns the sum of all the items in the iterable passed to
it.
Example :
from functools import reduce
Recursive Functions :
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.
Factorial of a number is the product of all the integers from 1 to that number.
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself.
When we call this function with a positive integer, it will recursively call itself
by decreasing the number.
Module 2
Each function multiplies the number with the factorial of the number below
it until it is equal to one. This recursive call can be explained in the following
steps.
Our recursion ends when the number reduces to 1. This is called the base
condition.
Every recursive function must have a base condition that stops the recursion
or else the function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite
recursions, resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it
results in RecursionError. Let's look at one such condition.
def recursor():
recursor()
recursor()
Module 2
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
Recursion Error: maximum recursion depth exceeded
12. Discuss the usage of break, continue, and else statements in loops with
examples.
13. Write a Python program to count the number of vowels in a given string
using a loop. Explain the process of iteration and conditional checks in your
program.
14. How does a for loop with the range() function work in Python? Write a
program that prints all even numbers between 1 and 100 using a for loop
and range().
15. Describe how the else clause works with loops in Python. Write a Python
program that demonstrates the use of else with a loop and explain its
execution.
16. Write a Python program to reverse a list of integers using a loop. Provide
detailed explanations of the logic and loop structure used.
17. Compare and contrast the use of while loops and for loops in Python for
solving problems where the number of iterations is known versus unknown.
Provide examples.
18. Write a Python program that sums all the numbers divisible by 3 or 5
below 1000 using a loop. Explain how the loop works and how the sum is
calculated.
19. Explain the concept of functions in Python. Differentiate between built-in
and user-defined functions with examples.
20. Write a Python function to check whether a number is prime. Explain
how function definition, function call, and return statements work in this
program.
Module 2
30. Explain how lambda functions are used with map(), filter(), and reduce()
in Python. Write a Python program to demonstrate their use in transforming
and reducing a list of integers.
Module 3
MODULE 3
Strings:
A String is a data structure in Python Programming that represents a
sequence of characters. It is an immutable data type, meaning that once you
have created a string, you cannot change it. Python Programming does not
have a character data type, a single character is simply a string with a length
of 1.
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters; internally, it
stores manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters
in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to
create the string.
Python String are used widely in many different applications, such as storing
and manipulating text data, representing names, addresses, and other types
of data that can be represented as text.
Module 3
Syntax:
string_variable = 'Hello, world!'
Example
str = “ Hello,World! “
Creating String
Create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
OUTPUT:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Module 3
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Module 3
OUTPUT :
H
E
L
L
O
IndexError: string index out of range
The slice operator [] is used to access the individual characters of the string. However, we can
use the: (colon) operator in Python to access the substring from the given string. Consider the
following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if
str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
Module 3
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])
OUTPUT :
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.
Module 3
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])
OUTPUT:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Module 3
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with new string since its
content cannot be partially replaced. Strings are immutable in Python.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
OUTPUT :
Traceback (most recent call last):
File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
Module 3
Example :
1. str = "JAVATPOINT"
2. del str[1]
OUTPUT :
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
OUTPUT :
NameError: name 'str1' is not defined
String Operators
Module 3
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to print
the actual meaning of escape characters such as "C://python". To define any string as a raw
string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how formatting is
done in python.
Example :
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
Module 3
10. print("The string str : %s"%(str)) # prints The string str : Hello
OUTPUT :
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Method Description
center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for encoding.
'strict')
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
isalpha() It returns true if all the characters are alphabets and there is at
least one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at least
one character, otherwise False.
istitle() It returns true if the string is titled properly and false otherwise.
A title string is the one in which the first character is upper-case
whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true
otherwise it returns false.
ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.
partition() It searches for the separator sep in S, and returns the part before
it, the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the backward
direction. It returns the list of words in the string. If Separator is
not specified then the string splits according to the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It returns
the list of substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str
between begin and end.
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
translate(table,deletechars = '') It translates the string according to the translation table passed
in the function .
Module 3
rpartition()
Sample Questions-Module 3
1. Explain the below functions in Python – read (), write (), append (), open ()
2. With examples, Illustrate the difference between string indexing and string slicing.
4. Write a Python program that accepts a hyphen separated sequence of words as input and
prints the words in hyphen-separated sequence after sorting them alphabetically
5. With an example show how to import modules in Python
7. Write a Python program to count number of uppercase letters, lowercase letters and spaces in
a string and toggle case the given string
8. With suitable examples, Explain read mode in file handling in python.
10. With suitable examples, Explain write and append mode in file handling.
11. Write a python program to count the number of words, characters and lines in a specified file.
13. Explain the difference between single string and multiline string with an example
15. Illustrate the working of replace and Case fold function with an example.
16. Discuss string indexing and slicing in Python. Illustrate your answer with examples showing
how to access individual characters.
17. Describe the various string operators available in Python. Provide examples of string
concatenation, repetition, and membership testing using the in operator.
18. Explain the concept of exception handling in Python. Define the purpose of try, except, raise,
and finally blocks with examples.
19. What are assertions in Python, and how are they used? Discuss their purpose in debugging
and testing code, along with the syntax for using assertions.
20. Explain how to create strings in Python. Provide examples of string creation using single
quotes, double quotes, and triple quotes.
MODULE-4
List: Creating a List, List indexing and splitting, Python List Operations, List Built-in functions,
Tuple: Creating a tuple, Indexing, Deleting Tuple, Tuple operations, Tuple inbuilt functions.
Set: Creating a set, Python Set Operations, Python Built-in set methods.
Dictionary: Creating the dictionary, Properties of Keys and Values, Accessing the dictionary values, and
>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
List slices:
List slicing is an operation
that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1
[:] this will print the entire list
[2:2] this will create a empty slice
slices example description
a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from
>>> a[0:3] 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. so
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]
List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)
>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>> a.pop() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 a.pop(index) >>> a.pop(0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 a.remove(element) >>> a.remove(1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 a.count(element) >>> a.count(6) Returns the count of
2 number of items
passed as an
argument
>>>a=[7, 6, 5, 4, 3, 2]
11 a.copy() >>> b=a.copy() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>> a.clear() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined
List loops:
1. For loop
2. While loop
3. Infinite loop
List using For Loop:
The for loop in Python
is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
Iterating over a sequence is called traversal.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using indentation.
Syntax:
for val in sequence:
Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
An item can
be changed in a list by accessing it directly as part of the assignment
statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.
Example description
changing single element
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing multiple element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]
Aliasing(copying):
Creating a copy of a list is called aliasing.
When you create a copy both the list will be having same memory location.
changes in one list will affect another list.
Alaising refers to having different names for same list values.
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
In this a single list object is created and modified using the subscript operator.
When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.
This type of change is what is known as a side effect. This happens because after
the assignment b=a, the variables a and b refer to the exact same list object.
They are aliases for the same object. This phenomenon is known as aliasing.
To prevent aliasing, a new object can be
created and the contents of the original
can be copied which is called cloning.
Clonning:
To avoid the disadvantages of copying we are using cloning.
Creating a copy of a same list of elements with two different memory locations is called cloning.
Changes in one list will not affect locations of aother list.
Cloning is a process of making a copy of the list without modifying the original list.
1. Slicing
2. list()method
3. copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
List as parameters:
In python, arguments are passed by reference.
If any changes are done in the parameter which refers
within the function, then the
changes also reflects back in the calling function.
When a list to a function is passed, the function gets a reference to the list.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example 1`: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:
A tuple is same as list,
except that the set of elements is enclosed in parentheses instead
of square brackets.
A tuple is an immutable list. i.e. once a tuple
has been created, you can't add elements to
a tuple or remove elements from the tuple.
But tuple can be converted into list and list can be converted in to tuple.
methods example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:
Tuple is immutable
so changes cannot be done on the elements of a tuple once it is
assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.
Tuple Assignment:
Tuple assignment allows, variables on the leftof an assignment operator and values of
tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right hand
side, and
a tuple of targets from the left, and then matching each expression to a
target.
Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
Sets
What is a Set?
– Example A = {x : x N, x < 5}
Some examples of Roster Form vs Set-builder Form
Roster Form Set-builder Form
1 {1, 2, 3, 4, 5} {x | x N, x <6}
Sets of Numbers
1. Natural Numbers (N)
2. Integers (Z)
W = {0, 1, 2, 3, 4, 5, 6…}
{𝑝 : p Z, q Z, q ≠ 0}
𝑞
Empty Set
• It is denoted by ϕ (phai)
• Also n (ϕ) = 0
Equal Sets
• i.e. A ⊆ A, B ⊆ B etc.
• i.e. ϕ ⊆ A, ϕ ⊆ B
• If A ⊆ B and B ⊆ A, then A = B
• Similarly, if A = B, then A ⊆ B and B ⊆ A
• The set of all possible subsets of a set A is called the power set of A,
denoted by P(A). IfA contains n elements, then P(A) = 2n sets.
• Let A be any set and let B be any non-empty subset. Then A is called
a proper subset ofB, and is written as A B, if and only if every
element of A is in B, and there exists at least one element in B
which is not there in A.
• i.e. if A = {1, 2}, B = {3, 4}, and C = {1, 5}, then U or = {1,
2, 3, 4, 5}
Operations on Sets
• Union of Sets
• So if A B = {x | x A or x B}
• Disjointed Sets
• Intersecting sets
• Two sets are said to be intersecting or overlapping or
joint sets, if they haveat least one element in common.
• Intersection of sets is
Associative
• (A B) C = A (B C)
• If A ⊆ B, then A B = A
• Since A ⊆ , so A = A
• A B ⊆ A and A B ⊆ B
• Difference of Sets
• If A B then A – B =
• Complement of a Set
• Please note
• ’ = and ’=
A A’ = and A A’ = ϕ
• A (B C) = (A B) (A C)
• A (B C) = (A B) (A C)
• De-Morgan’s Laws
• (A B)’ = A’ B’
A Set in Python is a collection of unique elements which are unordered and mutable.
Python provides various functions to work with Set. In this article, we will see a list of
all the functions provided by Python to deal with Sets.
Dictionary is an unordered collection
of elements. An element in
dictionary has a key: value pair.
All elements in dictionary are placed inside the curly braces i.e. { }
Elements in Dictionaries are accessed via keys and not by their position.
The values of a dictionary can be any data type.
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical
doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.
Dictionary is used
when data is being
constantly modified.
PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Difference between del and remove methods in List?
5. Difference between pop and remove in list?
6. How are the values in a tuple accessed?
7. What is a Dictionary in Python
8. Define list comprehension
9. Write a python program using list looping
10. Define Tuple and show it is immutable with an example.
11. state the difference between aliasing and cloning in list
12. what is list cloning
13. what is deep cloning
14. state the difference between pop and remove method in list
15. create tuple with single element
16. swap two numbers without using third variable
17. define properties of key in dictionary
18. how can you access elements from the dictionary
19. difference between delete and clear method in dictionary
20. What is squeezing in list? give an example
21. How to convert a tuple into list
22. How to convert a list into tuple
23. How can you return multiple values from function?
24. Find length of sequence without using library function.
25. how to pass tuple as argument
26. how to pass a list as argument
27. how can you insert values into dictionary
28. what is key value pair
29. mention different data types can be used in key and value
30. What is the use of from keys() in dictioanary.
PART-B
1. Explain in details about list methods
2. Discuss about operations in list
3. What is cloning? Explain it with example
4. What is aliasing? Explain with example
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples
7. write a program for matrix addition
8. write a program for matrix subtraction
9. Explain in detail about dictionaries and its methods.
10. Explain in detail about advanced list processing.
Sample Questions-Module 4
1. Difference between List and Dictionary in Python with example program for each.
2. Difference between List and Tuple in Python with example program for each.
3. Convert list of tuple into dictionary using iterative method with example program.
4. Which is better list or tuple in Python? Justify you answer with example program?
5. Difference Between ‘+’ and ‘append’ in Python with example.
6. How to Split Elements of a List? Explain the different methods.
7. Give any two ways to create a list in Python and reverse a list.
8. Explain the different list methods in Python for Python lists and give example program
for any five.
9. What is Immutable in Tuples? Justify your answer with example program.
10. Explain the append() and extend() in Python with suitable program for each.
11. Given a list of lists, write a Python program to extract the last element of each sublist in
the given list of lists.
12. List out the Different Operations Related to Tuples. Explain any five with example
program for each.
13. Explain the different tuple methods in Python for Python tuples and give example
program for each.
14. Advantages of tuple over list with example.
15. List out the Different Operations Related to sets. Explain with example program.
16. Explain the different set methods in Python for Python tuples and give example program
for each.
17. Create a dictionary and explain the properties of keys and values.
18. Explain any 5 ways to iterate through a dictionary with suitable example for each.
19. Write a python program to removing dictionary from list of dictionaries with output.
What are the built-in methods that you can use on dictionaries? Explain any five with
example program
Module 5
Module-5
Files: Text files, reading and writing files, format operator; command line arguments, modules,
packages
Object Oriented Programming: – creating python classes – Initializing objects, Objects and
classes -Abstraction – overview of inheritance and its type, polymorphism
Module 5
Mode Description
Module 5
Example:
# open a file in default mode (read and text)
file1 = open("test.txt") # equivalent to open("test.txt", "rt")
# open a file in write and text mode
file1 = open("test.txt",'w')
# open a file in read, write and binary mode
file1 = open("img.bmp",'+b')
Output:
This is a test file.
Hello from the test file.
In the above example, the code file1.read() reads the content of the file and stores
it in the read_content variable.
Delete a File
To delete a file, we must import the OS module, and run its os.remove() function:
Example:
import os
os.remove("demofile.txt")
print(read_content)
Here, with...open automatically closes the file, so we don't have to use the close()
function.
Method Description
Closes an opened
close()
file
Returns an integer
that represents the
tell()
current position of
the file's object
FORMAT OPERATOR
The argument of write has to be a string, so if we want to put other values in a
file, we have to convert them to strings. The easiest way to do that is with str:
>>> x = 52
Module 5
>>> fout.write(str(x))
'42'
The result is the string '42', which is not to be confused with the integer value
42.
A format sequence can appear anywhere in the string, so you can embed a value
in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels 'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has
to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-
point number and '%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') 'In 3 years I have
spotted 0.1 camels.'
Module 5
The number of elements in the tuple has to match the number of format sequences
in the string. Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
Using sys.argv
The sys module provides functions and variables used to manipulate different
parts of the Python runtime environment. This module provides access to some
variables used or maintained by the interpreter and to functions that interact
strongly with the interpreter. One such variable is sys.argv which is a simple list
structure. It’s main purpose are:
• It is a list of command line arguments.
• len(sys.argv) provides the number of command line arguments.
• sys.argv[0] is the name of the current Python script.
Example: Let’s suppose there is a Python script for adding two numbers and the
numbers are passed as command-line arguments.
Module 5
Output:
Module 5
where,
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options
that require an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that
require arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list
of (option, value) pairs. The second is the list of program arguments left
after the option list was stripped.
Example:
# Python program to demonstrate command line arguments
import getopt, sys
# Remove 1st argument from the
# list of command line arguments
argumentList = sys.argv[1:]
# Options
options = "hmo:"
# Long options
long_options = ["Help", "My_file", "Output="]
try:
# Parsing argument
arguments, values = getopt.getopt(argumentList, options, long_options)
Module 5
Output:
Using argparse module is a better option than the above two options as it
provides a lot of options such as positional arguments, default value for
arguments, help message, specifying data type of argument etc.
Note: As a default optional argument, it includes -h, along with its long version
–help.
Example 1:
# Python program to demonstrate
# command line arguments
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
MODULES
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named wc.py with the following code:
def linecount(filename):
count = 0
Module 5
PACKAGES
A package is a collection of modules. A Python package can have sub-
packages and modules.
A directory must contain a file named __init__.py in order for Python to
consider it as a package. This file can be left empty but we generally place the
initialization code for that package in this file.
Here is an example. Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the figure below.
For example, if want to import the start module in the above example, it is done
as follows. import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use
the full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package
prefix as follows.
from Game.Level import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form
a module within a package would be as follows.
from Game.Level.start import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace
avoids confusion and prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in
sys.path, similar as for module search path.
Example Code :
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
The class keyword defines the class named 'Dog'. The __init__ method is very
much like what constructors do in C++ and Java. They initialize the state of the
object.The self-parameter is used to reference the current instance of the class
and access its variables.
Module 5
INITIALIZING OBJECTS
An object is a particular instance of a class with unique characteristics and
functions. After a class has been established, you may make objects based on it.
By using the class constructor, you may create an object of a class in Python. The
object's attributes are initialised in the constructor, which is a special procedure
with the name __init__.
Syntax:
# Declare an object of a class
object_name = Class_Name(arguments)
Initializing Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)
person1.greet()
Output:
"Hello, my name is Ayan"
ABSTRACTION
Abstraction is one of the important principles of object-oriented programming. It
is the act of representing key features without including supporting information.
It is a method for developing a brand-new data type appropriate for a particular
application. It avoids providing extraneous or pointless facts and only displays
the precise portion the user has requested. It is crucial since it prevents you from
performing the same task more than once.It refers to a programming approach by
which only the relevant data about an object is exposed, hiding all the other
details. Objects only reveal internal mechanisms that are relevant for the use of
other objects, hiding any unnecessary implementation code. The derived class can
have its functionality extended.
This concept can help developers more easily make additional changes or
additions over time.This approach also helps in reducing the complexity and
increasing the efficiency of application development.
An abstract class can be considered a blueprint for other classes. It allows you to
create a set of methods that must be created within any child classes built from
the abstract class.
A class that contains one or more abstract methods is called an abstract class.
An abstract method is a method that has a declaration but does not have an
implementation.
An abstract class can be used for designing large functional units or to provide a
common interface for different implementations of a component.
Why use abstract classes?
When an abstract class is defined, you are basically defining a common API for
different sub-classes. This is especially useful when a third-party implements it.
For example, the plugins, which provides customization for each user based on
their need.
Another important use case of abstract classes is when you are working with a
larger team in the backend and remembering all the class names is next to
impossible.
"Abstract Method"
pass
#Sub class/ child class of abstract class
class SBI(Bank):
def interest(self):
"Implementation of abstract method"
print("In sbi bank 5 rupees interest")
s= SBI()
s.bank_info ()
s.interest()
OUTPUT :
Welcome to bank
In sbi bank 5 rupees interest
In the above example, Bank is an abstract class which having interest() abstract
method.
SBI class is a child class to Bank class, so SBI class should provide
implementation for abstract method which is available in Bank abstract class.
An object is created to subclass, which is SBI, and the implemented method
interest() is called.
Disadvantages Of Abstraction
1.Overhead Complexity: Although abstraction simplifies complexity at higher
levels, it can sometimes lead to a more complicated system at lower levels. This
is because the 'hidden' complexities don't disappear. They are merely
encapsulated.
2.Performance Trade-off: Abstraction often involves creating additional layers
over raw data or processes, inevitably leading to some degree of overhead. An
abstracted system may sometimes be less efficient regarding memory and
processing speed than a non-abstracted one.
3.Limited Customization: Since abstraction hides underlying details, it might
limit the possibility of making detailed level modifications or customisations,
which could be important in certain scenarios.
4.Loss of control: Higher levels of abstraction might result in loss of finer control.
The users of an abstraction might not perform certain operations due to the
restricted view offered to them.
OVERVIEW OF INHERITANCE
One of the core concepts in object-oriented programming (OOP) languages is
inheritance.
It is a mechanism that allows you to create a hierarchy of classes that share a set
of properties and methods by deriving a class from another class. Inheritance is
the capability of one class to derive or inherit the properties from another class.
Module 5
Classes can reuse code and properties from other classes. Relationships and
subclasses between objects can be assigned, enabling developers to reuse
common logic, while still maintaining a unique hierarchy. Inheritance forces
more thorough data analysis, reduces development time and ensures a higher
level of accuracy.
Inheritance enables to create new classes that inherit attributes and methods
from existing ones, promoting code reuse and extensibility.
TYPES OF INHERITANCE
1) Single Inheritance
It is the simplest form of inheritance and is often used when you want to model
an “is-a” relationship between two classes.
In this type, A class inherits from only one base class. This creates a linear
hierarchy, where each subclass inherits attributes and methods from a single
superclass.
Module 5
Example
# Base class
class Vehicle:
def start_engine(self):
print("Engine started")
# Derived class inheriting from Vehicle
class Car(Vehicle):
def drive(self):
print("Car is moving")
# Creating an instance of Car
my_car = Car()
# Accessing methods from the base class
my_car.start_engine()
# Output: "Engine started"
my_car.drive()
# Output: "Car is moving"
2)Multiple Inheritance
This allows a class to inherit attributes and methods from more than one base
class. Python supports this feature, enabling a class to inherit from multiple parent
classes.
It can be powerful but can also introduce complexity. It’s useful when you want
to combine features from different classes into a single class. Careful design is
essential to avoid conflicts or ambiguity when methods or attributes with the same
name are inherited from multiple parent classes.
Module 5
Example
# Base classes
class Human:
def eat(self):
print("Eating")
class AI:
def compute(self):
print("Processing data")
# Derived class inheriting from both Human and AI
class Robot(Human, AI):
def work(self):
print("Working efficiently")
# Creating an instance of Robot
my_robot = Robot()
# Accessing methods from both base classes
my_robot.eat()
# Output: "Eating"
my_robot.compute()
# Output: "Processing data"
my_robot.work()
# Output: "Working efficiently"
3)Multilevel Inheritance
It involves a chain of inheritance, where a class derives from a base class, and
then another class inherits from it. This forms a hierarchy or sequence of
inheritance.
Module 5
It allows you to create a structured hierarchy of classes, each building upon the
features of the previous one. It’s a way to achieve specialization while
maintaining a clear lineage of classes.
Example
# Base class
class Shape:
def area(self):
pass
# Intermediate class inheriting from Shape
class Polygon(Shape):
def sides(self):
pass
# Derived class inheriting from Polygon
class Rectangle(Polygon):
def calculate_area(self, length, width):
return length * width
# Creating an instance of Rectangle
my_rectangle = Rectangle()
# Accessing methods from the entire hierarchy
my_rectangle.area()
# Accesses Shape's area method
my_rectangle.sides()
# Accesses Polygon's sides method
4)Hybrid Inheritance
This is a combination of two or more types of inheritance within a single program
or class hierarchy. It often involves the use of multiple inheritance, where a class
Module 5
inherits from more than one base class, and then further extends this hierarchy
using single, multiple, or multilevel inheritance.
Example
# Base class for all animals
class Animal:
def __init__(self, name):
self.name = name
# Base class for land animals
class LandAnimal(Animal):
def walk(self):
print(f"{self.name} is walking")
# Base class for aquatic animals
class AquaticAnimal(Animal):
def swim(self):
print(f"{self.name} is swimming")
# Derived class for a specific animal, inheriting from both LandAnimal and
AquaticAnimal
class Platypus(LandAnimal, AquaticAnimal):
def __init__(self, name):
super().__init__(name)
# Creating an instance of Platypus
perry = Platypus("Perry the Platypus")
# Accessing methods from both LandAnimal and AquaticAnimal
perry.walk()
# Output: "Perry the Platypus is walking"
perry.swim()
# Output: "Perry the Platypus is swimming"
Module 5
5)Hierarchical Inheritance
Hierarchical inheritance is a type of inheritance where multiple derived classes
inherit from a single base class.
In this hierarchy, a single base class serves as a common ancestor for multiple
derived classes, allowing each derived class to share common attributes and
methods from the base class while adding their unique features.
Example
# Base class for all shapes
class Shape:
def __init__(self, name):
self.name = name
def area(self):
Pass
# Derived class for a specific shape (e.g., Circle)
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Derived class for another specific shape (e.g., Rectangle)
class Rectangle(Shape):
def __init__(self, name, length, width):
super().__init__(name)
self.length = length
self.width = width
Module 5
def area(self):
return self.length * self.width
# Derived class for yet another specific shape (e.g., Triangle)
class Triangle(Shape):
def __init__(self, name, base, height):
super().__init__(name)
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
POLYMORPHISM
Polymorphism is defined as the circumstance of occurring in several forms. It
refers to the usage of a single type entity (method, operator, or object) to represent
several types in various contexts. Polymorphism is made from 2 words – ‘poly‘
and ‘morphs.’ The word ‘poly’ means ‘many’ and ‘morphs’ means ‘many forms.’
Polymorphism, in a nutshell, means having multiple forms. To put it simply,
polymorphism allows us to do the same activity in a variety of ways.
In programming, polymorphism means the same function name (but different
signatures) being used for different types. The key difference is the data types and
number of arguments used in function. Polymorphism lets objects of diverse
types share the same interface, empowering methods to be executed unexpectedly
based on the object type. This decreases the code required and streamlines
upkeep.
Example 1:
# len() being used for a string
print(len("geeks"))
# len() being used for a list
print(len([10, 20, 30]))
#Output : 5 3
Example 2 :
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
Module 5
self.model = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
x.move()
OUTPUT :
Drive!
Sail!
Fly!
ADVANTAGES OF POLYMORPHISM
1.It helps programmers reuse the code and classes once written, tested and
implemented. They can be reused in many ways.
2.Single variable name can be used to store variables of multiple data types(Float,
double, Long, Int etc).
3.Polymorphism helps in reducing the coupling between different functionalities.
Module 5
DISADVANTAGES OF POLYMORPHISM
1.One of the disadvantages of polymorphism is that developers find it difficult to
implement polymorphism in codes.
2.Polymorphism reduces the readability of the program. One needs to identify the
runtime behavior of the program to identify actual execution time.
QUESTION BANK
1.Name two types of data files used in python.
2.What is the difference between write and append mode?
3.Illustrate which function is used to open a file. What is the default mode for
opening a file.
4.Illustrate how to read an entire text file.
5.Illustrate with code snippet how to read first n lines of a file.
6.Illustrate how to append text to a file and display the text.
7.Write a Python program to read a file line by line and store it into a list.
8. Illustrate with code how to find the longest words.
9.Write a Python program to count the number of lines in a text file.
10.Investigate the technique to count the frequency of words in a file.
11.Write a Python program to select a random element from a list, set,
dictionary-value, and file from a directory. Use random.choice() [Python
Module]
12.What is a python package? How to create package in python.
13.Interpret why python is considered as object oriented programming
language.
14.Elaborate on the concept of creating python classes.
15.Describe how the objects are initialised in python
16.Describe the concept of abstraction in python
17.Develop a program for formulating abstract classes in python.
18.Discuss the concept of inheritance in python.
Module 5
Sample Questions-Module 5
1. Explain the file reading operation with an example
2. Describe the processing of writing a character into a file using suitable example
3. Analyse the format operators in python
4. Discuss the details of command line arguments
5. Evaluate the use of modules and packages for efficient programming
6. Explain the governing principles of object-oriented programming
7. Illustrate with a python program to create a class and objects
8. Discuss the implementation of various types of inheritance using suitable examples
9. Write a python program to read line by line from a given files file1 & file2 and write
into file3.
10. Read a text file in Python and print no. of lines and no. of unique words.
11. Write a Python program to read a text file and do following:
1. Print no. of words
2. Print no. Statements
12. How operator overloading can be implemented in Python?
13. Write a Python program to overload + operator.
14. Explain built-in class attributes in a python class.
15. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.
16. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.
17. Create a class student with following member attributes: roll no, name, age and total
marks.
18. Create suitable methods for reading and printing member variables. Write a python
program to overload ‘==’ operator to print the details of students having same marks.
19. Write about class constructor(_init_()),self-variable
20. Compare method overloading and overriding