Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python ALL Modules Merged[1]

Uploaded by

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

Python ALL Modules Merged[1]

Uploaded by

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

Module 1

Introduction to Python

1. Python is a widely used general-purpose, high level programming


language. It was initially
2. designed by Guido van Rossum in 1991 and developed by Python
Software Foundation.
3. It was mainly developed for emphasis on code readability, and its
syntax allows programmers to express concepts in fewer lines of code.
4. Python is a programming language that lets you work quickly and
integrate systems more efficiently.

There are two major Python versions- Python 2 and Python 3.


• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and
includes new features.
Module 1

Differences between scripting language and programming language:

Why to use Python:


The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading
and
multiple inheritance.
2. Indentation
Module 1

Indentation is one of the greatest feature in python

3. It’s free (open source)


Downloading python and installing python is free and easy

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.

6. It’s easy to use and learn


No intermediate compile
Python Programs are compiled automatically to an intermediate form
called
byte code, which the interpreter then reads.
This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.

7. Interpreted Language
Python is processed at runtime by python Interpreter
Module 1

8. Interactive Programming Language


Users can interact with the python interpreter directly for writing the
programs

9. Straight forward syntax


The formation of python syntax is simple and straight forward which also
makes it
Popular

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.

The list of keywords are:


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from',
'global', 'if',
Module 1

'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

Output: Hello, World!


8. elif
Definition: Stands for "else if", used in conditional statements to check
multiple expressions for True.
Example:
x = 10
if x > 15:
print("Greater than 15")
elif x > 5:
print("Greater than 5 but not 15")
else:
print("5 or less")
Output: Greater than 5 but not 15
9. else
Definition: Used in conditional statements and loops to define a block of
code that runs if no conditions are true.
Example:
x=3
if x > 5:
print("Greater than 5")
else:
print("5 or less")
Output: 5 or less
10. except
Definition: Used in error handling to catch exceptions.
Example:
try:
print(10 / 0)
except ZeroDivisionError:
Module 1

print("You can't divide by zero!")


Output: You can't divide by zero!
11. finally
Definition: Used with try...except blocks to execute code regardless of
whether an exception is thrown.
Example:
try:
print(10 / 0)
except ZeroDivisionError:
print("Division by zero")
finally:
print("This runs no matter what")
Output:
csharp
Division by zero
This runs no matter what
12. for
Definition: Used to iterate over a sequence (like a list, tuple, dictionary,
or string).
Example:
for i in range(3):
print(i)
Output:
0
1
2
13. from
Definition: Used to import specific parts of a module.
Example:
Module 1

from math import pi


print(pi)
Output: 3.141592653589793
14. global
Definition: Used to declare a variable as global inside a function.
Example:
x=5
def update():
global x
x = 10
update()
print(x)
Output: 10
15. if
Definition: Used for conditional execution.
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output: x is greater than 5
16. import
Definition: Used to import a module into your Python script.
Example:
import math
print(math.sqrt(16))
Output: 4.0
17. in
Definition: Used to check if a value is present in a sequence (like a list,
string, or tuple).
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

# Python program using various Python keywords

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

# Using keywords in conditions and loops


if __name__ == "__main__":
number = Number(10)
is_positive = check_number(number.value)

if is_positive is True:
print("The number is positive.")
Module 1

elif is_positive is None:


print("The number is zero.")
else:
print("The number is negative.")

# Demonstrating loops and conditional statements


for i in range(5):
while i < 3:
print(f"Current value: {i}")
break
else:
continue

# Using with statement


with open("sample.txt", "w") as file:
file.write("This is an example of using Python keywords.")

# Example of lambda and list comprehension


square = lambda x: x**2
numbers = [square(x) for x in range(5)]
print(f"Squares: {numbers}")

# Example of try, except, finally


try:
result = number.value / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")
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

Rules for Naming an Identifier


4. Identifiers cannot be a keyword.
5. Identifiers are case-sensitive.
6. It can have a sequence of letters and digits. However, it must begin
with a letter or The first letter of an identifier cannot be a digit.
7. It's a convention to start an identifier with a letter rather _.
8. Whitespaces are not allowed.
9. We cannot use special symbols like !, @, #, $, and so on.

1. Python is a case-sensitive language. This means, Variable and variable


are not the same.
2. Always give the identifiers a name that makes sense. While c = 10 is a
valid name, writing count = 10 would make more sense, and it would be
easier to figure out what it represents when you look at your code after a
long gap.
3. Multiple words can be separated using an underscore, like
this_is_a_long_variable.
Module 1

In Python, identifiers are names used to identify variables, functions,


classes, modules, and other objects. Here are the key points to understand
about Python identifiers:

Rules for Naming Identifiers:


Alphabetic Characters and Digits:
An identifier can be a combination of uppercase (A-Z) or lowercase (a-z)
letters, digits (0-9), and underscores (_).
Example: myVariable, age_2, _count.
Starting Character:
An identifier must start with a letter (A-Z or a-z) or an underscore (_).
It cannot start with a digit.
Example: variable1, _result.
Case Sensitivity:
Identifiers are case-sensitive in Python. For example, Data, data, and
DATA are three different identifiers.

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.

Rules for Naming Variables:


1. Variable names must start with a letter (a-z, A-Z) or an underscore (_).
2. The rest of the variable name can contain letters, numbers (0-9), and
underscores.
3. Variable names are case-sensitive (age and Age are different).
Module 1

4. Python keywords cannot be used as variable names.

Example of Variables in Python:


# Assigning values to variables
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.8 # Float variable
is_student = True # Boolean variable

# Printing variable values


print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is a student:", is_student)

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

Type Conversion: Python supports type conversion using built-in


functions like int(), float(), str(), etc.
Dynamic Typing: Variables can change types during execution.
Immutability: Types like strings, tuples, and frozensets are immutable,
meaning their contents cannot be changed after creation.
1. Easy to use and learn
Python has a simple syntax that is easy to learn. It makes it an ideal
programming language for beginners. The language structure is
straightforward. And the code is easy to read and understand.
Additionally, Python's readability is enhanced by the use of white space
and indentation. Python is a popular language for scripting and rapid
application development.

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

4. Large Standard Library


Python comes with a comprehensive standard library. It includes modules
for performing a wide range of tasks. This library contains modules for
web development, database interaction, file manipulation, data analysis,
and scientific computing. The large standard library of Python saves
developers time and effort. They do not have to write code from scratch
and can use pre-existing modules.

5. Object-Oriented Programming Language


Python is a powerful object-oriented programming language that supports
OOPs concepts like inheritance, polymorphism, and encapsulation. It
allows users to create reusable and modular code, making it easier to
manage large codebases. Examples: NumPy, matplotlib, Django, and
Panda.

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.

7. Large Community Support


Python is a large and active community of developers, which means it has
extensive documentation and tutorials. It also provides support through
social media platforms, mailing lists, and online forums to make it easy
for developers to get help and cooperate with others.
Module 1

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.

11. High-Level Language


Python is a high-level language, meaning the code is closer to human
language than machine language. This makes it easier to read and
understand. The developers can write less complex code. The high-level
nature of Python also allows developers to write code more quickly.

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

13. Third-Party Libraries


