0% found this document useful (0 votes)
13 views105 pages

Python Inforamtion

The document provides an introduction to Python programming, covering its features, applications, and basic concepts such as variables, data types, control flow, and operators. It also discusses Python versions, installation steps, and type conversions, emphasizing Python's readability and ease of use. Additionally, it highlights Python's extensive libraries and their role in various fields like web development, data science, and automation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views105 pages

Python Inforamtion

The document provides an introduction to Python programming, covering its features, applications, and basic concepts such as variables, data types, control flow, and operators. It also discusses Python versions, installation steps, and type conversions, emphasizing Python's readability and ease of use. Additionally, it highlights Python's extensive libraries and their role in various fields like web development, data science, and automation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Unit – I
Introduction to Python Programming
Introduction to Python: Working with python, Variables, expressions, and statements,
accepting user input. Conditional execution. Nested conditionals, Iteration, Function Basics
Built-in Functions. Recursion, Scope Global, Local variables. Modules: Creating and importing
modules importing all or specific classes from module.

Introduction:
 Python is a high-level, interpreted programming language known for its simplicity and
readability.

 Created by Guido van Rossum and first released in 1991.

 Python has become the most popular programming languages particularly for tasks like web
development, data analysis, artificial intelligence, scientific computing, and automation.

Features of pythons:
 Readability and Simplicity: Python's syntax are easier for programmers to understand and write
code, reducing errors and improving maintainability.

 Ease of Use: Compared to other languages, Python requires less code. This frees programmers
from writing repetitive code and allows them to focus on the core logic of their program.

 Interpreted Language: An interpreter executes the code line by line, making development faster
and debugging easier.

 Cross-Platform Compatibility: Python code can run on various operating systems like
Windows, macOS, and Linux without modification.

 Dynamic Typing: Python variables don't have a predefined data type. The type is associated
with the value assigned to the variable at runtime.

 Object-Oriented Programming (OOP): Python supports object-oriented programming


concepts like classes, objects, inheritance, and polymorphism.

 Extensible: Python allows for easy integration with other languages like C and C++.

 Strong Standard Library: Python comes with a comprehensive standard library that provides
modules and functions for a wide range of tasks, such as file I/O, networking, and data
manipulation.

Applications of Python:
 Web Development: Python is widely used for building dynamic web applications.
Frameworks like Django and Flask provide developers with powerful tools for rapid
development, scalability, and security.

1|Page
Python Programming
 Data Science and Machine Learning: Python has become the de facto language for data
science and machine learning due to its extensive libraries such as NumPy, pandas, etc. These
libraries facilitate data manipulation, analysis, visualization, and implementation of machine
learning algorithms.

 Automation and Scripting: Python's simplicity and readability make it ideal for automating
repetitive tasks and writing scripts. It is commonly used for tasks such as system
administration, file manipulation, and batch processing.

 Game Development: Python is increasingly being used in game development, both for indie
games and large-scale productions. Libraries like Pygame provide developers with tools for
building 2D games, while engines like Unity and Unreal Engine offer support for scripting in
Python.

 Desktop GUI Applications: Python can be used to create desktop graphical user interface
(GUI) applications using libraries like Tkinter, PyQt, and wxPython. These libraries allow
developers to build cross-platform GUI applications with ease.

 Educational Purposes: Python's easy-to-understand syntax and extensive documentation


make it an excellent choice for teaching programming to beginners. Many educational
institutions use Python as an introductory language for computer science courses.

Python Versions
Python has undergone several major releases since its inception. Some of the notable versions
include:
 Python 1.x: The initial versions of Python, including
1.0 and 1.6, introduced fundamental features of the language such as the core syntax and
basic data structures. These versions are no longer in active use.

 Python 2.x: Python 2 was a major release series that introduced significant improvements
and new features. The most widely used versions in this series were Python 2.7, which
became the stable version for many
years. However, Python 2 reached its end-of-life on January 1, 2020, and is no longer maintained
or supported.

 Python 3.x: Python 3 is the current and actively developed version of the language. Notable
versions in the Python 3 series include Python 3.0, Python 3.6,
Python 3.7, Python 3.8, Python 3.9, and Python 3.10 (the latest stable release as of my last
update). Python 3 is the recommended version for all new development.

Installation of Python
1. Download Python Executable Installer
On the web browser, in the official site of python ([Link]), move to the Download
for Windows section.

2|Page
Python Programming
2. Run Executable Installer
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
New.

On clicking the Install Now, The installation process starts.


3. Verify Python is installed on Windows
To ensure if Python is successfully installed on your system. Follow the given steps −
 Open the command prompt.
 Type ‘python’ and press enter.
 The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.
4. Verify Pip was installed
To verify if pip was installed, follow the given
steps −
 Open the command prompt.
 Enter pip –V to check if pip was installed.
 The following output appears if pip is installed successfully.

Basics of Pythons
1. Python Identifiers
 An identifier in Python is a name used for identifying a variable, class, function, object, module.

 An identifier in python programming starts with a letter A to Z / a to z / an underscore followed


by zero or more letters, underscores, and digits.

 Python language does not allow punctuation characters within an identifier name for example: @,
$, and %.

3|Page
Python Programming
 No identifiers can begin with a number, and no symbols other than the underscore.

 Python is a case sensitive programming language.

2. Python Keywords
 Keywords in python are the reserved words.

 These words cannot be used as a variable name, function name, or any other identifier name.

 The following table lists some keywords of python.

3. Statements and Expressions

Statements:
 Statements are complete instructions that tell the Python interpreter to perform an action. They
don't
necessarily return a value.
 Statements can be used for various tasks like:
 Assigning values to variables (x = 5)
 Printing output to the console (print("Hello, world!"))
 Creating control flow using if, for, and while statements
 Defining functions (def my_function():)
 Importing modules (import math)

Expressions:

 Expressions are combinations of values, variables, operators, and function calls that evaluate
to a single result.
 This result can be a number, a string, a Boolean value, or even another data structure.
 Expressions are often used within statements, but they don't perform actions on their own.

4|Page
Python Programming

4. Variables in Python
o Variables are containers for storing a value.
o Python is dynamically typed, it means that there is no requirement of pre-declaration of a variable
or its type.
o The type (and value) are initialized on the assignment. Assignments are performed using an equal
sign (=).
o Following example depicts how to declare variables in python:
>>> count = 0 name = 'Ram'
count = count + 1
o A variable is created the moment you first assign a value to it.
o Variables do not need to be declared with any particular type and can even change type after
they have been set.
x=4 # x is of type int
x= "Tally" #x is now of type str
o String variables in Python can be declared either by using single or double quotes.

Operators in Python
 Operators in Python are symbols that perform operations on variables and values.

 Python supports various types of operators, including arithmetic, comparison, assignment,


logical, bitwise, membership, and identity operators.

5|Page
Python Programming
1. Arithmetic Operators

o Arithmetic operators perform basic mathematical operations.

2. Comparison Operators:

 Comparison operators compare two values and return a Boolean result (True or False).

3. Assignment Operators:

o Assignment operators are used to assign values to variables.

6|Page
Python Programming

4. Logical Operators:

o Logical operators perform logical operations on Boolean values.

Bitwise Operators:

o Bitwise operators perform operations on binary representations of integers.

7|Page
Python Programming

5. Membership Operators:

o Membership operators test for membership in sequences like lists, tuples, and strings.

 in (checks if value is present in sequence)


 not in (checks if value is not present in sequence).

6. Identity Operators:

o Identity operators compare the memory addresses of two objects.

 is (checks if two variables refer to the same object),


 is not (checks if two variables refer to different objects).

Precedence and Association


o In Python, operator precedence determines the order in which operators are evaluated in an
expression.

o While operator association defines the direction in which operators of the same precedence are
evaluated.

Precedence:

o Operator precedence determines the order in which operators are evaluated in an expression.

o Operators with higher precedence are evaluated before operators with lower precedence.
8|Page
Python Programming

o For example, multiplication (*) has higher precedence than addition (+), so 3 + 5 * 2 is evaluated
as 3 + (5 *
2), resulting in 13.

