Unit 2 Python
Unit 2 Python
P.SARAVANAKUMAR
Assistant Professor
UNIT-II: Functions
Built-in functions in Python
It’s a Collection of pre-defined functions that are
always available for use without requiring any
imports. These functions provide fundamental
functionalities for various operations, including:
Type Conversion and Creation:
Functions
like int(), float(), str(), list(), tuple(), dict(), set
(), bool() are used to convert between data
types or create new instances of these types.
Cont…
Mathematical Operations:
Functions such
as abs(), round(), min(), max(), sum(), pow(), div
mod() facilitate common mathematical
calculations.
Input/Output:
The print() function is used to display output,
and input() is used to get user input.
Iterables and Iterators:
Functions like
len(), range(), enumerate(), zip(), sorted(), rever
sed(), all(), any(), iter(), next() are used for
working with sequences and iterators.
Cont…
Object Inspection and Manipulation:
Functions
as type(), id(), dir(), getattr(), setattr(), hasattr(), isinsta
nce(), issubclass() provide ways to inspect and
manipulate objects and their attributes.
Utility Functions:
Other useful built-in functions include help() for
accessing documentation, callable() to check if an object
can be called, and open() for file operations.
These built-in functions simplify coding by providing
ready-to-use solutions for common programming tasks,
reducing the need to write custom functions for basic
operations.
Commonly Used Modules
Python boasts a rich ecosystem of modules, both built-in
and third-party, that cater to diverse programming
needs. Some of the most commonly used modules
include:
Standard Library Modules (Built-in):
os: Provides functions for interacting with the operating
system, including file and directory manipulation.
sys: Offers access to system-specific parameters and
functions, such as command-line arguments and Python
interpreter details.
math: Contains mathematical functions and constants
for numerical operations.
Cont…
datetime: Enables handling and manipulation of
dates and times.
random: Generates pseudo-random numbers.
json: Facilitates encoding and decoding of JSON
data.
re: Provides support for regular expressions for
pattern matching in strings.
csv: Handles reading from and writing to CSV
(Comma Separated Values) files.
collections: Offers specialized container datatypes
like defaultdict, Counter, and deque.
logging: Provides a flexible framework for emitting
log messages.
Cont…
Third-Party Modules (Installed via pip):
NumPy: Fundamental for numerical computing,
especially with arrays and matrices, crucial for
scientific computing and data science.
Pandas: Provides powerful data structures and data
analysis tools, particularly for tabular data
(DataFrames).
Matplotlib: A comprehensive library for creating
static, animated, and interactive visualizations in
Python.
Scikit-learn: A robust library for machine learning,
offering various algorithms for classification,
regression, clustering, and more.
Requests: Simplifies making HTTP requests to
interact with web services and APIs.
Cont…
Flask / Django: Popular frameworks for web
development, with Flask being lightweight and
Django offering a full-featured approach.
BeautifulSoup: Used for web scraping, parsing
HTML and XML documents.
Selenium: Automates web browser interactions
for testing or data extraction.
Pillow (PIL Fork): Provides image processing
capabilities, including image manipulation and
analysis.
TensorFlow / PyTorch: Widely used libraries for
deep learning and neural network development.
Function Definition
In Python, functions are blocks of reusable code designed to
perform a specific task. They enhance code organization,
readability, and reusability.
Function Definition:
A function is defined using the def keyword, followed by the
function name, parentheses (), and a colon :. The code block
within the function is indented. Parameters, if any, are placed
inside the parentheses.
def my_function(parameter1, parameter2):
""" This is a docstring explaining what the function does. """
# Function body: statements to be executed
result = parameter1 + parameter2
return result # Optional: returns a valuedef
my_function(parameter1, parameter2): """ This is a
docstring explaining what the function does. """ #
Function body: statements to be executed result =
parameter1 + parameter2 return result # Optional: returns
a value
Calling the Function
To execute a defined function, you call it by its name
followed by parentheses (). If the function requires
arguments (values for its parameters), they are
passed inside the parentheses during the call.
Python
# Calling a function without arguments
my_function_without_args()
Example:
def greet(name):
print(f"Hello, {name}!") # This function performs an action (printing)
but doesn't return a value.
my_function()
# print(local_var) # This would raise a
NameError
Cont…
Enclosing (E): Variables defined in an outer
(enclosing) function when dealing with nested
functions. An inner function can access
variables from its enclosing scope.
def outer_function():
enclosing_var = "I am in the enclosing scope"
def inner_function():
print(enclosing_var)
inner_function()
outer_function()
Cont…
Global (G): Variables defined outside any
function, typically at the top level of a script or
module. They are accessible from any part of the
program.
global_var = "I am global“
def another_function():
print(global_var)
another_function()
print(global_var)
Built-in (B): Contains Python's pre-defined
functions and objects (e.g., print(), len()). These
are globally available without explicit definition.
Default Parameters
Default arguments in Python functions provide a way to assign
a default value to a parameter, which will be used if no
argument is provided for that parameter during the function
call.
Here's an example illustrating default arguments:
def greet(name, greeting="Hello"):
""" Greets a person with a customizable greeting. Args: name
(str): The name of the person to greet. greeting (str, optional):
The greeting message. Defaults to "Hello". """
print(f"{greeting}, {name}!")
Benefits:
Clarity: Makes function calls easier to understand,
especially for complex functions.
Flexibility: Allows you to pass arguments in any order.
Default Values: Works seamlessly with parameters that
have default values, allowing you to selectively override
them.
*args and **kwargs
In Python, *args and **kwargs are special
syntaxes used in function definitions to allow a
variable number of arguments to be passed to a
function.
1. *args (Arbitrary Positional Arguments):
*args allows a function to accept an arbitrary
number of non-keyworded (positional) arguments.
When *args is used as a parameter in a function
definition, all the positional arguments passed to
the function are collected into a tuple.
The name "args" is a convention; you could
use *anything as long as it's prefixed with a single
asterisk.
Cont…
Example:
def sum_all_numbers(*numbers):
total = 0
for num in numbers:
total += num
return total
display_info(name="Alice", age=30,
city="New York")
# Output:
# name: Alice
# age: 30
# city: New York
Python command-line
arguments
Python command-line arguments are
parameters passed to a Python script when it
is executed from the command line
interface. These arguments allow users to
customize the script's behavior or provide
input data without modifying the source code.
Accessing Command-Line Arguments:
The most basic way to access command-line
arguments in Python is through
the sys.argv list, which is part of
the sys module.
Cont…
import sys
# sys.argv is a list containing all command-
line arguments
# sys.argv[0] is always the script's name
# Subsequent elements (sys.argv[1],
sys.argv[2], etc.) are the arguments passed
print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
if len(sys.argv) > 1:
print(f"First argument: {sys.argv[1]}")
else:
print("No arguments provided.")
UNIT-II: Functions
Creating Strings:
In Python, strings are sequences of characters used
to represent text. They are immutable, meaning once
created, their content cannot be changed.
Strings can be created by enclosing characters
within various types of quotes:
Single Quotes: Used for simple, single-line strings.
my_string = 'Hello, Python!'
Double Quotes: Functionally equivalent to single
quotes, often used for consistency or when the string
contains single quotes.
another_string = "Python is powerful."
quoted_string = "He said, 'Hello!'"
Cont…
Triple Quotes (Single or Double): Used for multi-
line strings or strings that contain both single and
double quotes without needing escape
characters. They are also commonly used for
docstrings (documentation strings).
multi_line_string = '''This is a multi-line string.''‘
doc_string = """This function calculates the sum of
two numbers."""
str() Constructor: The built-in str() function can be
used to create an empty string or to convert other
data types into strings.
= str()
number_as_string = str(123)
Storing Strings:
Once created, strings are stored in memory and
assigned to variables for later use. Python
handles the memory management for strings
automatically. When you assign a string to a
variable, the variable essentially holds a
reference to the string object in memory.
# Create and store a string in the 'name'
variable
name = "Alice“
# Create and store another string in the
'message' variable
message = "Welcome to Python!"
Python's dynamic typing means you don't need
to explicitly declare the data type of a variable
String operations
Python provides various basic operations and
methods for manipulating strings.
1. Concatenation:
Strings can be joined together using
the + operator.
str1 = "Hello"
str2 = " World"
combined_string = str1 + str2
print(combined_string) # Output: Hello World
String operations
2. Repetition:
A string can be repeated multiple times using
the * operator.
word = "Python"
repeated_word = word * 3
print(repeated_word) # Output:
PythonPythonPython
String operations
3. Indexing and Slicing:
Individual characters can be accessed using
indexing (starting from 0 for the first character),
and substrings can be extracted using slicing.
my_string = "Programming"
print(my_string[0]) # Output: P (first character)
print(my_string[2:6]) # Output: ogra (characters
from index 2 up to, but not including, 6)
print(my_string[:4]) # Output: Prog (characters
from the beginning up to, but not including, 4)
print(my_string[5:]) # Output: amming
(characters from index 5 to the end)
String operations
4. Length of a String:
The len() function returns the number of
characters in a string.
text = "Example"
length = len(text)
print(length) # Output: 7
String operations
5. Case Conversion:
Methods
like upper(), lower(), capitalize(), title(),
and swapcase() allow for changing the case of
characters within a string.
s = "PyThOn"
print(s.upper()) # Output: PYTHON
print(s.lower()) # Output: python
print(s.capitalize()) # Output: Python
print(s.title()) # Output: Python
print(s.swapcase()) # Output: pYtHoN
String operations
6. Searching and Replacing:
find() and index() locate the first occurrence
of a substring. find() returns -1 if not found,
while index() raises a ValueError.
replace() substitutes occurrences of a
substring with another.
sentence = "Learning Python is fun"
print(sentence.find("Python")) # Output: 9
print(sentence.replace("fun", "great")) #
Output: Learning Python is great
String operations
7. Splitting and Joining:
split() divides a string into a list of substrings based
on a delimiter (default is whitespace).
join() concatenates elements of an iterable (like a
list) into a single string using the string itself as a
separator.
data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits) # Output: ['apple', 'banana', 'cherry']
words = ["Hello", "Python", "World"]
joined_string = " ".join(words)
print(joined_string) # Output: Hello Python World
Accessing Characters in String
by Index Number
In Python, individual characters within a
string can be accessed using indexing, which
involves placing the character's index number
within square brackets [] following the string
variable. Python uses zero-based indexing,
meaning the first character of a string is at
index 0, the second at index 1, and so on.
1. Positive Indexing:
Positive indices start from 0 for the first character and
increment by one for each subsequent character.
my_string = "Python“
# Accessing the first character
first_char = my_string[0]
print(f"First character: {first_char}") # Output: First
character: P
# Accessing the third character
third_char = my_string[2]
print(f"Third character: {third_char}") # Output: Third
character: t
# Accessing the last character using positive indexing
last_char_positive = my_string[len(my_string) - 1]
print(f"Last character (positive index): {last_char_positive}") #
Output: Last character (positive index): n
2. Negative Indexing:
Negative indices allow access to characters from the
end of the string. The last character has an index of -
1, the second-to-last character has an index of -2, and
so on.
my_string = "Python"
# Basic slicing
print(my_string[0:6]) # Output: Python
print(my_string[7:18]) # Output: Programming
# Negative indexing
print(my_string[-11:]) # Output: Programming
print(my_string[-1]) # Output: g
Examples:
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90]
# Basic slicing
print(numbers[2:6]) # Output: [30, 40, 50, 60] (elements
from index 2 up to, but not including, index 6)
# Slicing from the beginning
print(numbers[:4]) # Output: [10, 20, 30, 40]
# Slicing to the end
print(numbers[5:]) # Output: [60, 70, 80, 90]
# Slicing with a step
print(numbers[1:8:2]) # Output: [20, 40, 60, 80] (every
second element from index 1 to 7)
# Reverse slicing using a negative step
print(numbers[::-1]) # Output: [90, 80, 70, 60, 50, 40, 30,
20, 10] (reverses the list)
print(numbers[7:2:-2]) # Output: [80, 60, 40] (from index 7
down to, but not including, index 2, with a step of -2)
Built-in Functions for Lists
Python provides several built-in functions that
can be used directly on lists without needing to
import any modules. These functions offer
convenient ways to perform common
operations.
len(), min(), max(), sum(), sorted() & list().
len(): Returns the number of elements in the
list.
my_list = [10, 20, 30, 40]
length = len(my_list)
print(length) # Output: 4
Cont…
min(): Returns the smallest element in the list. This
function requires that all elements in the list are
comparable (e.g., all numbers or all strings).
numbers = [5, 1, 9, 2]
minimum = min(numbers)
print(minimum) # Output: 1
max(): Returns the largest element in the list. Similar
to min(), elements must be comparable.
numbers = [5, 1, 9, 2]
maximum = max(numbers)
print(maximum) # Output: 9
sum(): Returns the sum of all numeric elements in the
list. This function only works with lists containing
numbers.
data = [1, 2, 3, 4]
total = sum(data)
print(total) # Output: 10
Cont…
sorted(): Returns a new sorted list from the elements of the
original list, leaving the original list unchanged. By default,
it sorts in ascending order.
unsorted_list = [3, 1, 4, 1, 5, 9, 2]
sorted_list = sorted(unsorted_list)
print(sorted_list) # Output: [1, 1, 2, 3, 4, 5, 9]
print(unsorted_list) # Original list remains unchanged: [3, 1,
4, 1, 5, 9, 2]
list(): Converts an iterable (like a tuple, string, or set) into a
list.
my_tuple = (1, 2, 3)
new_list = list(my_tuple)
print(new_list) # Output: [1, 2, 3]
my_string = "hello"
char_list = list(my_string)
print(char_list) # Output: ['h', 'e', 'l', 'l', 'o']
Lists methods
Python lists are mutable ordered sequences
that offer a rich set of built-in methods for
manipulation. Here are some common list
methods with examples:
append(element): Adds a single element to
the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Lists methods
extend(iterable): Appends all elements from
an iterable (e.g., another list, tuple) to the
end of the list.
list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4]
Lists methods
insert(index, element): Inserts an element at
a specified index.
my_list = [1, 2, 4]
my_list.insert(2, 3)
print(my_list) # Output: [1, 2, 3, 4]
remove(element): Removes the first occurrence
of a specified element from the list. Raises
a ValueError if the element is not found.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
pop(index=-1): Removes and returns the
element at the given index. If no index is
provided, it removes and returns the last
element.
my_list = [1, 2, 3]
removed_element = my_list.pop(1)
print(my_list) # Output: [1, 3]
print(removed_element) # Output: 2
clear(): Removes all items from the list, making
it empty.
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
index(element, start=0, end=len(list)): Returns
the index of the first occurrence of the
specified element. Optional start and end argu
ments can be used to limit the search.
my_list = ['a', 'b', 'c', 'a']
index = my_list.index('a')
print(index) # Output: 0
count(element): Returns the number of times
a specified element appears in the list.
my_list = [1, 2, 2, 3, 2]
count = my_list.count(2)
print(count) # Output: 3
sort(key=None, reverse=False): Sorts the
items of the list in ascending order by
default. key can be a function to customize
the sort order, and reverse=True sorts in
descending order.
my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
reverse(): Reverses the order of the elements
in the list in-place.
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
copy(): Returns a shallow copy of the list.
original_list = [1, 2, 3]
copied_list = original_list.copy()
print(copied_list) # Output: [1, 2, 3]
del statement
The del statement in Python is used to delete
objects, including variables, elements from
sequences (like lists and tuples), and key-value
pairs from dictionaries. It removes the reference
to the object from the current namespace,
potentially allowing the object to be garbage
collected if no other references exist.
1. Deleting a Variable:
x = 10
print(x) # Output: 10
del x
# print(x) # This would raise a NameError as x
is no longer defined
del statement
2. Deleting an Element from a List:
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
del my_list[2] # Deletes the element at index
2 (value 3)
print(my_list) # Output: [1, 2, 4, 5]
del statement
3. Deleting a Slice of a List:
my_list = [1, 2, 3, 4, 5, 6]
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
del my_list[1:4] # Deletes elements from
index 1 up to (but not including) index 4
print(my_list) # Output: [1, 5, 6]
del statement
4. Deleting a Key-Value Pair from a
Dictionary:
obj = MyClass("Example")
print(obj.name) # Output: Example
END