Python has a great and active community that has developed many third-
party libraries for various tasks. These libraries include tools for scientific
computing, web development, machine learning, and data manipulation.
The availability of third-party libraries has made Python a popular
language.

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.

OPERATORS AND EXPRESSION:

In Python, assignment statements are used to assign values to variables.


The assignment operator (=) is the most basic way to bind a value to a
variable. Python also supports various types of assignment operators that
allow for more complex expressions.

1. Basic Assignment Operator (=)


The = operator assigns the value on the right to the variable on the left.
Example:

x = 10 # Assigns 10 to the variable x


name = "Alice" # Assigns the string "Alice" to the variable name
Module 1

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

Augmented Assignment Operators


Python provides a shorthand for applying an operation and assigning the
result back to the variable. These are known as augmented assignment
operators.
Examples:
Addition Assignment (+=):
x=5
x += 3 # Equivalent to x = x + 3; x is now 8
Subtraction Assignment (-=):
y = 10
y -= 2 # Equivalent to y = y - 2; y is now 8
Multiplication Assignment (*=):
z=4
z *= 5 # Equivalent to z = z * 5; z is now 20
Division Assignment (/=):
a = 15
a /= 3 # Equivalent to a = a / 3; a is now 5.0
Modulus Assignment (%=)
Module 1

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

simple or complex, depending on the combination of operators and


operands used.
1. Arithmetic Operators
Python supports the following basic arithmetic operators:
Addition (+): Adds two numbers.
Example: x + y
Subtraction (-): Subtracts the second number from the first.
Example: x - y
Multiplication (*): Multiplies two numbers.
Example: x * y
Division (/): Divides the first number by the second (result is always a
float).
Example: x / y
Floor Division (//): Divides the first number by the second and returns
the largest integer less than or equal to the quotient.
Example: x // y
Modulus (%): Returns the remainder of the division.
Example: x % y
Exponentiation (**): Raises the first number to the power of the second.
Example: x ** y
2. Order of Operations (PEMDAS/BODMAS)
Python follows the standard mathematical order of operations, often
remembered by the acronym PEMDAS (Parentheses, Exponents,
Multiplication and Division (left-to-right), Addition and Subtraction (left-
to-right)).

result = 2 + 3 * 4 # 3 * 4 is evaluated first, then 2 + 12, resulting in 14


result = (2 + 3) * 4 # Parentheses change the order: 5 * 4, resulting in 20
Modulus (%): Returns the remainder of the division.
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.

AND (&): Performs a binary AND operation


5 & 3 # 1 (binary: 0101 & 0011 -> 0001)

OR (|): Performs a binary OR operation.


Module 1

5 | 3 # 7 (binary: 0101 | 0011 -> 0111)

XOR (^): Performs a binary XOR operation.


5 ^ 3 # 6 (binary: 0101 ^ 0011 -> 0110)
Left Shift (<<): Shifts the bits to the left.
2 << 1 # 4 (binary: 0010 << 1 -> 0100)

Order of Evaluation in Python


The order of evaluation in Python refers to the sequence in which
expressions are evaluated and executed in a Python program.
Understanding this order is essential for correctly predicting the outcome
of complex expressions.

Precedence and Associativity


Python follows specific rules for evaluating expressions that involve
multiple operators:

Precedence: Determines the order in which operations are performed in


an expression with multiple operators. Operators with higher precedence
are evaluated before those with lower precedence.

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

Example: 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2).

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.

There are two types of type conversion in Python.

Implicit Conversion - automatic type conversion


Explicit Conversion - manual type conversion
Module 1

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to
another. This is known as implicit type conversion.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower
data type (integer) to the higher data type (float) to avoid data loss.

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))
Output
Value: 124.23
Data Type: <class 'float'>
In the above example, we have created two variables: integer_number
and float_number of int and float type respectively.

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.

It is because Python always converts smaller data types to larger data


types to avoid the loss of data.
Module 1

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.

Example 2: Addition of string and integer Using Explicit Conversion


num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string


Module 1

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.

After converting num_string to an integer value, Python is able to add


these two variables.

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

Type Conversion in Python


Type conversion in Python refers to converting one data type to another.
Python provides two types of type conversions:
Implicit Type Conversion
Explicit Type Conversion (Type Casting)
1. Implicit Type Conversion
In implicit type conversion, Python automatically converts one data type
to another without any user intervention. This usually happens when
performing operations between two different types, where one type is
smaller or less complex than the other.

Example:
x = 10 # integer
y = 3.5 # float

result = x + y

print(result) # Output: 13.5 (float)


print(type(result)) # Output: <class 'float'>
Here, the integer x is automatically converted to a float when added to y,
and the result is a float.

2. Explicit Type Conversion (Type Casting)


Explicit type conversion, or type casting, is when the user manually
converts one data type to another using Python's built-in functions.

Common Type Casting Functions:

int() – Converts a value to an integer.


Module 1

float() – Converts a value to a float.


str() – Converts a value to a string.
bool() – Converts a value to a boolean.
list() – Converts a value to a list.
tuple() – Converts a value to a tuple.
dict() – Converts a value to a dictionary.
set() – Converts a value to a set.
Examples:

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:

Loss of Data: Some conversions might lead to a loss of data, especially


when converting from a float to an integer, where the fractional part is
truncated.
Compatibility: Not all types can be converted into each other. For
example, trying to convert a string that doesn't represent a number (like
"abc") to an integer using int("abc") will raise a ValueError.
Summary
Implicit Conversion: Done automatically by Python, usually when
mixing different types.
Explicit Conversion: Requires the use of built-in functions to convert
data types manually.

INPUT OUTPUT STATEMENTS


Python provides several ways to handle input and output operations.
These operations are fundamental to interacting with the user, reading
data, and displaying results.
Module 1

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

sep: String inserted between values, default is a space.


end: String appended after the last value, default is a newline.
file: The output stream to which the values are printed, default is
sys.stdout.
flush: Whether to forcibly flush the stream.
Examples:

Basic Output:
print("Hello, World!")
This prints the string Hello, World!.

Printing Multiple Values:


name = "Alice"
age = 25
print(name, "is", age, "years old.")
This prints Alice is 25 years old. with spaces automatically inserted
between the arguments.

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.

Printing Without a Newline:


for i in range(5):
Module 1

print(i, end=" ")


This prints 0 1 2 3 4 on the same line.

3. Formatted Output
Python allows for formatted strings using the format() method or f-strings
(formatted string literals).

Using format() Method:


name = "Bob"
age = 30
print("{} is {} years old.".format(name, age))
This prints Bob is 30 years old..

Using f-strings:
name = "Bob"
age = 30
print(f"{name} is {age} years old.")
This also prints Bob is 30 years old..

4. Handling Input and Output Together


You can combine input and output to create interactive programs:
name = input("What is your name? ")
print(f"Hello, {name}!")
age = int(input("How old are you? "))
print(f"You will be {age + 1} next year.")
This program asks for the user's name and age, then greets them and tells
them how old they will be next year.
Module 1

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

Using Multiple Single-Line Comments:

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

1. Define Python. List the salient features of python.