o Parentheses can be used to override precedence and explicitly specify the order of evaluation.

Association:

o Operator association determines the direction in which operators of the same precedence are
evaluated.

o It's relevant when operators of equal precedence are present in an expression.

o Most operators in Python have left-to-right association, meaning they are evaluated from left to
right.

o However, exponentiation (**) has right-to-left association, meaning it's


evaluated from right to left.

o For example, 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2),


resulting in 512.

Datatypes in Python
 In Python, data types represent the type or category of data that a variable or object can
hold.

 Python is a dynamically-typed language, meaning that variables do not have fixed types.
Instead, the type of a variable is determined at runtime based on the value assigned to it.

 Some of the primary data types in Python are:

1. Numeric Types:

o int: Integers represent whole numbers without any decimal point. Example: x = 10.

o float: Floats represent real numbers with a decimal point. Example: y = 3.14.
9|Page
Python Programming

o complex: Complex numbers consist of a real part and an imaginary part represented by j.
Example: z
= 3 + 2j.

2. Boolean Type:

o bool: Booleans represent the truth values True and False. Example: is_python_fun = True.

3. Dictionary:

o Unordered collections of key-value pairs enclosed in curly braces {}.

o Keys must be unique and immutable (often strings or numbers), while values can be of any
data type

o Example: D= {"name": "Alice", "age": 30}.

4. Set:

o Unordered collections of unique elements enclosed in curly braces {}.

o Elements must be immutable (often strings or numbers).

o Sets don't allow duplicate elements (e.g., {1, "apple", 3.14}).

5. Sequence Types:

o string: Strings represent sequences of characters enclosed in single (') or double (") quotes.

 Example: message = 'Hello, World!'.

o list: Lists represent ordered collections of items that can be of different data types.

 Example: my_list = [1, 'apple', True].

o tuple: Tuples are similar to lists but are immutable (cannot be modified after creation).

 Example: my_tuple = (1, 2, 3).

6. None Type:

o None: Represents the absence of a value or a null value. Example: x = None.

Indentation in Python
o Indentation is a unique and essential aspect of Python's syntax.

o Unlike many other programming languages that use curly braces { } to define code blocks, Python relies
on indentation to structure your code.

o Here's a breakdown of how indentation works in Python:


10 | P a g
e
Python Programming
 Indentation Levels: Python uses consistent whitespace (usually 4 spaces) to define the nesting of
code blocks.

 Indentation Scope: Statements with the same indentation level belong to the same block of code and
are executed together.
 New Block, New Indentation: To create a new block of code (like within an if statement or
loop), you must indent the statements further to the right.

 Consistent Indentation: It's crucial to maintain consistent indentation throughout your code.
Mixing spaces and tabs or using inconsistent indentation levels will lead to errors.

Type Conversions in python


o Type conversion, also known as type casting, in Python refers to the process of transforming a
value from one data type to another.

o There are two main approaches to type conversion in Python:

1. Implicit Type Conversion (Automatic):

o Python is dynamically typed, meaning variables don't have a fixed data type assigned at declaration.

o The type is associated with the value assigned to the variable.

o When performing operations or assigning values that involve different data types, Python sometimes
automatically converts the data types to ensure compatibility. This implicit conversion happens
behind the scenes.

2. Explicit Type Conversion (Manual):

o In some cases, you might want to explicitly control the data type conversion.

o Python provides built-in functions to perform this type casting.

o Common Type Conversion Functions:

 int(x): Converts x to an integer.

 float(x): Converts x to a floating-point number.

 str(x): Converts x to a string.

 bool(x): Converts x to a boolean (True or False).

Python Libraries
o Python libraries are collections of pre-written code modules that provide functionalities for various
tasks.

o They extend the capabilities of the Python language and allow you to perform complex operations
11 | P a g
e
Python Programming
without writing everything from scratch.

Importing Libraries

1. Importing the Entire Library:

Use the import statement followed by the library name to import all functionalities from the library.

Example:

2. Importing Specific Functions or Classes:

You can import specific functions or classes from a library using the from ... import syntax.

Example:

3. Giving Aliases to Libraries:


For long library names, you can assign shorter aliases using the as keyword.

Example

Python Control Flow


Control flow in Python refers to the order in which statements are executed in a program. Python
provides several control flow constructs to enable conditional execution, looping, and branching

1. Conditional Statements:

Used to make decisions based on certain conditions.

i. if statement:

Executes a block of code if a specified condition is True.

12 | P a g
e
Python Programming

ii. else statement:

Provides an alternative block of code to execute if the condition in the if statement is False.

iii. elif statement:

Allows you to check multiple conditions sequentially.

2. Looping Statements in Python


o Looping statements are used to execute a block of code repeatedly until a specified condition is
satisfied.
o They help avoid writing the same code multiple times and make programs more efficient and shorter.
o Python mainly provides two types of loops:
o for loop
o while loop
i. for loop
Explanation:

 The for loop is used to iterate over a sequence of items such as a list, tuple, dictionary, set, or
string.
 It automatically assigns each value in the sequence to a loop variable and executes the block of
code for every element.
 It is mostly used when the number of iterations is known in advance.

Syntax:

for variable in sequence:


# block of code
13 | P a g
e
Python Programming
 variable → Temporary variable that holds each item in the sequence.
 sequence → A collection of items (list, string, range, etc.).
 The code block inside the loop runs once for every element in the sequence.

Example 1: Using range()


for i in range(5):
print("Iteration:", i)
OUTPUT:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

ii. while loop


Explanation:
 The while loop keeps executing a block of code as long as the given condition remains True.
 It is used when the number of iterations is not known beforehand.
Syntax:
 condition → A logical expression evaluated before every iteration.
 The loop continues until the condition becomes False.

Example 1: Counting numbers

14 | P a g
e
Python Programming

2. break and continue Statements:


These statements are used to control the flow of loops — to either stop or skip certain iterations.
i. break:
Used within loops to prematurely exit the loop when a certain condition is met.
Explanation:
 The break statement is used to exit a loop immediately, even if the condition is still True
or there are remaining items.
Once executed, control moves to the first statement after the loop

ii. continue:
Used within loops to skip the current iteration and proceed to the next one.

range () and exit () functions in python


1. range() Function:
o The range() function generates a sequence of numbers within a specified range.

o It is commonly used with loops to iterate over a sequence of numbers.

o The range() function can take one, two, or three arguments: range(stop), range(start, stop), or
range(start, stop, step).

o By default, range() starts from 0 and increments by 1.

2. exit() Function:
o The exit() function is used to terminate
the execution of the Python interpreter.

o It can be used to exit the current script or


15 | P a g
e
Python Programming
Python session immediately.

o The exit() function is usually called with an optional status code, which can indicate success (0) or
failure (non-zero).

o exit() is typically used in command-line scripts or interactive sessions to halt execution.

o It is part of the sys module and can also be accessed as [Link]().

 What is a Function?

 A function in Python is a block of reusable code that performs a specific task.


 It helps to make programs modular, organized, and less repetitive.

Built-in Functions-
o In Python, you can use built-in functions to perform console input and output operations.

o These functions allow you to interact with the user through the console (also known as standard input
and standard output).

o Here are the main built-in functions for console input and output:

2. Console Output:

o print(): The print() function is used to display output to the console.

o It can take one or more arguments, which can be of different data types.

o The function converts the arguments to strings and concatenates them, separating them with a
space by default.

3. Console Input:

o input(): The input() function is used to receive input from the user via the console.

o It displays a prompt to the user (if provided) and waits for the user to enter a value followed by
pressing the Enter key.

o The function returns the input value as a string.

16 | P a g
e
Python Programming

Function Description Example Output


Name
abs() Returns the absolute (positive) value of a abs(-15) 15
number.
ascii() Returns a printable version of an object ascii("Pranesh ©") 'Pranesh \\xa9'
(escapes special characters).
bin() Converts an integer to a binary string. bin(7) '0b111'
chr() Returns the character for the given ASCII chr(65) 'A'
value.
complex() Creates a complex number. complex(2, 5) (2+5j)
dict() Creates a dictionary object. dict(name="Raj", {'name': 'Raj',
age=20) 'age': 20}
dir() Returns a list of attributes and methods of an dir("hello") List of string
object. methods
frozenset() Creates an immutable (unchangeable) set. frozenset([1, 2, 3]) frozenset({1, 2,
3})
help() Shows documentation for modules, help(len) Documentation
functions, etc. text
input() Reads a line of input from the user. input("Enter name: ") User-entered
value

Recursive Functions:

The term Recursion can be defined as the process of defining something in terms of itself

Recursion is programming technique where-in function is called repeatedly until a
condition is met.
 Recursion is programming technique where-in function call itself.
 In general, a recursive definition is made up of two parts. There is at least one base case
that directly specifies result for a special case and there is least one recursive case.
 Example 1: Program to print the fibonacci series upto n_terms
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))

