PYTHON PROGRAMMING (23UCSCC01) – UNIT - III

 

PYTHON PROGRAMMING (23UCSCC01) – UNIT - III

Functions: Function Definition – Function Call – Variable Scope and its Lifetime- Return Statement. Function Arguments: Required Arguments, Keyword Arguments, Default Arguments and Variable Length Arguments- Recursion. Python Strings: String operations- Immutable Strings - Built-in String Methods and Functions - String Comparison. Modules: import statement- The Python module – dir() function – Modules and Namespace – Defining our own modules.

 

What is a Function in Python?

A function is a block of reusable code that performs a specific task. It helps us organize code into small, manageable parts, avoid repetition, and improve clarity.

Benefits of Using Functions:

·         Modularity: Breaking down complex problems into smaller, manageable parts.

·         Reusability: Avoiding repetitive code by defining a task once and calling it multiple times.

·         Readability: Making code easier to understand and maintain.

·         Organization: Structuring code logically.


Function Definition

  • A function is defined using the def keyword, followed by the function name and parentheses ().
  • The code block inside the function is indented.

Syntax:

deffunction_name(parameters):

    # Function body

statements

 Example:

def greet(name):

        print("Hello, " + name + "!")

 

Function Call

  • After defining a function, we can call it using its name and providing required arguments.

 Syntax:

function_name(arguments)

 Example:

greet("Alice")  # Output: Hello, Alice!

 

Variable Scope and Lifetime

Scope:

The scope of a variable defines where the variable can be accessed.

  • Local Scope: Variables defined inside a function are local variables. Accessible only inside that function.
  • Global Scope: Variables defined outside any function are global variables. Accessible anywhere in the module.

Lifetime:

The lifetime of a variable is the duration for which it exists in memory.

  • Local variables: Exist while the function is executing and get destroyed when the function ends.
  • Global variables: Exist as long as the program runs.

 Example:

global_var = 10  # Global variable

 

defmy_function():

        local_var = 5  # Local variable

        print("Inside function: local_var =", local_var)

        print("Inside function: global_var =", global_var)


my_function()

print("Outside function: global_var =", global_var)

# print(local_var)  # This would cause an error because local_var is not accessible here.

 

Global Keyword Example:

count = 0  # Global variable

 

def increment():

        global count

        count += 1

        print("Count inside function:", count)

 

increment()

print("Count outside function:", count)

 

Return Statement

  • The return statement is used to send a value back from the function to the caller.
  • Once return is executed, the function terminates.

 Syntax:

deffunction_name(parameters):

    # code

    return value

 

Example:

def add(a, b):

        return a + b

 

result = add(3, 5)

print("Sum is:", result)  # Output: Sum is: 8

 

Without Return:

def greet(name):

        print("Hello, " + name + "!")

 

output = greet("Bob")

print(output)  # Output: None, because the function doesn't return anything explicitly

 

Concept

Example

Function Definition

deffunc():

Function Call

func()

Local Variable

Defined inside a function

Global Variable

Defined outside any function

Return Statement

return value

 

 Complete Example Combining All Concepts:

count = 0  # Global variable

 

defincrement_counter(step):

        global count

        count += step  # Modify global variable

        print("Inside function, count =", count)

        return count

 

print("Before function call, count =", count)

new_count = increment_counter(5)

print("After function call, count =", new_count)

 

Function Arguments

In Python, arguments are the values you pass into a function when you call it.
These values are used by the function to perform tasks or calculations.

 1. Required Arguments

These are arguments that must be provided in the correct order when calling the function.
If any required argument is missing, Python raises an error.

 

Example:

def greet(name, age):

        print(f"Hello {name}, you are {age} years old.")

 

greet("Alice", 25)  # Works fine

# greet("Alice")    # Error: missing the 'age' argument

 

 2. Keyword Arguments

Arguments can be passed by explicitly naming the parameter in the function call, allowing arguments to be provided in any order.

 

Example:

def greet(name, age):

        print(f"Hello {name}, you are {age} years old.")

 

greet(age=30, name="Bob")  # Works fine

 

 3. Default Arguments

When a function parameter has a default value, it becomes optional in the function call.
If no value is provided, the default is used.

 

Example:

def greet(name, age=18):

        print(f"Hello {name}, you are {age} years old.")

 

greet("Charlie")       # Uses default age = 18

greet("Charlie", 22)   # Overrides default with 22

 

 4. Variable Length Arguments

When you don’t know in advance how many arguments will be passed, use:

  • *args for non-keyword variable arguments (as a tuple)
  • **kwargs for keyword variable arguments (as a dictionary)

 

Example:

defmy_func(*args, **kwargs):

        print("Positional arguments (args):", args)

        print("Keyword arguments (kwargs):", kwargs)

 

my_func(1, 2, 3, name="Alice", job="Engineer")

 

Output:

Positional arguments (args): (1, 2, 3)

Keyword arguments (kwargs): {'name': 'Alice', 'job': 'Engineer'}

 

Argument Type

Usage

Required Arguments

Must be provided, in order

Keyword Arguments

Passed by name, any order

Default Arguments

Have a default value, optional in calls

Variable Length Arguments

*args, **kwargs for arbitrary numbers

 

Recursion in Python

Recursion is a programming technique where a function calls itself in order to solve a smaller version of a problem until a base condition is met.

 

 Key Concepts of Recursion:

  1. Base Case: A condition to stop the recursion, preventing an infinite loop.
  2. Recursive Case: The function calls itself with modified arguments, approaching the base case.

 

 Simple Example: Factorial Calculation

def factorial(n):

        if n == 0:

               return 1  # Base Case

        else:

               return n * factorial(n - 1)  # Recursive Call

 

print(factorial(5))  # Output: 120

 

 How It Works:

  • factorial(5) calls factorial(4), which calls factorial(3), and so on, until factorial(0) returns 1.
  • Then the recursive calls resolve: 1 * 1, 2 * 1, 3 * 2, ..., up to 5 * 24 = 120.

 

 Another Example: Fibonacci Series (nth Term)

def fibonacci(n):

        if n <= 1:

               returnn  # Base Case

        else:

               returnfibonacci(n - 1) + fibonacci(n - 2)  # Recursive Call

 

print(fibonacci(6))  # Output: 8

 

How It Works:

  • fibonacci(6) computes fibonacci(5) + fibonacci(4) → each of these calls splits further until reaching base cases (fibonacci(1) or fibonacci(0)).

 

Python String

A string in Python is a sequence of characters enclosed in single quotes (' ') or double quotes (" ").

s1 = 'Hello'

s2 = "World"

 

 String Characteristics

  • Strings are immutable → Once created, their content cannot be changed.
  • They are sequences → We can access individual characters using indexing and slicing.

 

String Operations

1 Concatenation (+)

s1 = "Hello"

s2 = "World"

result = s1 + " " + s2

print(result)  # Output: Hello World

 

2 Repetition (*)

s = "Hi! "

print(s * 3)  # Output: Hi! Hi! Hi!

 

3 Indexing

s = "Python"

print(s[0])   # Output: P

print(s[-1])  # Output: n

 

4 Slicing

s = "Programming"

print(s[0:6])   # Output: Progra

print(s[:6])    # Output: Progra

print(s[3:])    # Output: gramming

 

5 Length of String

s = "Python"

print(len(s))  # Output: 6

 

6 Membership Test (in, not in)

s = "Python"

print('P' in s)       # Output: True

print('z' not in s)   # Output: True

 

7 String Methods

  • .lower(), .upper(), .strip(), .replace(), .split(), .find(), etc.

s = " Hello World "

print(s.strip())            # Output: "Hello World"

print(s.lower())            # Output: " hello world "

print(s.replace('World', 'Python'))  # Output: " Hello Python "

print(s.split())            # Output: ['Hello', 'World']

 

Immutable Nature of Strings

Once a string is created, its content cannot be modified.

s = "Python"

# s[0] = 'p'   # ❌ This raises an error: TypeError: 'str' object does not support item assignment

 

# Instead, create a new string

new_s = 'p' + s[1:]

print(new_s)   # Output: python

 

Operation

Example

Concatenation

"Hello" + "World""HelloWorld"

Repetition

"Hi! " * 3"Hi! Hi! Hi! "

Indexing

"Python"[0]'P'

Slicing

"Python"[1:4]'yth'

Methods