2. Define Flowchart. Draw the Flowchart to check whether the input number is odd
or even.
3. Explain Membership and Identity operators in Python
4. Write a python program to find roots of a quadratic equation ax2+bx+c . Use
input() to enter a, b and c and print root1 and root2
5. Define an Algorithm. Write an algorithm to find the greatest number among the
given two numbers
6. Explain the operator precedence and order of evaluation for arithmetic operators
in Python
7. Write a Python program to find GCD and LCM of two given numbers.
8. Write a python program to find the factorial of a number
9. Computes the expressions 1. 3+(4-(11//5))**2%2 2. (1+2)**(5-2) 3. 3*2**2.
Define PEDMAS.
10. Explain the rules to define a variable in python. Give examples for assigning
multiple values to multiple variables.
11. Define Keyword. Explain any six keywords in python.
12. Explain type casting and its usage with an example
13. Classify the different operators in Python with an example.
Module 2

MODULE-2
Module 2

SYLLABUS : Loops, controls statements And functions

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

LOOPS And Control Statements :

Control Flow Statements


The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Module 2

Python control flow statements


Conditional statements
In Python, condition statements act depending on whether a given
condition is true or false. You can execute different blocks of codes
depending on the outcome of a condition. Condition statements
always evaluate to either True or False.
There are three types of conditional statements.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else

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

Syntax of the if statement


if condition:
statement 1
statement 2
statement n
+

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.

Python if-else statements


Example
password = input('Enter password ')

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

Nested if-else statement


In Python, the nested if-else statement is an if statement inside
another if-else statement. It is allowed in Python to put any number
of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The
nested if-else is useful when we want to make a series of decisions.
Syntax of the nested-if-else:
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
Module 2

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

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)
Output 1:
Enter first number 56
Enter second number 15
56 is greater than 15
Module 2

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

While Loop in Python


While loops execute a set of lines of code iteratively till a condition is
satisfied. Once the condition results in False, it stops execution, and the part
of the program after the loop starts executing.

The syntax of the while loop is :


while condition:
statement(s)
Module 2

Example of Python while loop:


i=1
while (i<=5):
print(i)
i=i+1
Here the condition checked is ‘i<=5’. For the first iteration, i=1 and is less
than 5. So, the condition is True and 1 is printed. Then the ‘i’ value is
incremented to print the next number and the condition is checked. When
the value of ‘i’ becomes 6, the condition will be False and the execution of
the loop stops.
The while Loop
Let’s see how Python’s while statement is used to construct loops. We’ll start
simple and embellish as we go.
The format of a rudimentary while loop is shown below:
Python
while <expr>:
<statement(s)>
<statement(s)> represents the block to be repeatedly executed, often
referred to as the body of the loop. This is denoted with indentation, just as
in an if statement.
All control structures in Python use indentation to define blocks.
Module 2

The controlling expression, <expr>, typically involves one or more variables


that are initialized prior to starting the loop and then modified somewhere in
the loop body.
When a while loop is encountered, <expr> is first evaluated in Boolean
context. If it is true, the loop body is executed. Then <expr> is checked again,
and if still true, the body is executed again. This continues
until <expr> becomes false, at which point program execution proceeds to
the first statement beyond the loop body.
Consider this loop:
Python
1>>> n = 5
2>>> while n > 0:
3... n -= 1
4... print(n)
Here’s what’s happening in this example:
 n is initially 5. The expression in the while statement header on line 2
is n > 0, which is true, so the loop body executes. Inside the loop body
on line 3, n is decremented by 1 to 4, and then printed.
 When the body of the loop has finished, program execution returns to
the top of the loop at line 2, and the expression is evaluated again. It is
still true, so the body executes again, and 3 is printed.
 This continues until n becomes 0. At that point, when the expression is
tested, it is false, and the loop terminates. Execution would resume at
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.

The Python break and continue Statements


In each example you have seen so far, the entire body of the while loop is
executed on each iteration. Python provides two keywords that terminate a
loop iteration prematurely:
 The Python break statement immediately terminates a loop entirely.
Program execution proceeds to the first statement following the loop
body.
 The Python continue statement immediately terminates the current
loop iteration. Execution jumps to the top of the loop, and the
controlling expression is re-evaluated to determine whether the loop
will execute again or terminate.
The distinction between break and continue is demonstrated in the following
diagram:
Module 2

Break and continue :


Here’s a script file called break.py that demonstrates the break statement:
Python
n=5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
Module 2

Running break.py from a command-line interpreter produces the following


output:
Windows Command Prompt
C:\Users\john\Documents>python break.py
Loop ended.

When n becomes 2, the break statement is executed. The loop is terminated


completely, and program execution jumps to the print() statement on line 7.
Note: If your programming background is in C, C++, Java, or JavaScript, then
you may be wondering where Python’s do-while loop is. Well, the bad news
is that Python doesn’t have a do-while construct. But the good news is that
you can use a while loop with a break statement to emulate it.
The next script, continue.py, is identical except for a continue statement in
place of the break:
Python
n=5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('Loop ended.')
The output of continue.py looks like this:
Module 2

Windows Command Prompt


C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.
This time, when n is 2, the continue statement causes termination of that
iteration. Thus, 2 isn’t printed. Execution returns to the top of the loop, the
condition is re-evaluated, and it is still true. The loop resumes, terminating
when n becomes 0, as previously.
Pass statement in Python
The pass is the keyword In Python, which won’t do anything. Sometimes
there is a situation in programming where we need to define a syntactically
empty block. We can define that block with the pass keyword.
A pass statement is a Python null statement. When the interpreter finds a
pass statement in the program, it returns no operation. Nothing happens
when the pass statement is executed.
It is useful in a situation where we are implementing new methods or also in
exception handling. It plays a role like a placeholder.
Example
months = ['January', 'June', 'March', 'April']
for mon in months:
Module 2

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

Python For loop :


In Python, the for loop is used to iterate over a sequence such as a list,
string, tuple, other iterable objects such as range.
With the help of for loop, we can iterate over each item present in the
sequence and executes the same set of operations for each item. Using
a for loops in Python we can automate and repeat tasks in an efficient
manner.
So the bottom line is using the for loop we can repeat the block of
statements a fixed number of times. Let’s understand this with an example.
As opposed to while loops that execute until a condition is true, for loops are
executed a fixed number of times, you need to know how many times to
repeat the code.
 An unknown number of times: For example, Ask the user to guess the
lucky number. You don’t know how many attempts the user will need to
guess correctly. It can be 1, 20, or maybe indefinite. In such cases, use
a while loop.
 Fixed number of times: Print the multiplication table of 2. In this case,
you know how many iterations you need. Here you need 10 iterations.
In such a case use for loop.
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.

Syntax of for loop


for i in range/sequencee:
statement 1
statement 2
statement n
Module 2

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

# Example: Iterating over a list


numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

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:

Create a Python Function


Here, we have created a simple function named greet() that prints Hello
World!
Note: When writing a function, pay attention to indentation, which are the
spaces at the start of a code line.
In the above code, the print() statement is indented to show it's part of the
function body, distinguishing the function's definition from its body.
Module 2

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

Example: Python Function Call


def greet():
print('Hello World!')

# call the function


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:

Working of Python Function


Here,
1. When the function greet() is called, the program's control transfers to
the function definition.
2. All the code inside the function is executed.
3. The control of the program jumps to the next statement after the
function call
Create a Function
Let's create our first function.
def greet():
print('Hello World!')
Here are the different parts of the program:
Module 2

Create a Python Function


Here, we have created a simple function named greet() that prints Hello
World!
Note: When writing a function, pay attention to indentation, which are the
spaces at the start of a code line.
In the above code, the print() statement is indented to show it's part of the
function body, distinguishing the function's definition from its body.

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

To use this function, we need to call the function.


Function Call
greet()

Example: Python Function Call


def greet():
print('Hello World!')

# call the function


greet()

print('Outside function')

Python Function Arguments


Arguments are inputs given to the function.
def greet(name):
print("Hello", name)

# 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

Example: Function to Add Two Numbers


# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)

# function call with two values


add_numbers(5, 4)
Output
Sum: 9
Module 2

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:

Working of Python Function


Here,
1. When the function greet() is called, the program's control transfers to
the function definition.
2. All the code inside the function is executed.
3. The control of the program jumps to the next statement after the
function call.
In the above example, we have created a function
named add_numbers() with arguments: num1 and num2.
Module 2

Python Function with Arguments

Parameters and Arguments

The return Statement


We return a value from the function using the return statement.
# function definition
def find_square(num):
result = num * num
return result

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

Working of functions in Python

The pass Statement


Module 2

The pass statement serves as a placeholder for future code, preventing


errors from empty code blocks.
It's typically used where code is planned but has yet to be written.
def future_function():
pass

# this will execute without any action or error


future_function()

Python Library Functions


Python provides some built-in functions that can be directly used in our
program.
We don't need to create the function, we just need to call them.
Some Python library functions are:
1. print() - prints the string inside the quotation marks
2. sqrt() - returns the square root of a number
3. pow() - returns the power of a number
These library functions are defined inside the module. And to use them,
we must include the module inside our program.
For example, sqrt() is defined inside the math module.

Example: Python Library Function


Module 2

import math

# sqrt computes the square root


square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power


power = pow(2, 3)

print("2 to the power 3 is",power)


Output
Square Root of 4 is 2.0
2 to the power 3 is 8
Here, we imported a math module to use the library
functions sqrt() and pow().
Module 2

Function with return statement :


How to Create a Function that Returns Multiple Values in Python
In our earlier example, the function volume_of_cuboid() returned only one
value, namely, the volume of a cuboid given its dimensions. Let's see how we
can return multiple values from a function.
 To return multiple values from a function, just specify the values to be
returned, separated by a comma.
 By default, the function returns the values as a tuple. If there
are N return values, we get an N-tuple.
Let's create a simple function cube() that returns the volume and total
surface area of a cube, given the length of its side.
def cube(side):
volume = side **3
surface_area = 6 * (side**2)
return volume, surface_area
To verify that a tuple is returned, let's collect it in a variable returned_values,
as shown below:
returned_values = cube(8)
print(returned_values)

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

my_list = ['Geeks', 'for']


Module 2

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 in Python


Python has several functions available for you to use directly from anywhere
in your code. These functions are known as built-in functions and they cover
many common programming problems, from mathematical computations to
Python-specific features.
Note: Many of Python’s built-in functions are classes with function-style
names. Good examples are str, tuple, list, and dict, which are classes that
define built-in data types.
Module 2

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

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

ascii() Returns a readable version of an object. Replaces none-ascii ch


escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes


Module 2

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is di

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate

eval() Evaluates and executes an expression

exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number


Module 2

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or metho

globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified o

issubclass() Returns True if a specified class is a subclass of a specified obje

iter() Returns an iterator object

len() Returns the length of an object


Module 2

list() Returns a list

locals() Returns an updated dictionary of the current local symbol tabl

map() Returns the specified iterator with the specified function applie

max() Returns the largest item in an iterable

memoryview() Returns a memory view object

min() Returns the smallest item in an iterable

next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of the specified c

pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increment


Module 2

repr() Returns a readable version of an object

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list

staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

super() Returns an object that represents the parent class

tuple() Returns a tuple

type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators


Module 2

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

# to give it a name, assign it to a variable:


function_name = lambda arguments: expression

# this is equivalent to:


Module 2

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

# Lambda function to find the average of three numbers


average = lambda x, y, z: (x + y + z) / 3
Although lambda functions can only contain one expression, we can still do a
lot with them.
For example, here's a Lambda function to concatenate 2 strings and convert
them to uppercase:
concat_and_uppercase = lambda str1, str2: (f'The concatenated string is {str1
+ str2}'.upper())
Module 2

print(concat_and_uppercase("hello", "world")) # Output: THE


CONCATENATED STRING IS HELLOWORLD
Ways to Call Lambda Functions
There are primarily three ways to use or call lambda functions:
1. Assigning to a Variable
Assign the lambda function to a variable and then call it using that variable:
multiply = lambda x, y: print(f'{x} * {y} = {x * y}')
multiply(2, 10) # Output: 2 * 10 = 20
or
multiply = lambda x, y: f'{x} * {y} = {x * y}'
print(multiply(2, 10)) # Output: 2 * 10 = 20

2. Directly Calling the Lambda Function


Define and immediately invoke the lambda function by wrapping the
definition in parentheses and providing the arguments directly:
print((lambda x, y: f'{x} * {y} = {x * y}')(2, 10)) # Output: 2 * 10 = 20
or
(lambda x, y: print(f'{x} * {y} = {x * y}'))(2, 10) # Output: 2 * 10 = 20
3. Using as an Argument to Higher-Order Functions
Lambda functions are often used as arguments to higher-order functions
like map, filter, and reduce.
Module 2

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

Using lambda functions with filter()


The filter function filters elements in an iterable based on a specified
predicate. Only elements for which the predicate returns True are included in
the new iterable.
# syntax

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

from functools import reduce


reduce(function, iterable)
Here, Function takes two arguments and returns a single value. Iterable
elements will be processed by the function.
Example:
from functools import reduce

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Using reduce with lambda to sum the numbers


sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers)
Module 2