n_terms = 5
if n_terms <= 0:
print("Invalid input ! input a positive value")
else:
print("Fibonacci series:") for i in range(n_te rms):
print(recursive_fibonacci(i))

17 | P a g
e
Python Programming

Output
Fibonai series:
0
1
1
2
3

Scope and Lifetime of Variables in Functions.


All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −
 Global variables
 Local variables
The lifetime of a variable in Python:

The variable lifetime is the period during which the variable remains in the memory
of the Python program. The variables' lifetime inside a function remains as long as the
function runs. These local types of variables are terminated as soon as the function replaces or
terminates.

Global variables:
Variables that are defined outside have a global scope. Global variables can be accessed
throughout the program body by all functions.

Local variables:
Variables that are defined inside a function body have a local [Link] means that local
variables can be accessed only inside the function in which they are declared.
Example total = 0; # This is global variable.
def sum( arg1, arg2 ):
total = arg1 total is local variable. print "Inside
the function local total : + arg2; # Here ", total
return total;
sum( 10, 20 );
print "Outside the function global total : ", total
Output:
Inside the function local total : 30
Example 2: # Program to print factorial of a numbe recursively.

18 | P a g
e
Python Programming
# Global variable
total = 0
def fact(n): # Local variable inside the function
if n == 1:
return n
else:
return n * fact(n - 1)
# Main program
num = 6

if num < 0:
print("Invalid input! Enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
total = fact(num) # Accessing the global variable
print("Factorial of number", num, "=", total)

OUTPUT: Factorial of number 6 = 720

Modules:
1. What is a Module?
A module in Python is a file containing Python functions, classes, variables, and statements.
Any file saved with a .py extension is considered a module.
Example:
File name: my_module.py
Module name: my_module

Purpose:
Modules help in reusability, organization, and easy maintenance of large programs.

2. Importance of Modules
o Break large programs into smaller parts
o Reusability of functions and classes
o Easier debugging
o Each module has its own namespace
o Python provides many built-in modules like math, random, datetime, os
3. Creating a Module
Create any Python file and save it with .py extension.

19 | P a g
e
Python Programming

Example: my_module.py
def greet(name):
return f"Hello, {name}!"

class MyClass:
def __init__(self, value):
[Link] = value

def get_value(self):
return [Link]

PI = 3.14159
This file can be used in other programs by importing it.

4. Importing Modules
Python supports multiple import methods.

4.1 Import Entire Module


import my_module

print(my_module.greet("Alice"))
obj = my_module.MyClass(10)
print(obj.get_value())
print(my_module.PI)

4.2 Import with Alias


import my_module as mm

print([Link]("Bob"))

20 | P a g
e
Python Programming
4.3 Import Specific Items
from my_module import greet, MyClass

print(greet("Charlie"))
obj = MyClass(20)
print(obj.get_value())

4.4 Import All Items


from my_module import *
print(greet("David"))
obj = MyClass(30)
print(obj.get_value())
print(PI)
⚠ Not recommended in large projects because it may cause naming conflicts.

5. Built-in Modules (Examples)


math
import math
[Link](25)
[Link](5)
random
import random
[Link](1, 10)
datetime
from datetime import datetime
[Link]()

6. Special Variable __name__


Every module has a built-in variable __name__.
 If file runs directly → __name__ = "__main__"
 If file is imported → __name__ = module_name

21 | P a g
e
Python Programming
Example
if __name__ == "__main__":
print("Running directly")
else:
print("Imported")
Used to separate testing code from main logic.

7. Advantages of Modules
 Reusable code
 Better organization
 Easy debugging
 Avoids duplication
 Faster development
 Supports team collaboration

22 | P a g
e
PYTHON PROGRAMMING UNIT II
Unit: 2
Python Functions
Function is structured sequence of statements written in order to achieve specific task
There are three Types of functions in Python:
There are mainly types of functions in python.
 Built-in library function: These are Standard functions in Python that are available to use.
(Python provides a lot of built-in functions that eases the writing of code. )
(Note: These Built-in-function has explained in the 1st unit)
 User-defined function: We can create our own functions based on our requirements.
 Anonymous function: which also are called lambda functions because they're not declared with the
quality def keyword. Instead, they are defined using the lambda keyword.

 User-defined function:
 A function starts with the keyword def, followed by the function name and parentheses ().
 Input values (parameters) can be placed inside the parentheses.
 The first line inside a function can be a docstring (optional), which describes what the function
does.
 The code inside the function is written after a colon : and must be indented.
 The return statement ends the function and can send a value back.
 Example: return 5 sends back 5.
 return with no value is the same as return None.

 Syntax
 In python each function is defined as
def name_of_function(list of formal parameters):
body of function

 Ex:
# A simple Python function
def max(x, y):
if(x>y):
return x
else:
return y
# calling a function
max(30, 40)

 Function Calling:
 Defining a function gives it a name, sets its parameters, and organizes the code.
 After a function is defined, you can use (call) it by writing its name.
 If the function needs values (parameters), pass them inside the parentheses.
 If it does not need any values, just use empty parentheses ().

 Passing Parameters/arguments
 Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
 When function is used, formal parameters are bound to actual parameters during
PYTHON PROGRAMMING UNIT II

function invocation or function call.


 The point of execution moves from point of invocation to first statement in function.
Body of function is performed & after return statement, its transferred back to code
immediately following invocation.

 Example: A simple Python function to check whether x is even or odd


def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function

evenOdd(2)
evenOdd(3)

Output:
even
odd

Default Arguments in Python


 In Python, you can give default values to function arguments.
 If you don’t provide a value when calling the function, Python uses the default value.
 If you pass a value, it replaces the default value.
Example:
def greet(name, city="Hyderabad"):
print(f"Hello {name} from {city}!")

greet("Pranesh", "Mumbai")
greet("Raj")

Output:
Hello Pranesh from Mumbai!
Hello Raj from Hyderabad!
Explanation:
 First call: "Mumbai" replaces the default "Hyderabad".
 Second call: No value for city, so the default "Hyderabad" is used.

 The return statement


There is special statement, return that can be used only within body which returns control
back to function call with some value.

Keyword Arguments
 Keyword arguments are used when calling a function by specifying the parameter names.
 They are often used with default values so that some arguments can be optional.
PYTHON PROGRAMMING UNIT II

Example:
def printName(fName, lName, reverse=False):
if reverse:
print(lName + ', ' + fName)
else:
print(fName, lName)

printName("KLE", "BCA", reverse=True)


# Output: BCA, KLE

printName("KLE", "BCA")
# Output: KLE BCA
Key Points:
 Default values allow calling the function with fewer arguments.
 Using keyword arguments, you can change the order of arguments when calling the
function.

Lambda Functions:
 A lambda function is a small anonymous function.
 It can take any number of arguments, but can only have one expression.
 Syntax:
lambda arguments : expression
The expression is evaluated and returned.
Basic Examples
1. Add 10 to an argument:
x = lambda a : a + 10
print(x(5))
Output: 15
2. Multiply two arguments:
x = lambda a, b : a * b
print(x(5,6))
Output: 30
3. Sum three arguments:
x = lambda a, b, c : a + b + c
print(x(5,6,2))
Output: 13
PYTHON PROGRAMMING UNIT II

Why Use Lambda Functions?


 Useful for short-lived anonymous functions inside other functions.
Example:
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
print(mydoubler(11)) # Output: 22

mytripler = myfunc(3)
print(mytripler(11)) # Output: 33

Lambda Functions with Built-in Functions


 Often used with map(), filter(), sorted().
1. Using with map():
Applies a function to every item in an iterable (like a list) and returns a new
iterable with the results.
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2,4,6,8,10]