.lower(), .upper(), .strip(), .replace(), .split()

Important: Strings are immutable, so any change creates a new string object.

 

Built-in String Methods

Python provides many useful built-in string methods that help in processing strings easily.

Method

Description

Example

.lower()

Converts string to lowercase

"Hello".lower()'hello'

.upper()

Converts string to uppercase

"Hello".upper()'HELLO'

.strip()

Removes leading/trailing spaces

" Hello ".strip()'Hello'

.replace(old, new)

Replaces substring old with new

"Hello World".replace("World", "Python")'Hello Python'

.split(separator)

Splits string into list by separator

"a,b,c".split(",")['a', 'b', 'c']

.join(iterable)

Joins iterable of strings into one string

"-".join(['a', 'b', 'c'])'a-b-c'

.find(sub)

Finds first index of substring (returns -1 if not found)

"Hello".find('e')1

.count(sub)

Counts occurrences of substring

"banana".count('a')3

.startswith(prefix)

Checks if string starts with prefix

"Hello".startswith('H')True

.endswith(suffix)

Checks if string ends with suffix

"Hello".endswith('o')True

.isdigit()

Checks if string contains only digits

"123".isdigit()True

.isalpha()

Checks if string contains only letters

"abc".isalpha()True

.isspace()

Checks if string contains only whitespace

" ".isspace()True

 

 Examples

s = "  Python Programming  "

 

print(s.lower())                      # '  python programming  '

print(s.upper())                      # '  PYTHON PROGRAMMING  '

print(s.strip())                      # 'Python Programming'

print(s.replace("Python", "Java"))    # '  Java Programming  '

print(s.split())                      # ['Python', 'Programming']

print('-'.join(['Python', '3.10']))   # 'Python-3.10'

print(s.find('Pro'))                  # 9

print(s.count('o'))                   # 2

print(s.startswith('  P'))            # True

print(s.endswith('ing  '))            # True

print("123".isdigit())                # True

print("abc".isalpha())                # True

print("   ".isspace())                # True

 

Built-in String Functions in Python

  • These are global built-in functions helpful for string manipulation and conversions.
  • They often return new objects (like lists or bytes), not modifying the original string.
  • Useful in formatting, encoding, and character manipulation.

Function

 Description

Example

len()

Returns the length of the string

len("Python")6

str()

Converts any data type to string

str(100)'100'

ord()

Returns Unicode code point of a character

ord('A')65

chr()

Returns character from Unicode code point

chr(65)'A'

max()

Returns the max character (based on Unicode)

max("Python")'y'

min()

Returns the min character (based on Unicode)

min("Python")'P'

sorted()

Returns a sorted list of characters in string

sorted("Python")['P', 'h', 'n', 'o', 't', 'y']

format()

Formats the string (with placeholders)

'Hello, {}'.format('Alice')'Hello, Alice'

 

 Example Demonstrations

print(len("Python"))  # Output: 6

print(str(123))       # Output: '123'

print(ord('A'))       # Output: 65

print(chr(65))        # Output: 'A'

print(max("Python"))  # Output: 'y'

print(min("Python"))  # Output: 'P'

print(sorted("Python"))  # Output: ['P', 'h', 'n', 'o', 't', 'y']

print("Welcome, {}".format("Deepa"))  # Output: 'Welcome, Deepa'

 

String Comparison in Python

In Python, you can compare strings using comparison operators just like numbers.
The comparison is done lexicographically, based on the Unicode (ASCII) value of characters.

 How String Comparison Works

  • Comparison happens character by character from left to right.
  • The comparison uses Unicode value of each character.

 Comparison Operators

Operator

Meaning

==

Equal to

!=

Not equal to

< 

Less than

> 

Greater than

<=

Less than or equal to

>=

Greater than or equal to

 Examples

s1 = "apple"

s2 = "banana"

 

print(s1 == s2)  # False

print(s1 != s2)  # True

print(s1 < s2)   # True  ('a' < 'b')

print(s1 > s2)   # False

 

print("abc" < "abd")    # True (because 'c' < 'd')

print("abc" > "ab")     # True (longer string is considered greater)