# 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].

Additional Use Cases


Lambda functions can also be used in sorting or other functional
programming contexts. For example:
Sorting a List of Strings:
cities = ["India", "Germany", "America", "Japan"]
sorted_cities = sorted(cities, key=lambda city: city.lower())
Module 2

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]

# Using lambda in list comprehension to square each number


squared_numbers = [(lambda x: x ** 2)(x) for x in numbers]
Module 2

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

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(), Filter(), Reduce Function :

Map, Filter, and Reduce are paradigms of functional programming. They


allow the programmer (you) to write simpler, shorter code, without
neccessarily needing to bother about intricacies like loops and branching.
Essentially, these three functions allow you to apply a function across a
number of iterables, in one fell swoop. map and filter come built-in with
Python (in the __builtins__ module) and require no importing. reduce,
however, needs to be imported as it resides in the functools module. Let's
get a better understanding of how they all work, starting with map.
Module 2

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

for pet in my_pets:


pet_ = pet.upper()
uppered_pets.append(pet_)

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

The following is a list (iterable) of the scores of 10 students in a Chemistry


exam. Let's filter out those who passed with scores more than
75...using filter.
Example :
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]

def is_A_student(score):
return score > 75

over_75 = list(filter(is_A_student, scores))


print(over_75)

output : [ 90,76, 88, 81]

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

numbers = [3, 4, 6, 9, 34, 12]