2. Using with filter():


Filters elements from an iterable based on a condition. Returns only the elements
that satisfy the condition.
numbers = [1,2,3,4,5,6,7,8]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers) # Output: [1,3,5,7]

Key Takeaways
 Lambdas are good for small, throw-away functions.
 Useful with map, filter, sorted on lists or iterables.
 Limited to one expression — use def for complex logic.
 Overuse can reduce readability; use sparingly.
PYTHON PROGRAMMING UNIT II

Strings
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
 Creating and Storing Strings
 Create a string by enclosing the characters in single-quotes or double-
quotes.
Examples
str1 = 'Hello Python' str2 = "Hello Python"

 Strings are stored as individual characters in a contiguous memory


location. It can be accessed from both directions: forward and backward.
Example
The string "HELLO" is indexed as given in the below figure.

 Accessing Sting Characters


 In Python, individual characters of a String can be accessed by using the method of Indexing.
 the indexing of the Python strings starts from 0
 Use the square brackets for slicing along with the index or indices to obtain your substring. Example

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
PYTHON PROGRAMMING UNIT II

Operations on Strings:
 Concatenation
Two strings can be concatenated in Python by simply using the ‘+’ operator between
them.

s1="bca"
s2="kle"
s3=s1+s2
s4=s1+" "+s2
print(s3)
print(s4)
OUTPUT:
bcakle
bca kle

OUTPUT:
HELLO
IndexError: string index out of range

 The str()function

Python str() function returns the string version of the object.


Syntax:
str(object, encoding=’utf-8?, errors=’strict’)
Parameters:
• object: The object whose string representation is to be returned.
• encoding: Encoding of the given object.
• errors: Response when decoding fails.

# Python program to demonstrate strings


num = 100 s = str(num)

print(s, type(s)) num = 100.1

s = str(num) print(s, type(s))

OUTPUT
100 <class 'str'>
100.1 <class 'str'>
PYTHON PROGRAMMING UNIT II

Comparison
To compare two strings, to identify whether the two strings are equivalent to each other
or not, or greater or smaller than the other.
name = "KLE"
name1 = "BCA"

print("Are name and name1 equal?")


print(name == name1)

OUTPUT:
Are name and name1 equal? False

Slicing
 You can return a range of characters by using the slice syntax.
 Specify the start index and the end index, separated by a colon, to return a part of
the string.
Example:
String = 'ASTRING'

# Using slice constructor s1 = slice(3)


s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing") print(String[s1])


print(String[s2]) print(String[s3])

Output: String slicing AST


SR GITA

___
Join
The string join() method returns a string by joining all the elements of an iterable
(list, string, tuple), separated by the given separator.

Example:
text = ['Python', 'is', 'a', 'fun', 'programming', 'language']

# join elements of text with space


print(' '.join(text))

Output:
Python is a fun programming language

 Traversig Example 1:

string_name = "Pythonprogram"
# Iterate over the string
for element in string_name:
PYTHON PROGRAMMING UNIT II

print(element, end=' ')


print("\n")

output:
Pythonprogram

Example 2:
string_name = "Python"

# Iterate over index


for element in range(0, len(string_name)):
print(string_name[element])

Output:
Py t h o n

 Escape Sequences:

Escape Description Example Output


Sequence
\newline Ignores the new line in a print("Python1\ Python2 \ Python3") Python1
statement. Python2
Python3
\\ Prints a single backslash. print("\\") \
\' Prints a single quote. print('\'') '
\" Prints double quotes. print("\"") "
\a Produces a bell sound (alert). print("\a") (Bell sound)
\b Backspace (deletes previous print("Hello\b World") Hello World
character).
\f Form feed (used in printers, print("Hello\fWorld!") Hello World!
moves to next page).
\n Inserts a new line. print("Hello\nWorld!") HelloWorld!
\r Carriage return (moves cursor print("Hello\rWorld!") World!
to the beginning of the line).

 Raw and Unicode Strings


Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are
stored as 16-bit Unicode. This allows for a more varied set of characters, including special
characters from most languages in the world.
PYTHON PROGRAMMING UNIT II

 Python String Methods.

Method Description
capitalize() It capitalizes the first character of the
String.
isalnum() It returns true if the characters in the string are alphanumeric

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.

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.


isupper() It returns false if characters of a string are in Upper case, otherwise False.
lower() It converts all the characters of a string to Lower case.
upper() It converts all the characters of a string to Upper Case.
PYTHON PROGRAMMING UNIT II

File Handling
 Every computer system uses files to save things from one computation to the next.
 Python provides many facilities for creating and accessing files.

File Types
There are mainly two types of data files
1. Text file
2. Binary File

o A text file consists of human readable characters, which can be opened by any text editor.
o Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents.

Operations on Files– Create, Open, Read, Write, Close Files.


A file operation can be done in the following order.

 Open a file
 Read or write - Performing operation
 Close the file

Creating files
filehandle = open(‘kids’ , ‘w’) instructs the operating system to create a file with name
kids
& return its filehandle for the file. The argument w indicates that file is opened for writing.

Syntax:
fileobject = open(<file-name>, <access mode>, <buffering>)

Opening a file
 Python provides an open() function that accepts two arguments, file name and access mode in
which the file is accessed.
 The function returns a file object which can be used to perform various operations like reading,
writing, etc.
Example
fileptr = open("[Link]","r")

if fileptr:
print("file is opened successfully")
Read a file
To read a file using the Python script, the Python provides the read() method. The
read() method reads a string from the file. It can read the data in the text as well as a binary
format.

We can also open file for reading using argument ‘r’ and prints its contents. Python treats file
as a sequence of lines, we use for statement to iterate over file’s contents.

Example:
fileptr = open("[Link]","r")
content = [Link](10)
print(type(content))
print(content) [Link]()
PYTHON PROGRAMMING UNIT II

Write in file
 To write some text to a file, we need to open the file using the open method with one of the
following access modes.
o w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.
o a: It will append the existing file. The file pointer is at the end of the file. It creates a
new file if no file exists.

Example
fileptr = open("[Link]", "w")
[Link](Python has an easy syntax and user friendly interaction)
[Link]()

Close Files
 Once all the operations are done on the file, we must close it through our Python script
using the close() method.
 Any unwritten information gets destroyed once the close() method is called on a file object.

Syntax
[Link]()

File Access Modes


Access Description
mode
r It opens the file to read-only mode. The file pointer exists at the beginning. The
file is by default open in this mode if no access mode is passed.
rb It opens the file to read-only in binary format. The file pointer exists at the
beginning of the file.
r+ It opens the file to read and write both. The file pointer exists at the beginning of
the file.
rb+ It opens the file to read and write both in binary format. The file pointer exists
at the beginning of the file.
w It opens the file to write only. It overwrites the file if previously exists or creates
a new one if no file exists with the same name. The file pointer exists at the
beginning of the file.
wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.
w+ It opens the file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the
previously written file. It creates a new file if no file exists. The file pointer
exists at the beginning of the file.
wb+ It opens the file to write and read both in binary format. The file pointer exists
at the beginning of the file.
a It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists
with the same name.
ab It opens the file in the append mode in binary format. The pointer exists at the
end of the previously written file. It creates a new file in binary format if no file
exists with the same name.
a+ It opens a file to append and read both. The file pointer remains at the end of the
file if a file exists. It creates a new file if no file exists with the same name.
ab+ It opens a file to append and read both in binary format. The file pointer remains
at the end of the file.
PYTHON PROGRAMMING UNIT II