print("Apple" < "apple")  # True (uppercase letters have lower Unicode)

 

 Important Notes

  • Comparison is case-sensitive:
    • 'A' (Unicode 65) is less than 'a' (Unicode 97).
  • Always be mindful of string casing when comparing:
    • Use .lower() or .upper() if needed to make comparisons case-insensitive.

 

Case-insensitive Comparison Example

s1 = "Python"

s2 = "python"

 

print(s1 == s2)                       # False

print(s1.lower() == s2.lower())       # True

 

Comparison

Result

'apple' == 'apple'

True

'apple' != 'Apple'

True

'apple' < 'banana'

True

'abc' < 'abcd'

True

'apple' < 'Apple'

False (due to case)

 

Difference Between String Methods and Built-in Functions in Python

Feature

String Methods

Built-in String Functions

 What are they?

Functions that are called on string objects(using dot notation).

Global functions that can operate on strings (and other types) without needing to be called on a string object.

Example

'hello'.upper()'HELLO'

len('hello')5

Syntax

string.method()

function(string)

Usage

Methods are specific to string objects.

Functions are more general-purpose and work on many types.

Immutability

Methods return a new string (strings are immutable).

Functions usually return a value or new object based on the input string.

Examples

.lower(), .replace(), .strip(), .split(), .find()

len(), ord(), chr(), str()

 Python Modules

Import Statement

The import statement is used to load and use other Python modules into a program.

Without importing, we cannot use functions or variables from another module.

Forms of import:

1. Simple import

                 import math

                print(math.sqrt(16))

2. Import with alias

                import math as m

                print(m.pi)

3. Import specific names

                from math import sqrt, pi

                print(sqrt(9))

                print(pi)

4. Import all names (not recommended)

                 from math import

                print(sin(0))

  

The Python Module

·         A module is a file containing Python code.

·         Advantages of Modules:

  1. Code Reusability → write once, use anywhere.

  2. Easy Maintenance → divide code into separate files.

  3. Avoids Code Duplication.

  4. Better Organization → related functions grouped together.

  5. Large programs can be split into multiple files.

·         Python has three types of modules:

                                 1. Built-in Modules → Already available (e.g., math, os, random).

                 2. External Modules → Installed using pip (e.g., numpy, pandas).

                 3. User-defined Modules → Created by the programmer.

Example – Built-in module:

import datetime

today = datetime.date.today()

print("Todays date:", today)

Example – External module (after installation):

import numpy as np

arr = np.array([1, 2, 3])

print(arr)

 

 dir() Function

·         dir() is a built-in function to know what names are defined inside a module or program.

·         Without arguments → lists names defined in the current scope.

·         With module name → lists names defined inside that module.

Examples:

import math

print(dir(math))    #Lists all functions/constants in math module

            x = 10

print(dir())       # Lists current scope names including x

 


Namespace

·         A namespace is like a container where names (identifiers) are mapped to objects (variables, functions, classes).

·         Python uses namespaces to avoid naming conflicts.

·         Types of Namespaces:

1. Local Namespace → Inside a function (local variables).

2. Global Namespace → At the top level of a program/module.

3. Built-in Namespace → Contains predefined functions like len(), max(), print().

Modules and Namespace Relation:

Each module creates its own namespace.

                We access names in a module using the module_name.member notation.

Example:

import math

print(math.pi)        Access pi from math namespace

print(math.sqrt(25))  Access sqrt() function

Advantage: Different modules can have functions with the same name without conflict (because each has its own namespace).

 

Defining Our Own Modules

We can create our own modules for custom tasks.

Steps:

1. Create a file named mymodule.py:

                def add(a, b):

                                return a + b

                def multiply(a, b):

                                return a * b

 2. Use this module in another program:

                import mymodule

                print(mymodule.add(4, 5))       

                print(mymodule.multiply(3, 6))  

  3. Alternative import:

                from mymodule import add

                print(add(2, 3))   5

  4. Reloading a module (useful when making changes while running):

                import importlib

                import mymodule

                importlib.reload(mymodule)

Comments

Popular posts from this blog

Backtracking - N-Queens Problem, Sum of Subsets, Graph Colouring, Hamiltonian Cycle

Divide and Conquer Technique - Binary Search, Quick Sort, Merge Sort

PYTHON PROGRAMMING - LAB EXERCISES (23UCSCCP01)