def custom_sum(first, second):


return first + second

result = reduce(custom_sum, numbers)


print(result)

The result, as you'll expect is 68.


Module 2

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.

In Python, we know that a function can call other functions. It is even


possible for the function to call itself. These types of construct are termed as
recursive functions.
The following image shows the working of a recursive function
called recurse.

Following is an example of a recursive function to find the factorial of an


integer.
Module 2

Factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.


Example of a recursive function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

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.

factorial(3) # 1st call with 3


3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
Let's look at an image that shows a step-by-step process of what is going on:
Module 2

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

Advantages of Recursive function :


1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.

Disadvantages of Recursive function :


1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
3. Recursive functions are hard to debug.
Module 2

Sample Questions -Module 2


1.Explain the different types of control statements in Python with examples.
2. Write a Python program to check if a number is prime or not using control
statements. Explain the control flow of the program.
3. Discuss the differences between break, continue, and pass statements in
Python with code examples.
4.Describe the structure of a while loop in Python and compare it with a for
loop. Provide examples where each loop is more appropriate.
5. Write a Python program to print the Fibonacci series using a loop and
control statements. Explain the control flow of the program in detail.
6. How do nested loops work in Python? Write a program to print a pattern
using nested loops and explain how control moves through each iteration.
7. Explain the concept of else with loops in Python. How does it differ from
else with if statements? Provide examples for both cases.
8. What are conditional expressions (ternary operators) in Python? How are
they different from traditional if-else statements? Provide examples.
9. Explain the difference between for and while loops in Python with
examples.
10. Write a Python program to find the factorial of a number using a loop.
Explain the control flow of the program.
11. What are nested loops in Python? Write a program to display a
multiplication table for numbers from 1 to 10 using nested loops, and explain
the execution flow.
Module 2

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

21. Discuss the concept of function arguments in Python. Explain with


examples the different types of function arguments: default arguments,
keyword arguments, and variable-length arguments.
22. What are lambda functions in Python? Write a Python program using a
lambda function to filter even numbers from a list. Explain the advantages
and limitations of lambda functions.
23. Describe the concept of recursion with respect to functions in Python.
Write a Python function that computes the factorial of a number using
recursion and explain the flow of recursive calls.
24. Explain the difference between positional arguments and keyword
arguments in Python functions. Write a program to demonstrate both with
an example.
25. Write a Python program to demonstrate the use of map(), filter(), and
reduce() functions with appropriate examples. Explain how each function
operates on iterable data.
26. How does Python handle function scope? Write a program to explain the
concepts of local and global variables in functions.
27. Explain how *args and **kwargs are used in Python functions. Write a
program to demonstrate the use of both and explain their utility.
28. Write a Python program to calculate the sum of a list of numbers using a
function. Explain how the function is defined, how it is called, and how the
return statement is used.
29. Discuss the similarities and differences between map(), filter(), and
reduce() functions in Python. Provide examples for each.
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: Creating String in Python, Strings indexing and splitting,


Reassigning Strings, Deleting the String, String Operators, Python string
functions, slice operations.
Assertion and Exception Handling: Assertion usage in Python, Exception
handling, try, except, raise finally.
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.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

OUTPUT:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Module 3

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts from 0. For example, the
string "HELLO" is indexed as given in the below figure.

Consider the following example :

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

Consider the following example :

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

Consider the following example

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

Deleting the String


As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.

Example :

1. str = "JAVATPOINT"
2. del str[1]

OUTPUT :

TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

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 slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified
range.

in It is known as membership operator. It returns if a particular sub-string is present in the


specified string.

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

Python String functions


Python provides various in-built functions that are used for string handling. Many String
fun

Method Description

capitalize() It capitalizes the first character of the String. This function is


deprecated in python3

casefold() It returns a version of s suitable for case-less comparisons.

center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.

count(string,begin,end) It counts the number of occurrences of a substring in a String


between begin and end index.

decode(encoding = 'UTF8', errors = Decodes the string using codec registered for encoding.
'strict')

encode() Encode S using the codec registered for encoding. Default


encoding is 'utf-8'.
Module 3

endswith(suffix It returns a Boolean value if the string terminates with given


,begin=0,end=len(string)) suffix between begin and end.

expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space


value is 8.

find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.

format(value) It returns a formatted version of S, using the passed value.

index(subsring, beginIndex, It throws an exception if string is not found. It works same as


endIndex) find() method.

isalnum() It returns true if the characters in the string are alphanumeric


i.e., alphabets or numbers and there is at least 1 character.
Otherwise, it returns false.

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.

isidentifier() It returns true if the string is the valid identifier.

islower() It returns true if the characters of a string are in lower case,


otherwise false.

isnumeric() It returns true if the string contains only numeric characters.

isprintable() It returns true if all the characters of s are printable or s is empty,


false otherwise.
Module 3

isupper() It returns false if characters of a string are in Upper case,


otherwise False.

isspace() It returns true if the characters of a string are white-space,


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.

join(seq) It merges the strings representation of the given sequence.

len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.

lower() It converts all the characters of a string to Lower case.

lstrip() It removes all leading whitespaces of a string and can also be


used to remove particular character from leading.

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.

maketrans() It returns a translation table to be used in translate function.

replace(old,new[,count]) It replaces the old sequence of characters with the new


sequence. The max characters are replaced if max is given.
Module 3

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward


direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward


direction.

rjust(width,[,fillchar]) Returns a space padded string having original string right


justified to the number of characters specified.

rstrip() It removes all trailing whitespace of a string and can also be


used to remove particular character from trailing.

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.

strip([chars]) It is used to perform lstrip() and rstrip() on the string.

swapcase() It inverts case of all characters in a string.

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

upper() It converts all the characters of a string to Upper Case.

zfill(width) Returns original string leftpadded with zeros to a total of width


characters; intended for numbers, zfill() retains any sign given
(less one zero).

rpartition()

Assertion and Exception Handling:

Assertions in Python are statements that assert or assume a condition to be


true. If the condition turns out to be false, Python raises
an AssertionError exception. They are used to detect programming errors that
should never occur if the code is correct.
Module 3

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.

3. Explain the string operations of concatenation and repetition with an example

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

6. Explain Deleting/Updating in a string with an example

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.

9. Explain the string slicing and splitting along with examples.

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.

12. Classify the index and Find function with an example.

13. Explain the difference between single string and multiline string with an example

14. Examine the reassigning of 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 SET, DICTIONARY AND TUPLE

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

adding dictionary values, Iterating Dictionary, Built in Dictionary functions


Lists
 
List is an ordered sequence of items. Values in the list are called elements / items.

It can be written
 as a list of comma-separated items (values) between square
brackets[ ].

Items in the lists can be of different data types.


Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison

operations examples description


create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>b=[20,30] Adding and printing the


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.

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

slices example description

a[2:2] >>> a[2:2] print an empty slice


[]
a[0:6:2] >>> a=[9,8,7,6,5,4] Slicing list values with step
>>> a[0:6:2] size 2.(from index[0] to 2nd
[9, 7, 5] element and from that
>>> a[0:6:3] position to next 2nd element
[9,6]

List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)

syntax example description