Common functions for accessing files are

 open(fn, 'w') fn is a string representing a file name. Creates a file for writing and returns a
file handle.
 open(fn, 'r') fn is a string representing a file name. Opens an existing file for reading and
returns a file handle.
 open(fn, 'a') fn is a string representing a file name. Opens an existing file for appending
and returns a file handle.
 [Link]() returns a string containing the contents of the file associated with file handle fh.
 [Link]() returns the next line in the file associated with the file handle fh.
 [Link]() returns a list each element of which is one line of the file associated with the
file handle fh.
 [Link](s) write the string s to the end of the file associated with the file handle fh.
 [Link](S) S is a sequence of strings. Writes each element of S to the file associated
with the file handle fh.
 [Link]() closes the file associated with the file handle fh

 File Names and Paths


Filename and path are two terminologies that are associated with file handling.
 As the name suggests, the filename refers to the name of the actual file.
 The path refers to the exact location of a file.

Methods to get filename from path in Python

There are three methods that we can use to get the filename from a given path in python.
Some of these methods use built-in functions, others use a module.
1. Split function in python
 Any path that is passed to the interpreter will be a string value.
 When a path is passed as an input, it will look like C:\Users\User1\Documents\[Link]
 We can use the built-in split function in python to split the path name. We will split the
path name at every \.
 Once we do that, we will have a tuple that contains all the words between the
slashes.
 Then we print the last element of the tuple and we get the filename with the extension.

Example:
file_path = "C:/Users/User1/Documents/[Link]"
file_name = file_path.split("/")[-1]
print(file_name)

OUTPUT:
[Link]
PYTHON PROGRAMMING UNIT II
2. OS module in python
 The OS module in python provides special functions and methods for operating system
functionality like filename extraction.
 We can use the [Link] function to get the filename from the path given by the
user.
 we can use the [Link] function to get the filename without the extension.

Example:
import os
file_path = "C:/Users/User1/Documents/[Link]"
full_name = [Link](file_path)
file_name = [Link](full_name)
print(full_name)
print(file_name[0])

Output:
[Link]
file1

3. Using the Pathlib module in python


 Besides the OS library, python also provides a library that is dedicated to handling different
types of paths provided by different operating systems.
 Inside the pathlib library, we can use the Path function to get the filename from a given path.
 The Path function has two attributes: stem and name.
 The stem attribute gives the filename without the extension
 the name attribute gives the complete filename along with the extension.

Example:
from pathlib import Path
file_path = "C:/Users/User1/Documents/[Link]"
full_name = Path(file_path).name
file_name = Path(file_path).stem
print(full_name)
print(file_name)

Output:
[Link]
file1
PYTHON PROGRAMMING UNIT II
PYTHON PROGRAMMING UNIT II
LISTS
• A list is a data structure in Python that is a mutable, ordered sequence of
elements. List is a data structure of collection of elements.
• Lists are defined using square brackets with items separated by commas.

• Mutable: lists are mutable, meaning we can change their values after they
are created.
• Ordered: lists maintains the order in which the elements were added to it.
• Indexing: we can access the elements of a list by their index.
• Slicing: we can extract a subset of elements from a list using slicing which
uses colon to separate a start and end indices.
Creating lists: different ways to create a list in python
1. Using square brackets: we can create a list by enclosing a comma-
separated sequence of values inside square brackets.
For example: my_list = [1, 2, 3, 4, 5]

2. Using list() function: we can create a list by passing a sequence of values


to the list() function.
For example: my_list = list((1, 2, 3, 4, 5))
Creating lists: different ways to create a list in python
3. Using list comprehension: we can create a list using a list comprehension,
which is a very concise way to create a new list by performing an operation on
each item in the existing list. List comprehension is considerably faster than
processing a list using the for loop.
For example: my_list = [x * 2 for x in range(5)]

4. Using range() function: we can create a list of sequential numbers using


the range() function and then convert it to a list using list() function.
For example: my_list = list(range(1,6))
Operations on Lists:
1. Indexing: we can access an individual item in a list using its index value,
which starts at 0.
Example: to access first item in a list.
my_list = [1, 2, 3, 4, 5]
print(my_list(0)) #1

2. Slicing: we can create a new list that contains a subset of the items in the
original list by using slicing. Slicing uses a colon to separate the start and stop
value. Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) #[2, 3, 4]
Operations on Lists:
3. Concatenation: we can combine 2 or more lists into a single list using
concatenation, which uses + operator. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # [1, 2, 3, 4, 5, 6]

4. Repetition: we can create a new list that contains multiple copies of the
items in the original list using repetition, which uses * operator. Example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) #[1, 1, 1, 2, 2, 2, 3, 3, 3]
Operations on Lists:
5. Length: we can determine the number of items in a list using the len()
function. Example:
mylist = [1, 2, 3, 5, 7]
print(len(mylist)) #5

6. Membership: we can check if an item is in a list using the in keyword.


Example:
my_list = [1, 2, 3]
print(2 in my_list) #True
print(4 in my_list) #False
Operations on Lists:
7. Sorting: we can sort a list in ascending or descending order using the sort(0 method.
Example:
mylist = [3, 2, 1, 4]
[Link]()
print(mylist) # [1, 2, 3, 4]
[Link](reverse=True)
print(mylist) # [4, 3, 2, 1]

8. Reversing: we can reverse the order of items in a list using the reverse() method.
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # [3, 2, 1]
Built-in Functions on Lists:
1. len() 8. count()
2. max() 9. index()
3. min() 10. append()
4. sum() 11. extend()
5. sorted() 12. insert()
6. reversed() 13. remove()
7. list() 14. pop()
15. clear()
Built-in Functions on Lists:
1. len(): This function returns the number of items in a list. Example:
my_list = [1, 3, 2]
print(len(my_list)) #3

2. max(): This function returns the maximum value in a list. Example:


my_list = [1, 3, 2]
print(max(my_list)) #3
my_list2 = [‘abc’, ‘xyz’, ‘pqr’]
print(max(my_list2)) # ‘xyz’
Built-in Functions on Lists:
3. min(): This function returns the minimum value in the list. Example:
my_list = [1, 3, 2, -1]
print(min(my_list)) # -1

4. sum(): This function returns the sum of all the elements in a list. Example:
my_list = [1, 3, 2]
print(sum(my_list)) #3
5. list(): Using list() function, we can convert a sequence (tuple, string) into list.
Example:
tuple = (1, 2, 3, 4)
my_list = list(tuple)
print(my_list) # [1, 2, 3, 4]
Built-in Functions on Lists:
6. sorted(): This function returns a sorted order of list in ascending order.
Example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list)) # [1, 2, 3]

7. reversed(): This function returns reverse iterator of the list. Example:


my_list = [1, 3, 2]
reversed_list = list(reversed(my_list))
print(reversed_list) # [3, 2, 1]
Built-in Functions on Lists:
8. count(e): This function returns the number of occurrences of a specified
element in a list. Example:
my_list = [1, 2, 3, 4, 5, 1]
count = my_list.count(1)
print(count) #2

9. index(e): This function returns the index of the first occurrence of a


specified element in the list. Example:
my_list = [1, 3, 2, 5, 7]
index = my_list.index(3)
print(index) #1
Built-in Functions on Lists:
10. append(e): This function adds an element to the end of the list. Example:
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list) # [1, 2, 3, 4, 5, 6]

11. extend(e): This function adds the elements of another list to the end of the
list. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
[Link](list2)
print(list1) # [1, 2, 3, 4, 5, 6]
Built-in Functions on Lists:
12. insert(i,e): This function inserts an element at a specified position in the
list. Example:
my_list = [1, 2, 3, 4]
my_list.insert(0, 5)
print(my_list) # [5, 1, 2, 3, 4]
13. remove(e): This function removes the first occurrence of a specified
element in the list. Example:
numbers = [50, 10, 20, 30, 40, 50]
[Link](30)
print(numbers) # [50, 10, 20, 40, 50]
[Link](50)
print(numbers) # [10, 20, 40, 50]
Built-in Functions on Lists:
14. pop(): Using this function element can be removed from the list by specifying the
index value. If the indexed item is not specified then the last item will be deleted
from the list . Example:
my_list = [11, 12, 13, 14, 15]
removed_element = my_list.pop(1)
print(removed_element) # 12
removed_element = my_list.pop()
print(removed_element) # 15