1 >>> a=[1,2,3,4,5]
>>> a.append(6) Add an element to
a.append(element) >>> print(a) the end of the list
[1, 2, 3, 4, 5, 6]
2 a.insert(index,element) >>> a.insert(0,0) Insert an item at the
>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]
3 a.extend(b) >>> a=[1,2,3,4,5]
>>> b=[7,8,9]
>>> a.extend(b) Add all elements of a
>>> print(a) list to the another
[0, 1, 2, 3, 4, 5, 6, 7, 8,9] list
4 >>>a=[0, 1, 2, 3, 8,5, 6, 7, 8,9] Returns the index of
a.index(element) >>> a.index(8) the first matched
4 item
5 >>> a=[1,2,3,4,5]
>>> sum(a) Sort items in a list in
sum()
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
6 >>> a.reverse()
Reverse the order of
a.reverse() >>> print(a)
items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]

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

Accessing element output


a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop

The while loop in Python is usedto iterate over a block of code as long as the test
expression (condition) is true.

When the condition is tested and the result is false, the
 loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

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

clonning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using 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 leftof 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 return value:


 
A Tuple is a comma separated sequence of items.
 
It is created with or without ( ).
 A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

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?

• A set is a well-defined collection of distinct objects.


– Example: A = {1, 2, 3, 4, 5}

What is an element of a Set?

• The objects in a set are called its elements.

– So in case of the above Set A, the elements would be 1, 2, 3, 4, and


5. We can say,1  A, 2  A etc.

• Usually we denote Sets by CAPITAL LETTERs like A, B, C, etc. while


their elementsare denoted in small letters like x, y, z etc.

• If x is an element of A, then we say x belongs to A and we represent it


as x  A

• If x is not an element of A, then we say that x does not belong to A and


we represent it as
xA

How to describe a Set?

• Roaster Method or Tabular Form

– In this form, we just list the elements

– Example A = {1, 2, 3, 4} or B = {a, b, c, d, e}

• Set- Builder Form or Rule Method or Description Method

– In this method, we list the properties satisfied by all elements


of the 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}

2 {2, 4, 6, 8, 10} {x | x = 2n, n  N, 1 ≤ n ≤ 5}

3 {1, 4, 9, 16, 25, 36} {x | x = n2, n  N, 1 ≤ n ≤ 6}

Sets of Numbers
1. Natural Numbers (N)

 N = {1, 2, 3,4 ,5 6, 7, …}

2. Integers (Z)

 Z = {…, -3, -2, -1, 0, 1, 2, 3, 4, …}

3. Whole Numbers (W)

 W = {0, 1, 2, 3, 4, 5, 6…}

4. Rational Numbers (Q)

 {𝑝 : p  Z, q  Z, q ≠ 0}
𝑞

Finite Sets & Infinite Sets

 Finite Set: A set where the process of counting the


elements of the set wouldsurely come to an end is called
finite set
• Example: All natural numbers less than 50
• All factors of the number 36
 Infinite Set: A set that consists of uncountable number of
distinct elements iscalled infinite set.
• Example: Set containing all natural numbers {x |
x  N, x > 100}

Cardinal number of Finite Set

 The number of distinct elements contained in a finite set A


is called the cardinalnumber of A and is denoted by n(A)

• Example A = {1, 2, 3, 4} then n(A) = 4

• A = {x | x is a letter in the word ‘APPLE’}. Therefore A =


{A, P, L, E} and
n(A) = 4

• A = {x | x is the factor of 36}, Therefore A = { 1, 2, 3, 4,


6, 9, 12, 18, 36}and n(A) = 9

Empty Set

• A set containing no elements at all is called an empty set or a


null set or a void set.

• It is denoted by ϕ (phai)

• In roster form you write ϕ = { }

• Also n (ϕ) = 0

• Examples: {x | x  N, 3 < x <4} = ϕ

• {x | x is an even prime number, x > 5} = ϕ

Non Empty Set

• A set which has at least one element is called a non-empty set

• Example: A = {1, 2, 3} or B = {1}


Singleton Set

• A set containing exactly one element is called a singleton set

• Example: A = {a} or B = {1}

Equal Sets

• Two set A and B are said to be equal sets and written as A = B


if every element ofA is in B and every element of B is in A

• Example A = {1, 2, 3, 4} and B = {4, 2, 3, 1}

• It is not about the number of elements. It is the elements


themselves.

• If the sets are not equal, then we write as A ≠ B


Equivalent Sets

• Two finite sets A and B are said to be equivalent,


written as A ↔ B,if n(A) = n(B), that is they have
the same number of elements.

• Example: A = {a, e, i, o, u} and B = {1, 2, 3, 4, 5},


Therefore n(A) = 5 andn(B) = 5 therefore A ↔ B

• Note: Two equal sets are always equivalent but two


equivalent sets need not beequal.
Subsets

• If A and B are two sets given in such a way that every


element of A is in B, thenwe say A is a subset of B and we
write it as A ⊆ B

• Therefore is A ⊆ B and x  A then x  B

• If A is a subset of B, we say B is a superset of A and is written as


BA
• Every set is a subset of itself.

• i.e. A ⊆ A, B ⊆ B etc.

• Empty set is a subset of every set

• i.e. ϕ ⊆ A, ϕ ⊆ B

• If A ⊆ B and B ⊆ A, then A = B
• Similarly, if A = B, then A ⊆ B and B ⊆ A

• If set A contains n elements, then there are 2n subsets of A


Power Set

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

• i.e. if A = {1, 2}, then P(A) = 22 = 4

• Empty set is a subset of every set

• So in this case the subsets are {1}, {2}, {2, 3} & ϕ


Proper Subset

• 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 ⊆ B and A  B, then A  B

– Please note that ϕ has no proper subset

– A set containing n elements has (2n – 1) proper subsets.

• i.e. if A = {1, 2, 3, 4}, then the number of proper subsets is


(24 – 1) = 15
Universal Set

• If there are some sets in consideration, then there happens to be a


set which is a supersetof each one of the given sets. Such a set is
known as universal set, to be denoted by U or


• 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

• The union of sets A and B, denoted by A  B, is the set of all


those elements, eachone of which is either in A or in B or in
both A and B

• If there is a set A = {2, 3} and B = {a, b}, then A  B = {2, 3, a,


b}

• So if A  B = {x | x  A or x  B}

• , then x  A  B which means x  A or x  B

• And if x  A  B which means x  A or x  B


• Interaction of Sets

• The intersection of sets A and B is denoted by A  B, and is a


set of all elementsthat are common in sets A and B.

• i.e. if A = {1, 2, 3} and B = {2, 4, 5}, then A  B = {2} as 2 is the


only commonelement.

• Thus A  B = {x: x  A and x  B} then x  A  B i.e. x  A and x


B

• And if x  A  B i.e. x  A and x  B

• Disjointed Sets

• Two sets A and B are called disjointed, if they have no


element in common.Therefore:

• A  B = ϕ i.e. if A = {2, 3} and B = {4, 5}, then A  B = ϕ

• Intersecting sets
• Two sets are said to be intersecting or overlapping or
joint sets, if they haveat least one element in common.

• Therefore two sets A and B are overlapping if and only if


ABϕ

• Intersection of sets is Commutative

i.e. A  B = B  A for any sets A and B

• Intersection of sets is
Associative