15. clear(): This function removes all the elements from list. Example:
my_list = [1, 3, 2, 5, 7]
my_list.clear()
print(my_list) #[]
Nested Lists:
A Nested list is a list that contains another list as its elements. The elements of
a nested list can be accessed using multiple indices.
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, my_list is a list that contains three other lists as its
elements. The first element is [1, 2, 3], the second element is [4, 5, 6] and last
element is [7, 8, 9].
We can access the elements of a nested list using multiple indices. For
example,
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(my_list[0][0]) #1
print(my_list[1][2]) #6
print(my_list[2]) # [7, 8, 9]
DICTIONARIES
• Creating Dictionaries;
• Operations on Dictionaries;
• Built-in Functions on Dictionaries;
• Dictionary Methods;
• Populating and Traversing Dictionaries.
DICTIONARIES
• Creating dictionaries:

Ex1: dict = {1: ‘C', 2: ‘C++', 3: ‘Python'}


print(dict)
Output: {1: 'C', 2: 'C++', 3: 'Python'}

Ex2: dict1 = { "brand": "Ford", "model": "Mustang", "year": 1964 }


print(dict1)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items - Data Types
• The values in dictionary items can be of any data type.
• Example: String, int, boolean, and list data types:

Ex1: dict1 = {“brand”: ‘Ford',


“Model”: ‘Mustang',
“year”: 1964,
“colors”: [“red”, “white”, “blue”]}
print(dict)
Operations on Dictionaries

Accessing Dictionary Values


• A value is retrieved from a dictionary by specifying its corresponding key
in square brackets; dictionary_name[“key”]
• If you refer to a key that is not in the dictionary, Python raises an
exception: KeyError.
Example :
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}

print(“Printing Employee Data .... ")

print("Dictionary is", Employee)

print("Name of the employee is", Employee["Name"])

print("Age:", Employee["Age"])

print("Salary:", Employee["salary"])

print("Company:", Employee["Company"])
1. # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

2. # Adding elements to dictionary one at a time


Dict[1] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("Dictionary after adding 3 elements: ")
print(Dict)
3. # Adding set of values with a single key.
The emp_ages doesn’t exist to dictionary.

Dict[“emp_ages”] = [20, 33, 30]


print(Dict)

4. # Updating existing key’s value.

Dict[3] = ‘Rocky'
print("Dictionary after updating: ")
print(Dict)
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[1] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("Dictionary after adding 3 elements: ")
print(Dict)

Dict[“emp_ages”] = [20, 33, 30]


print(Dict)

# Updating existing key’s value.


Dict[3] = ‘Rocky'
print("Dictionary after updating: ")
print(Dict)
Removing elements from Dictionary
• We use del statement to remove/delete an element from the dictionary.
• For example,

Employee = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


del Employee["Name"]
print(Employee)

del Employee
print(Employee)
Checking for existence of keys in Dictionary
• We use in keyword check existence of key in the dictionary.
• For example,

Employee = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print(“Name” in Employee)

del Employee["Name"]
print(“Name” in Employee)
Looping over keys or values in dictionary
• We can loop through in dictionary for keys or values.
• For example,

Employee = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


for key in Employee:
print(key)

for value in [Link]():


print(vale)
Built-in Functions on Dictionaries
1. len()

2. keys()

3. values()

4. items()

5. get()

6. pop()

7. sorted()
Dictionary Methods
1. clear()

2. copy()

3. update()

4. pop()

5. popitem()

6. get()

7. items()

8. keys()
Dictionary Methods
1. clear() : It removes all the key-value pairs from the dictionary.

Emp = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


[Link]()
print(Emp)

print([Link]())

#{}

# None
Dictionary Methods
2. copy() : It returns a shallow copy of the dictionary.

Emp = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


New_Emp = [Link]()
print(New_Emp)

# {'Name': 'Dev', 'Age': 20, 'Salary': 45000, 'Company': 'WIPRO'}


Dictionary Methods
3. update() : It adds the key-value pairs from one dictionary to another. If a key
already exists in the dictionary, then its value is updated.

Emp1 = {"Name": "Dev", "Age": 20}


Emp2 = {“Salary":45000, "Company":"WIPRO"}

[Link](Emp2)

print(Emp1)

# {'Name': 'Dev', 'Age': 20, 'Salary': 45000, 'Company': 'WIPRO'}


Dictionary Methods
4. pop() : It removes the key-value pair associated with the specified key and
returns the value.

Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print([Link](“Salary”))

print(Emp1)

# 45000
# {'Name': 'Dev', 'Age': 20, 'Company': 'WIPRO'}
Dictionary Methods
5. popitem() : It removes the item (key-value pair) inserted into the dictionary.
The removed item is the return value of the popitem() method, as a tuple.
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print([Link]())

print(Emp1)

# ('Company', 'WIPRO')
# {'Name': 'Dev', 'Age': 20, 'Salary': 45000}
Dictionary Methods
6. get() : It returns the value of the specified key. If the key does not exist, it
returns the specified default value (None).
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print([Link](“Age”))

# 20
Dictionary Methods
7. items() : It returns a list of all the key-value pairs in a dictionary as tuples.

Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print([Link]())

# dict_items([('Name', 'Dev'), ('Age', 20), ('Salary', 45000), ('Company', 'WIPRO')])


Dictionary Methods
8. keys() : It returns a list of all the key in a dictionary.

Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print([Link]())

# dict_keys(['Name', 'Age', 'Salary', 'Company'])


Built-in Functions / Dictionary Methods
1. len() 7. sorted()
2. keys() 8. clear()
3. values() 9. copy()
4. items() 10. update()
5. get() 11. popitem()
6. pop()
Populating and Traversing(Iterating) Dictionaries
• Populating a dictionary in Python is simply a matter of assigning values to
keys using the key-value syntax. Here’s an example of creating a dictionary
with some data;
• dict1 = {
"Name": "Dev",
"Age": 20,
“Salary":45000,
"Company":"WIPRO“
}
Populating and Traversing(Iterating) Dictionaries
• To Traverse or to Iterate over a dictionary in Python is, to use a for loop.
There are several ways to iterate over the keys, values or items (key-value) of
a dictionary in Python. Example;

• Iterating over keys,


• Iterating over values, and
• Iterating over items.
Employee = {"Name": "Dev", "Age": 20, "salary":45000, "Company":"WIPRO"}
#Iterating over keys,
for key in Employee:
print(key)
#Iterating over values,
for value in [Link]():
print(value)
#Iterating over items
for key, value in [Link]():
print(key, value)
#Iterating/Traversing: Python program example;
Employee = {"Name": "Dev", "Age": 20, "salary":45000, "Company":"WIPRO"}

for i in Employee:
print(i)
for i in Employee:
print(Employee[i])

for i in [Link]():
print(i)
for i in [Link]():
print(i)

print([Link]())
print([Link]())
TUPLES
• Creating Tuples;
• Operations on Tuples;
• Built-in Functions on Tuples;
• Tuple Methods.
Tuples
• A Tuple is an ordered collection of elements, similar to a list. However tuples
are immutable, meaning that their values cannot be changed once they are
created.
• Tuple elements are enclosed within parentheses and separated by commas.

• A tuple in Python is similar to a list. The difference between the two is that
we cannot change the elements of a tuple once it is assigned whereas we
can change the elements of a list.
Creating a Tuple
• A Tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.

• A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).

• Syntax : tuple_name = (value1, value2, value3, ………………….)


Creating a Tuple: Different types of tuples
# Empty tuple # tuple with mixed datatypes
my_tuple = () my_tuple = (1, "Hello", 3.4)
print(my_tuple) print(my_tuple)

# Tuple having integers # nested tuple


my_tuple = (1, 2, 3) my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple) print(my_tuple)
Create a Python Tuple With one Element
• In Python, creating a tuple with one element is a bit tricky. Having one
element within parentheses is not enough.
• We will need a trailing comma to indicate that it is a tuple,
• var1 = ("hello")

var1 = ("Hello") # string • print(type(var1)) # <class 'str'>


• # Creating a tuple having one element
var2 = ("Hello",) # tuple
• var2 = ("hello",)
• print(type(var2)) # <class 'tuple'>
• # Parentheses is optional
• var3 = "hello",
• print(type(var3)) # <class 'tuple'>
Operations on Tuples
• Indexing, Slicing, Concatenation, Repetition, Length, Membership test,
Iteration.
1. Indexing: We can use the index operator [ ] to access an item in a tuple,
where the index starts from 0.
• Example: my_tuple = (1, 2, ‘a’, ‘b’, ‘c’)
print(my_tuple[2])

# prints - a
Operations on Tuples
2. Negative Indexing: Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last item and so on. For
example;

# accessing tuple elements using negative indexing


letters = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')

print(letters[-1]) # prints ‘n'


print(letters[-6:-2]) # prints ('p', ‘y', ‘t', ‘h‘)
Operations on Tuples
3. Slicing: We can access a range of items in a tuple by using the slicing operator
colon :
my_tuple = ('p', ‘y', ‘t', ‘h', ‘o', ‘n', ‘p', ‘r', ‘o‘, ‘g’, ‘r’, ‘a’, ‘m’)

# elements 2nd to 4th index


print(my_tuple[1:4]) ('y', 't', 'h')

# elements beginning to some element


print(my_tuple[:-7]) ('p', 'y', 't', 'h', 'o', 'n')

# elements 8th to end


print(my_tuple[7:]) ('r', 'o', 'g', 'r', 'a', 'm')

# elements beginning to end


print(my_tuple[:]) ('p', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'o', 'g', 'r', 'a', 'm')
Operations on Tuples
4. Concatenation: We can concatenate two tuples using + operator. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
letters2 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
letters3 = letters1 + letters2
print(letters3)
# ('p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n')
Operations on Tuples
5. Repetition: We can repeat a tuple using the * operator. For example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
letters2 = letters1 * 3
print(letters2)
# ('p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n')

6. Length: We can find the length of a tuple using the len() function. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print(len(letters1))
#6
Operations on Tuples
7. Membership test: We can check if an element is present in a tuple using the
in operator. For example;
my_tuple = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print( ‘p’ in my_tuple) #True
print( ‘g’ in my_tuple) #False
8. Iteration: We can iterate over the elements of a tuple using a for loop. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
p
for elements in letters1: y
t
print(elements) h
o
n
Built-in Functions on Tuples
• len()
• max()
• min()
• sum()
• sorted()
Built-in Functions on Tuples
• len() – returns the number of elements in a tuple.

• max() – returns the largest element in a tuple.

• min() – returns the smallest element in a tuple.

• sum() – returns the sum of all the elements from a


tuple. (only numeric)

• sorted() – returns a sorted list of element in a tuple.


Built-in Functions on Tuples: Example
my_tuple = (4, 5, 6, 1, 2, 3)

print(len(my_tuple)) #6

print(max(my_tuple)) #6

print(min(my_tuple)) #1

print(sum(my_tuple)) # 21

print(sorted(my_tuple)) # [1, 2, 3, 4, 5, 6]
Tuple Methods
• Tuples are immutable in Python, which means they cannot be modified once
they are created. As a result, there are only two methods defined for tuples;
1. count()
2. index()
• 1. count(): This method takes one argument and returns the number of
times that argument appears in the tuple:
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(count(1))
#4
Tuple Methods
• 2. index(): This method takes one argument and returns the index of the
first occurrence of that argument in the tuple. If the argument is not found,
it raises ValueError.
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(index(4)) #3
print(my_tulpe(index(1)) #0

Note: These methods do not modify the original tuple. If you wish to modify a
tuple, you must first convert it to a list, make changes and then convert it back
to a tuple.
PYTHON PROGRAMMING UNIT II

Unit: 3
Exception Handling
 An exception is defined as something that does not conform to the norm and therefore
somewhat rare.
 Exception handling is mechanism provided to handle the run-time errors or exceptions
which often disrupt the normal flow of execution.
 Most common types of exceptions are: TypeError, IndexError, NameError and ValueError.
 When an exception is raised that causes program to terminate, we say that an unhandled
exception has been raised

Process of Exception Handling


 There are 4 keywords used for exception handling mechanism. They are try, except,
raise and finally.
 If you feel that block of code is going to cause an exception than such code you need to
embed in a try block.
 Every try block should be followed by one or more except block(s). It is the place, where
we catch the exception.
 In some cases, we need to manually raise an exception , its done through raise keyword
followed by the exception name.
 The finally block will include house-keeping task or cleanup job. Its optional block,
which always get executed.
 Try-else block: if the exception has not occurred than control will be redirected to else
block after try block.

What are Exceptions?


 An exception is a runtime error that disrupts the normal flow of a program.
 When an error occurs during execution, an exception is “raised”.
 If not handled, it can terminate the program.
 Examples of built-in exceptions:
o ZeroDivisionError – dividing by zero
o ValueError – invalid type conversion
o IndexError – accessing invalid list index
o FileNotFoundError – trying to open a file that doesn’t exist

1
PYTHON PROGRAMMING UNIT II

Note:
Exceptions let programs detect and respond to unexpected situations instead of crashing.

2. Handling Exceptions
 Python provides structured exception handling using the following blocks:

1. try,
2. except,
3. else, and
4. finally.

(a) try block


 Contains code that might raise an exception.
 Python “tries” this code first.
Ex:
try:
result = 10 / 0 # risky operation

2
PYTHON PROGRAMMING UNIT II

(b) except block


 Catches and handles specific exceptions.
 You can have multiple except blocks for different exceptions.
 A general except can catch all exceptions.
Ex:
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except:
print("Some error occurred")

(c) else block


 Runs only if no exception occurs in the try block.
 Useful for code that depends on successful execution of try.
Ex:
try:
result = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print(f"Result: {result}")

(d) finally block


 Always executes, whether an exception occurs or not.
 Typically used for cleanup, like closing files or releasing resources.
Ex: try:
file = open("[Link]", "r")
except FileNotFoundError:
print("File not found!")
finally:
if 'file' in locals() and not [Link]:
[Link]()
print("File closed")

3
PYTHON PROGRAMMING UNIT II

3. Raising Exceptions
 You can manually raise an exception using the raise keyword.
 This is useful for enforcing rules or signaling errors in your code.
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
my_age = validate_age(-5)
except ValueError as e:
print(f"Validation Error: {e}")

4. User-Defined Exceptions
 You can create custom exceptions by subclassing the built-in Exception class.
 This allows domain-specific or meaningful error messages.

class MyCustomError(Exception):
"""Custom exception for specific errors"""
pass

def process_data(data):
if not data:
raise MyCustomError("Input data cannot be empty.")
print("Data processed successfully")

try:
process_data([])
except MyCustomError as e:
print(f"Custom Error: {e}")

Example:
def divide_numbers(a, b):

4
PYTHON PROGRAMMING UNIT II

try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Division result:", result)
finally:
print("Executing the finally block.\n")

divide_numbers(10, 2)
divide_numbers(10, 0)

OUTPUT:

5. Note:

Block / Feature Description


Exception Runtime error that disrupts program flow
try Code that may cause an exception
except Handles the exception
else Runs if no exception occurs
finally Always runs (cleanup)
raise Manually triggers an exception
User-defined Custom exceptions created by programmer

5
PYTHON PROGRAMMING UNIT IV

Object Oriented Programming


 Classes and Objects  Constructor Method
Class A constructor is a special type of method (function)
It is a logical entity that has some specific attributes which is used to initialize the instance members of
and methods. The class can be defined as a the class.
collection of objects. Constructors can be of two types.
Object 1. Parameterized Constructor
The object is an entity that has state and behavior. It
may be any real-world object like the mouse, 2. Non-parameterized Constructor
keyboard, chair, table, pen, etc.
 Creating the constructor in python
 Creating Classes and Objects The method the init () simulates the constructor
 Creating Classes of the class. This method is called when the class is
A class can be created by using the keyword class, instantiated. It accepts the self-keyword as a first
followed by the class name. The syntax to create a argument which allows accessing the attributes or
class is given below. method of the class.
Syntax Example
class Employee:
class ClassName:
def init (self, name, id):
#statement_suite
[Link] = id
Example:
[Link] = name
class Employee:
id = 10 def display(self):
name = "Devansh" print("ID: %d \nName: %s" % ([Link], [Link]))
def display (self):
print([Link],[Link]) emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
 Creating Object
A class needs to be instantiated if we want to use the # accessing display() method to print employee 1 information
class attributes in another class or method. A class [Link]()
can be instantiated by calling the class using the # accessing display() method to print employee 2 information
class name.
[Link]()
Syntax
Output:
<object-name> = <class-name>(<arguments>)
ID: 101
Example Name: John
class Employee: ID: 102
id = 10 Name: David

name = "John"
def display (self):
print("ID: “,[Link])
print("Name: “,[Link]))
# Creating a emp instance of Employee class
emp = Employee()
[Link]()

4
PYTHON PROGRAMMING UNIT IV

 Classes with Multiple Objects print("Enter values of object 1 ")


We can also create multiple objects from a single [Link]()
class. For example. print("Enter values of object 2 ")
# define a class [Link]()
class Employee: print("Values of object 1 ")
# define an attribute [Link]()
employee_id = 0 print("Values of object 2 ")
[Link]()
# create two objects of the Employee class obj3 = [Link](obj2)
employee1 = Employee() print("Values of object 3 (sum object) ")
employee2 = Employee() [Link]()

# access attributes using employee1 Output:


[Link] = 1001
print("Employee ID:", [Link]) Enter values of object 1
Enter value of x : 43
Enter value of y : 65
# access attributes using employee2 Enter values of object 2
[Link] = 1002 Enter value of x : 34
Enter value of y : 65
print("Employee ID:", [Link])
Values of object 1
Output value of x = 43 value of y = 65
Values of object 2
value of x = 34 value of y = 65
Employee ID: 1001
Values of object 3 (sum object)
Employee ID: 1002 value of x = 77 value of y = 130

 Objects as Arguments, Objects as Return  Inheritance


Inheritance - acquiring properties of super class into
Values
sub class. It is also called as base- derived class or
Python allows its programmers to pass objects to
parent-child class.
method. And also return objects from a method.
Here is a program to illustrate this, Syntax
class TwoNum: class derived-class(base class):
def GetNum(self): <class-suite>
self. x = int(input("Enter value of x : "))  Single and Multiple Inheritance
self. y = int(input("Enter value of y : ")) Single Inheritance Single inheritance allows a
derivate class to inherit properties of one parent
def PutNum(self): class, and this allows code reuse and the introduction
print("value of x = ", self. x,"value of y = ", of additional features in existing code.
self. y, )

def Add(self,T):
R=TwoNum()
R. x=self. x+T. x
R. y=self. y+T. y
return R

obj1 = TwoNum()
obj2 = TwoNum()

5
PYTHON PROGRAMMING UNIT IV

Example: Example:
class Parent1:
class Calculation1:
def func1(self):
print ("function is defined inside the parent class.") def Summation(self,a,b):
return a+b;
class Child1(Parent1):
class Calculation2:
def func2(self):
print ("function is defined inside the child class.") def Multiplication(self,a,b):
# Driver's code return a*b;
object = Child1()
object.func1() class Derived(Calculation1,Calculation2):
object.func2() def Divide(self,a,b):
return a/b;
Output: d = Derived()

function is defined inside the parent


print([Link](10,20))
class. print([Link](10,20))
function is defined inside the child print([Link](10,20))
class.

Output:
Multiple Inheritance If a class is able to be created
30
from multiple base classes, this kind of Inheritance is 200
known as multiple Inheritance. When there is multiple 0.5
Inheritance, each of the attributes that are present in the
classes of the base has been passed on to the class that is  Multilevel and Multipath Inheritance
derived from it. Multi-level inheritance is archived when a derived
class inherits another derived class. There is no limit
on the number of levels up to which, the multi-level
inheritance is archived in python.

Syntax
class Base1:
<class-suite>
class Base2:
<class-suite> Syntax
. class class1:
. <class-suite>
. class class2(class1):
class BaseN: <class suite>
<class-suite> class class3(class2):
class Derived(Base1, Base2, ........ BaseN): <class suite>
<class-suite> .
.

6
PYTHON PROGRAMMING UNIT IV

Example # Derivied class2


class Animal: class Child_2(Parent1):
def speak(self): def func_3(self):
print("Animal Speaking") print ("This function is defined inside the child 2.")
#The child class Dog inherits the base class Animal
class Dog(Animal): # Driver's code
def bark(self): object1 = Child_1()
print("dog barking") object2 = Child_2()
#The child class Dogchild inherits another child class Dog object1.func_1()
class DogChild(Dog): object1.func_2()
def eat(self): object2.func_1()
print("Eating bread...") object2.func_3()
d = DogChild()
[Link]() Output:
[Link]() This function is defined inside the parent
[Link]() class.
This function is defined inside the child 1.
This function is defined inside the parent
Output: class.
This function is defined inside the child 2.
dog barking
Animal Speaking  Encapsulation
Eating bread...
This is the concept of wrapping data and methods
Multipath Inheritance that work with data in one unit. This prevents data
If multiple derived classes are created from the same modification accidentally by limiting access to
base, this kind of Inheritance is known as hierarchical variables and methods.
inheritance or Multipath Inheritance. In this instance, we  Private Instance Variables
have two base classes as a parent (base) class as well as  Class members who have been declared private
two children (derived) classes. should not be accessed by anyone outside the class
or any base classes. Python does not have Private
instance variable variables that can be accessed
outside of a class.
 To define a private member, prefix the member's
name with a double underscore " ".
Example:
class Base1:
class Parent1: def init (self):
def func_1(self): self.p = "Javatpoint"
print ("This function is defined inside the parent class.") self. q = "Javatpoint"
# Creating a derived class
# Derived class1 class Derived1(Base1):
class Child_1(Parent1): def init (self):
def func_2(self): # Calling constructor of
print ("This function is defined inside the child 1.") # Base class

7
PYTHON PROGRAMMING UNIT IV

Please enter the value: Tpoint


Base1. init (self)
: JavaTpoint
print("We will call private member of base class")
print(self. q)
# Driver code Example 2:
obj_1 = Base1()
print(obj_1.p) class complex_1:
def init (self, X, Y):
Output:
self.X = X
Javatpoint self.Y = Y

 Polymorphism # Now, we will add the two objects


Polymorphism refers to having multiple forms. def add (self, U):
Polymorphism is a programming term that refers to return self.X + U.X, self.Y + U.Y
the use of the same function name, but with different
signatures, for multiple types.
Object_1 = complex_1(23, 12)
 Operator Overloading Object_2 = complex_1(21, 22)
The operator overloading in Python means
Object_3 = Object_1 + Object_2
provide extended meaning beyond their
print (Object_3)
predefined operational meaning.
Such as, we use the "+" operator for adding two
Output:
integers as well as joining two strings or
merging two lists. (44, 34)

Example 1:

class example:
def init (self, X):
self.X = X

# adding two objects


def add (self, U):
return self.X + U.X
object_1 = example( int( input( print ("Please enter
the value: "))))
object_2 = example( int( input( print ("Please enter
the value: "))))
print (": ", object_1 + object_2)
object_3 = example(str( input( print ("Please enter
the value: "))))
object_4 = example(str( input( print ("Please enter
the value: "))))
print (": ", object_3 + object_4)

Output:

Please enter the value: 23


Please enter the value: 21
: 44
Please enter the value: Java

You might also like