• i.e. for any sets, A, B, C,

• (A  B)  C = A  (B  C)

• If A ⊆ B, then A  B = A

• Since A ⊆ , so A   = A

• For any sets A and B, we have

• A  B ⊆ A and A  B ⊆ B

• A  ϕ = ϕ for every set A

• Difference of Sets

• For any two sets A and B, the difference A – B is a set of all


those elements of Awhich are not in B.

i.e. if A = {1, 2, 3, 4, 5} and B = {4, 5, 6}, Then A – B = {1, 2, 3} and B – A =


{6}

Therefore A – B = {x | x  A and x  B}, then x  A – B then x  A but x 


B

• If A  B then A – B = 


• Complement of a Set

• Let x be the universal set and let A  x. Then the complement


of A, denoted by A’is the set of all those elements of x which
are not in A.

• i.e. let  = {1, 2, 3, 4, 5,6 ,7 ,8} and A = {2, 3,4 }, then A’ =


{1, 5, 6, 7, 8}

• Thus A’ = {x | x   and x  A} clearly x  A’ and x  A

• Please note

• ’ =  and ’= 

A  A’ =  and A  A’ = ϕ

Disruptive laws for Union and Intersection of Sets

• For any three sets A, B, C, we have the following

• A  (B  C) = (A  B)  (A  C)

Say A = {1, 2}, B = {2, 3} and C = {3, 4}

Therefore A  (B  C) = {1, 2, 3} and

And (A  B)  (A  C) = {1, 2, 3} and hence equal

• A  (B  C) = (A  B)  (A  C)

Say A = {1, 2}, B = {2, 3} and C = {3, 4}

Then A  (B  C) = {2} and (A  B)  (A  C) = {2} and


hence equal

Disruptive laws for Union and Intersection of Sets

• De-Morgan’s Laws

– Let A and B be two subsets of a universal set , then


• (A  B)’ = A’  B’

• (A  B)’ = A’  B’

Let  = {1, 2, 3, 4, 5, 6} and A = {1, 2, 3} and B = {3, 4, 5}

Then A  B = {1, 2, 3, 4, 5}, therefore (A  B)’ = {6}

A’ = {4, 5, 6} and B’ = {1, 2, 6}

Therefore A’  B’ = {6}. Hence proven

Python Set Methods

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.

Functions Name Description


add() Adds a given element to a set
clear() Removes all elements from the set
copy() Returns a shallow copy of the set
difference() Returns a set that is the difference
between two sets
difference_update() Updates the existing caller set with the
difference between two sets
discard() Removes the element from the set
intersection() Returns a set that has the intersection of
all sets
intersection_update() Updates the existing caller set with the
intersection of sets
pop() Returns and removes a random element
from the set
remove() Removes the element from the set
union() Returns a set that has the union of all sets
update() Adds elements to the set
Dictionaries:


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

Operations Example Description

Creating a >>> a={1:"one",2:"two"} Creating the dictionary with


dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}
accessing an >>> a[1] Accessing the elements by using
element 'one' keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new value.
{1: 'ONE', 2: 'two'}
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False
Methods in
dictionary:

Method Example Description

a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=a.copy() dictionary. here copy of
>>> print(b) dictionary ’a’ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
a.items() >>> a.items() Return a new view of
dict_items([(1, 'ONE'), (2, 'two'), (3, the dictionary's items. It
'three')]) displays a list of
dictionary’s (key, value)
tuple pairs.
a.keys() >>> a.keys() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
a.values() >>> a.values() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
a.pop(key) >>> a.pop(3) Remove the element
'three' with key and return its
>>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.

setdefault(key,value) >>> a.setdefault(3,"three") If key is in the


'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>> a.setdefault(2) a value of dictionary and
'two' return dictionary.
a.update(dictionary) >>> b={4:"four"}
It will add the dictionary
>>> a.update(b)
with the existing
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} dictionary
fromkeys() >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
>>>lena(a) the list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>a.clear() form the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.

Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in
brackets[ ] and their and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])

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

FILE HANDLING IN PYTHON


File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we
are done, it needs to be closed, so that resources that are tied with the file are
freed. Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file

Advantages of File Handling in Python


1.Versatility : File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
2.Flexibility : File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files , etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
3.User – friendly : Python provides a user-friendly interface for file handling,
making it easy to create, read, and manipulate files.
4.Cross-platform : Python file-handling functions work across different
platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and
compatibility.

Disadvantages of File Handling in Python


1.Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the file
system (e.g. file permissions, file locks, etc.).
2.Security risks : File handling in Python can also pose security risks, especially
if the program accepts user input that can be used to access or modify sensitive
files on the system.
Module 5

3.Complexity : File handling in Python can be complex, especially when


working with more advanced file formats or operations. Careful attention must
be paid to the code to ensure that files are handled properly and securely.
4.Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.

Opening Files in Python


Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
Suppose we have a file named file1.txt.
• To open this file, we can use the open() function.
• file1 = open("file1.txt")
• Here, we have created a file object named file1. Now, we can use this
object to work with files.

Different File Opening Modes


• Python allows us to open files in different modes (read, write, append, etc.),
based on which we can perform different file operations. For example,
file1 = open("file1.txt")
Here, we are opening the file in the read mode (we can only read the content, not
modify it).
• By default, Python files are opened in read mode. Hence, the code
open("file1.txt", "r") is equivalent to open("file1.txt").

Mode Description
Module 5

Open a file in reading mode


R
(default)

W Open a file in writing mode

X Open a file for exclusive creation

Open a file in appending mode


A
(adds content at the end of the file)

T Open a file in text mode (default)

B Open a file in binary mode

Open a file in both read and write


+
mode

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

Opening a File Using its Full Path


Module 5

• We can also open a file using its full path.


Example:
file_path = "/home/user/documents/file1.txt"
file1 = open(file_path)

READING AND WRITING FILES :


Reading Files in Python
After we open a file, we use the read() method to read its content.
For example, suppose we have a file named file1.txt.
# open a file in read mode
file1 = open("file1.txt")
# read the file content
read_content = file1.read()
print(read_content)

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.

Writing to Files in Python


A text file is a sequence of characters stored on a permanent medium like a hard
drive, flash memory, or CD-ROM. To write to a Python file, we need to open it
in write mode using the w parameter.
Suppose we have a file named file2.txt. Let's write to this file.
# open the file2.txt in write mode
file2 = open('file2.txt', 'w')
Module 5

# write contents to the file2.txt file


file2.write('Programming is Fun.\n')
file2.write('Programiz for beginners\n’)
Note: If the file already exists, opening it in write mode clears out the old data
and starts fresh, so be careful! If the file doesn’t exist, a new one is created.

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

Closing Files in Python


When we are done performing operations on the file, we need to close the file
properly. We use the close() function to close a file in Python.
For example,
#open a file
file1 = open("file1.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
# close the file
file1.close()

Opening a Python File Using with...open


In Python, there is a better way to open a file using with...open. For example,
with open("file1.txt", "r") as file1:
read_content = file1.read()
Module 5

print(read_content)
Here, with...open automatically closes the file, so we don't have to use the close()
function.

Some Commonly Used File Methods

Method Description

Closes an opened
close()
file

Reads the file


read(n)
content

Changes the file


position to offset
seek(offset,from=SEEK_SET) bytes, in reference to
from (start, current,
end)

Returns an integer
that represents the
tell()
current position of
the file's object

Writes a string to the


write(s)
file

Writes a list of lines


writelines(lines)
to the file

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

An alternative is to use the format operator, %. When applied to integers, % is


the modulus operator. But when the first operand is a string, % is the format
operator.
The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted. The result is a
string.
For example, the format sequence '%d' means that the second operand should be
formatted as an integer (d stands for “decimal”):
>>> camels = 42

>>> '%d' % camels

'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

COMMAND LINE ARGUMENTS


Python Command Line Arguments provides a convenient way to accept some
information at the command line while running the program. Python provides
various ways of dealing with these types of arguments. The three most common
are:
• Using sys.argv
• Using getopt module
• Using argparse module

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

# Python program to demonstrate


# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)

Output:
Module 5

Using getopt module


Python’s getopt module is similar to the getopt() function of C. Unlike sys
module getopt module extends the separation of the input string by parameter
validation. It allows both short, and long options including a value assignment.
However, this module requires the use of the sys module to process input data
properly. To use getopt module, it is required to remove the first element from the
list of command-line arguments.
• Syntax: getopt.getopt(args, options, [long_options])

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

# checking each argument


for currentArgument, currentValue in arguments:
if currentArgument in ("-h", "--Help"):
print ("Displaying Help")

elif currentArgument in ("-m", "--My_file"):


print ("Displaying file_name:", sys.argv[0])

elif currentArgument in ("-o", "--Output"):


print (("Enabling special output mode (% s)") % (currentValue))

except getopt.error as err:


# output error, and return with an error code
print (str(err))

Output:

Using argparse module


Module 5

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

Example 2: Adding description to the help message.


# Python program to demonstrate
# command line arguments
import argparse
msg = "Adding description"
# Initialize parser
parser = argparse.ArgumentParser(description = msg)
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

for line in open(filename):


count += 1
return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the
file, which is 7.
You can also import it like this:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it
executes the test code at the bottom. Normally when you import a module, it
defines new functions but it doesn’t execute them.
Programs that will be imported as modules often use the following idiom: if
__name__ == '__main__':
8
print linecount('wc.py')
__name__ is a built-in variable that is set when the program starts. If the
program is running as a script, __name__ has the value __main__; in that
case, the test code is executed. Otherwise, if the module is being imported,
the test code is skipped. Eg:
# import module import calendar
yy = 2017
mm = 8
# To ask month and year from the user
Module 5

# yy = int(input("Enter year: "))


#mm = int(input("Enter month: "))
# display the calendar print(calendar.month(yy, mm))

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.

Importing module from a package


We can import modules from packages using the dot (.) operator.
Module 5

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.

OBJECT ORIENTED PROGRAMMING


Object Oriented Programming (OOP) approach identifies classes of objects that
are closely related to the methods with which they are associated. It also covers
the concepts of attribute and method inheritance. The Massachusetts Institute of
Technology was the first institution to utilize terminology referring to “objects”
in the sense that we use object-oriented programming today, in the late 1950s and
early 1960s.
OOP is based on the idea of classes and objects. It organizes a computer
program into basic, reusable blueprints of code or “classes.” These classes are
then used and reused to create new and unique objects with similar functions.
This paradigm represents a system that interacts with actual items in real life –
such as the user.
Module 5

Python is an object-oriented programming language that offers classes, which act


as a tool for writing reusable code. To describe objects with shared characteristics
and behaviours, classes are utilised.
Python follows the object-oriented programming paradigm, which is a model of
programming that is based on the concept of "objects", which represent data and
the actions that can be performed on that data.

CREATING PYTHON CLASSES


In Python, a class is a user-defined data type that contains both the data itself and
the methods that may be used to manipulate it.
Classes serve as a template to create objects. They provide the characteristics and
operations that the objects will employ.
In Python, a class can be created by using the keyword class, followed by the
class name.
The syntax to create a class is given below :
class ClassName:
#Class body

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"

OBJECTS AND CLASSES


Module 5

A class is a blueprint that is used for creating objects. It is a user-defined data


type that can be accessed and used by creating an instance of that class. It has its
own data members and member functions. A class is comparable to an object’s
blueprint. Both member functions and data members are found in classes. The
data members inside the class are manipulated using these member functions.
A Python class defines a structure that can be used to create multiple objects.
These objects will share the same structure and behavior as defined in the class.
Objects are instances of a class. In simple words, when we create an object, an
instance of the class is created that is complete with attributes and methods. At
the point of creation of a class, the description is the first object to be defined. An
instance of a class exists in an object. Notably, the system does not allocate any
memory space when a class is specified, but it’s allocated when it is instantiated,
i.e., when an object is formed. Real-world things have state and behavior in
common, a pair of features. An object conceals its behavior through methods and
keeps its information in attributes.

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.

ABSTRACT CLASSES IN PYTHON


Module 5

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.

Working with abstract classes


Python does not provide abstract classes by default. To create abstract classes and
perform abstraction, we need to first import the Python module abc.
This abc module provides the infrastructure for defining the abstract base class
in Python. Using this, we can define a structure, but there’s no need to provide
complete implementation for every method.
Example
from abc import ABC, abstractmethod
#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
Module 5

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

Benefits of Abstraction in Python


1.Modularity: Abstraction promotes modularity by breaking down complex
systems into smaller, more manageable modules. Each module can be developed
and tested independently, making the overall codebase more maintainable.
2.Reusability: With abstraction, we can create abstract classes that define
common attributes and behaviors. These abstract classes can be inherited by
multiple subclasses, allowing us to reuse code and avoid duplication.
Module 5

3.Encapsulation: Abstraction helps in encapsulating the implementation details


within a class. By hiding the internal workings of a class, we can protect the data
from being accessed or modified directly. This enhances the security and integrity
of the code.
4.Flexibility: Abstraction provides flexibility by allowing us to modify the
implementation of a class without affecting the code that uses it. This makes it
easier to adapt and extend the functionality of a program as requirements change.
5.Code Readability: By abstracting away unnecessary details, the code becomes
more readable and easier to understand. It allows developers to focus on the
essential aspects of a program and improves the overall code quality.

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.

The Syntax for inheritance is as follows :


Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}

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

For example, a Car is a Vehicle, and this relationship is represented through


single inheritance It promotes code organization and reuse without introducing
complexity

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

Advantages of Inheritance in Python


1.Modular Codebase: Increases modularity, i.e. breaking down the codebase into
modules, making it easier to understand. Here, each class we define becomes a
separate module that can be inherited separately by one or many classes.
2.Code Reusability: the child class copies all the attributes and methods of the
parent class into its class and use. It saves time and coding effort by not rewriting
them, thus following modularity paradigms.
3.Less Development and Maintenance Costs: Changes need to be made in the
base class, all derived classes will automatically follow.

Disadvantages of Inheritance in Python


1.Decreases the Execution Speed: loading multiple classes because they are
interdependent
2.Tightly Coupled Classes: this means that even though parent classes can be
executed independently, child classes cannot be executed without defining their
parent classes.
Module 5

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

19.Explain the types of inheritance with an example program for each.


20.Describe how polymorphism is implemented in python with an example
program.
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

You might also like