0% found this document useful (0 votes)
2 views24 pages

Python Unit 3

This document provides an overview of Python functions, including their definitions, types, and advantages. It covers function arguments, variable scope, recursion, and string manipulation in Python. Key concepts include built-in and user-defined functions, local and global variables, and the use of *args and **kwargs for variable-length arguments.

Uploaded by

rajalakshmicom85
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)
2 views24 pages

Python Unit 3

This document provides an overview of Python functions, including their definitions, types, and advantages. It covers function arguments, variable scope, recursion, and string manipulation in Python. Key concepts include built-in and user-defined functions, local and global variables, and the use of *args and **kwargs for variable-length arguments.

Uploaded by

rajalakshmicom85
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

Unit – III PYTHON PROGRAMMING

_________________________________________________________________________________________________________

Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again. Python functions are necessary for
intermediate-level programming and are easy to define. Function names meet the same
standards as variable names do. The objective is to define a function and group-specific
frequently performed actions. Instead of repeatedly creating the same code block for
various input variables, we can call the function and reuse the code it contains with
different variables.
Syntax
# An example Python Function
def function_name( parameters ):
# code block

Some Benefits of Using Functions

• Increase Code Readability


• Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:

Syntax of Python Function Declaration

1
Types of Functions in Python
Below are the different types of functions in Python:
• Built-in library function: These are Standard functions in Python that are available to
use.
• User-defined function: We can create our own functions based on our requirements.

Advantages of Python Functions


o Once defined, Python functions can be called multiple times and from any location in
a program.
o Our Python program can be broken up into numerous, easy-to-follow functions if it is
significant.

o The ability to return as many outputs as we want using a variety of arguments is one
of Python's most significant achievements.
o However, Python programs have always incurred overhead when calling functions.

Creating a Function in Python


We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python function
definition by using def keyword.
Python

# A simple Python function


def fun():
print("Welcome to GFG")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function. Below is the
example for calling def function Python.
Python

2
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output:
Welcome to GFG

Function Basics
def greet():
print("Hello, world!")

This defines a simple function called greet that prints "Hello, world!". To call this function,
you simply use its name followed by parentheses:

greet() Output: Hello, world!

Function Arguments

Functions in Python can also accept arguments. Here's an example of a function


that takes a name as an argument and greets the person by name:

def greet_with_name(name):
print(f"Hello, {name}!")
To call this function with an argument, you pass the argument inside the parentheses:
greet_with_name("Alice")

Output: Hello, Alice!

Returning Values:

Functions can also return values using the return statement. For example, let's create
a function that calculates the square of a number and returns the result:
def square(x):
return x ** 2

3
VARIABLE SCOPE AND ITS LIFETIME

Python is not “statically typed”. We do not need to declare variables before using them or
declare their type. A variable is created the moment we first assign a value to it.

Python Scope variable


The location where we can find a variable and also access it if required is called the scope
of a variable.

Python Local variable

Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function. Let’s look at how to make a local
variable.

def f(): Output I love Geeksforgeeks

# local variable
s = "I love Geeksforgeeks"

print(s)
# Driver code
f()

Python Global variables

Global variables are the ones that are defined and declared outside any function and are
not specified to any function. They can be used by any part of the program.

Def() Output:
print(s) I love Geeksforgeeks

# Global scope
s = "I love Geeksforgeeks"
f()

4
Nonlocal keyword
The nonlocal keyword is used in the case of nested functions. This keyword works
similarly to the global, but rather than global, this keyword declares a variable to point to
the variable of an outside enclosing function, in case of nested functions.

print("Value of a using nonlocal is : ", end="")

def outer():
a=5
def inner():
nonlocal a
a = 10
inner()
print(a)

outer()

print("Value of a without using nonlocal is : ", end="")

def outer(): Output: Value of a using nonlocal is : 10


a=5 Value of a without using nonlocal is : 5
def inner():
a = 10
inner()
print(a)
outer()

Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following function argument types in Python:
• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments *args and **kwargs)
Default arguments
Python allows function arguments to have default values. If the function is called without
the argument, the argument gets its default value.

5
Python has a different way of representing syntax and default values for function
arguments. Default values indicate that the function argument will take that value if no
argument value is passed during the function call. The default value is assigned by using
the assignment(=) operator of the form keywordname=value.

Syntax:
def function_name(param1, param2=default_value2, param3=default_value3)

def myFun(x, y=50): Output:


print("x: ", x) x: 10
y: 50
print("y: ", y)
myFun(10)
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.

Python allows to pass function arguments in the form of keywords which are also called
named arguments. Variables in the function definition are used as keywords. When the
function is called, you can explicitly mention the name and its value.

def printinfo( name, age ): Name: Naveen


"This prints a passed info into this function" Age 29
print ("Name: ", name) Name: miki
print ("Age ", age) Age 30
return

printinfo ("Naveen", 29)

printinfo(name="miki", age = 30)

Positional Arguments
We used the Position argument during the function call so that the first argument (or
value) is assigned to name and the second argument (or value) is assigned to age. By

6
changing the position, or if you forget the order of the positions, the values can be used in
the wrong places, as shown in the Case-2 example below, where 27 is assigned to the
name and Suraj is assigned to the age.
def nameAge(name, age): Case-1:
print("Hi, I am", name) Hi, I am Suraj
print("My age is ", age) My age is 27
print("Case-1:") Case-2:
nameAge("Suraj", 27) Hi, I am 27
print("\nCase-2:")
nameAge(27, "Suraj") My age is Suraj

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number
of arguments to a function using special symbols. There are two special symbols:
• *args in Python (Non-Keyword Arguments)
• **kwargs in Python (Keyword Arguments)

def myFun(*argv): Hello


for arg in argv:
print(arg) Welcome
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') to
GeeksforGeeks

Required arguments
Required arguments are the arguments passed to a function in correct positional order
The number of arguments in the function call should match exactly with the function
• definition. # Function definition is here def printme( name, age ): "This prints a passed
string into this function" print (name , age) # Now you can call printme function

7
printme("Ajay",30) To call the function printme( ), it is definitely need to pass one
argument, otherwise it gives a syntax error.
Variable Length Argument in Python
we will cover about Variable Length Arguments in Python. Variable-length arguments
refer to a feature that allows a function to accept a variable number of arguments in
Python. It is also known as the argument that can also accept an unlimited amount of data
as input inside the function. There are two types in Python:
• Non – Keyworded Arguments (*args)
• Keyworded Arguments (**kwargs)

What is Python *args?


In Python, *args is used to pass a variable number of arguments to a function. It is used to
pass a variable-length, non-keyworded argument list. These arguments are collected into a
tuple within the function and allow us to work with them.
Feature of Python *args
• To accept a variable number of arguments, use the symbol *; by convention, it is
commonly used with the term args.
• *args enables you to accept more arguments than the number of formal arguments you
previously defined. With *args, you can add any number of extra arguments to your
current formal parameters (including none).
• Using the *, the variable that we associate with the * becomes iterable meaning you can
do things like iterate over it, run some higher-order functions such as map and filter
• In this example, we define a function sum_all that accepts any number of arguments.
The *args syntax collects all the arguments into a tuple named args. Inside the function,
we iterate through the args tuple and calculate the sum of all the numbers passed to
the function.
def sum_all(*args):
result = 0
for num in args:
result += num
return result
8
print(sum_all(1, 2, 3, 4, 5))
Output
15

What is Python **kwargs?


In Python, **kwargs is used to pass a keyworded, variable-length argument list. We call
kwargs with a double star. The reason for this is that the double star allows us to pass over
keyword arguments (in any order). Arguments are collected into a dictionary within the
function that allow us to access them by their keys.
Feature of Python **kwargs
• A keyword argument is when you give the variable a name as you provide it into the
function.
• Consider the kwargs to be a dictionary that maps each keyword to the value we pass
beside it. As a result, when we iterate through the kwargs, there appears to be no
sequence in which they were printed.
In this example, the display_info function accepts a variable number of keyword
arguments. Inside the function, we iterate through the kwargs dictionary and print out
each key-value pair.
Combining *args and **kwargs
You can also use both *args and **kwargs in the same function definition, allowing you to
accept a mix of positional and keyword arguments.

def print_args_and_kwargs(*args, **kwargs):


print("Positional arguments:")
for arg in args:
print(arg)
print("Keyword arguments:")
for key, value in [Link]():
print(f"{key}: {value}")

9
print_args_and_kwargs(1, 2, 3, name="Alice", age=30)
Output
Positional arguments:
1
2
3
Keyword arguments:
name: Alice
age: 30

Recursion
The term Recursion can be defined as the process of defining something in terms of itself.
In simple words, it is a process in which a function calls itself directly or indirectly.

Recursion in Python refers to a function calling itself during its execution. This programming
technique is used to solve problems that can be broken down into simpler, repetitive tasks.
Each recursive call reduces the problem into a smaller piece, and recursion continues until it
reaches a base case, which does not involve a recursive call. Recursive functions are
commonly used in tasks like traversing data structures (e.g., trees or graphs) and solving
algorithmic problems (e.g., sorting or computing factorials).

Advantages of using recursion


• A complicated function can be split down into smaller sub-problems utilizing
recursion.
• Sequence creation is simpler through recursion than utilizing any nested iteration.
• Recursive functions render the code look simple and effective.
Disadvantages of using recursion
• A lot of memory and time is taken through recursive calls which makes it expensive for
use.
• Recursive functions are challenging to debug.
• The reasoning behind recursion can sometimes be tough to think through.

10
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
Example 1: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8….
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
Output
Fibonacci series:
0
1
1
2
3
5
8
13
21
34

11
Python String
A String is a data structure in Python Programming that represents a sequence of
characters. It is an immutable data type, meaning that once you have created a string, you
cannot change it. Python String are used widely in many different applications, such as
storing and manipulating text data, representing names, addresses, and other types of
data that can be represented as text.

Python Programming does not have a character data type, a single character is simply a
string with a length of 1.

Syntax of String Data Type in Python


string_variable = 'Hello, world!'

string_0 = "A Computer Science portal for geeks"


print(string_0)
print(type(string_0))
Output:
A Computer Science portal for geeks
<class 'str'>

Create a String in Python


Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python or how to write string in Python.
Example:
We will create a string using single quotes (‘ ‘), double quotes (” “), and triple double
quotes (“”” “””). The triple quotes can be used to declare multiline strings in Python

Accessing characters in Python String


In Python Programming tutorials, individual characters of a String can be accessed by
using the method of Indexing. Indexing allows negative address references to access
characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.

12
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types that will cause a TypeError.

Python String Positive Indexing


In this example, we will define a string in Python Programming and access its characters
using positive indexing. The 0th element will be the first character of the string.
String1 = "GeeksForGeeks"
print("Initial String: ", String1)

# Printing First character


print("First character of String is: ", String1[0])
Output:
Initial String: GeeksForGeeks
First character of String is: G

Case Changing of Python String Methods


• lower(): Converts all uppercase characters in a string into lowercase
• upper(): Converts all lowercase characters in a string into uppercase
• title(): Convert string to title case
• swapcase(): Swap the cases of all characters in a string
• capitalize(): Convert the first character of a string to uppercase

13
String Special Operators

Operator Description Example

Concatenation - Adds values on either side of the a + b will give


+
operator HelloPython

Repetition - Creates new strings, concatenating a*2 will give -


*
multiple copies of the same string HelloHello

[] Slice - Gives the character from the given index a[1] will give e

Range Slice - Gives the characters from the given a[1:4] will give
[:]
range ell

Membership - Returns true if a character exists in


in H in a will give 1
the given string

Membership - Returns true if a character does not M not in a will


not in
exist in the given string give 1

Raw String - Suppresses actual meaning of Escape


characters. The syntax for raw strings is exactly the
print r'\n'
same as for normal strings with the exception of the
prints \n and
r/R raw string operator, the letter "r," which precedes
print
the quotation marks. The "r" can be lowercase (r) or
R'\n'prints \n
uppercase (R) and must be placed immediately
preceding the first quote mark.

See at next
% Format - Performs String formatting
section

Built-in String Methods

Python includes the following built-in methods to manipulate strings −


14
[Link]. Methods with Description

capitalize()
1
Capitalizes first letter of string.

casefold()
2
Converts all uppercase letters in string to lowercase. Similar to lower(),
but works on UNICODE characters alos.

center(width, fillchar)
3
Returns a space-padded string with the original string centered to a total
of width columns.

count(str, beg= 0,end=len(string))


4
Counts how many times str occurs in string or in a substring of string if
starting index beg and ending index end are given.

decode(encoding='UTF-8',errors='strict')
5
Decodes the string using the codec registered for encoding. encoding
defaults to the default string encoding.

encode(encoding='UTF-8',errors='strict')
6
Returns encoded string version of string; on error, default is to raise a
ValueError unless errors is given with 'ignore' or 'replace'.

endswith(suffix, beg=0, end=len(string))

7 Determines if string or a substring of string (if starting index beg and


ending index end are given) ends with suffix; returns true if so and false
otherwise.

expandtabs(tabsize=8)
8
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if
tabsize not provided.

9 find(str, beg=0 end=len(string))

15
Determine if str occurs in string or in a substring of string if starting index
beg and ending index end are given returns index if found and -1
otherwise.

format(*args, **kwargs)
10
This method is used to format the current string value.

format_map(mapping)
11
This method is also use to format the current string the only difference is it
uses a mapping object.

index(str, beg=0, end=len(string))


12
Same as find(), but raises an exception if str not found.

isalnum()
13
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

isalpha()
14
Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

isascii()
15
Returns True is all the characters in the string are from the ASCII character
set.

isdecimal()
16
Returns true if a unicode string contains only decimal characters and false
otherwise.

isdigit()
17
Returns true if string contains only digits and false otherwise.

isidentifier()
18
Checks whether the string is a valid Python identifier.

16
islower()
19
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

isnumeric()
20
Returns true if a unicode string contains only numeric characters and false
otherwise.

Built-in Functions with Strings

Following are the built-in functions we can use with strings −

[Link]. Function with Description

len(list)
1
Returns the length of the string.

max(list)
2
Returns the max alphabetical character from the string str.

min(list)
3
Returns the min alphabetical character from the string str.

Python Strings Immutable


Strings in Python are “immutable” which means they can not be changed after they are
created. Some other immutable data types are integers, float, boolean, etc.
The immutability of Python string is very useful as it helps in hashing, performance
optimization, safety, ease of use, etc.
The article will explore the differences between mutable and immutable objects,
highlighting the advantages of using immutable objects. It will also compare immutability
with mutability, discussing various methods to handle immutability and achieve desired
outcomes.

17
Input: name_1 = "Aarun"
name_1[0] = 'T'
Output: TypeError: 'str' object does not support item assignment
Immutability is the property of an object according to which we can not change the object
after we declared or after the creation of it and this Immutability in the case of the string is
known as string immutability in Python.

Benefits of Immutable Objects


1. Hashability and Dictionary Keys: Immutable objects can be used as keys in
dictionaries because their hash value remains constant, ensuring that the key-value
mapping is consistent.
2. Memory Efficiency: Since immutable objects cannot change their value, Python can
optimize memory usage. Reusing the same immutable object across the program
whenever possible reduces memory overhead.
3. Thread Safety: Immutability provides inherent thread safety. When multiple threads
access the same immutable object, there’s no risk of data corruption due to concurrent
modifications.
Difference between Immutability and Mutability
1. Mutability: Mutable objects are those objects that can be modified after their
creation, to demonstrate mutability in Python we have a very popular data type
which is the list.

2. Immutability:
Immutability refers to the property of an object, that we can not change the object after
we declare it.
Ways to Deal with Immutability
• String Slicing and Reassembling
• String Concatenation
• Using the join() method
• Using String Formatting
• Converting to Mutable Data Structures

18
String Comparison in Python
String comparison is a fundamental operation in any programming language, including
Python. It enables us to ascertain strings’ relative positions, ordering, and
equality. Python has a number of operators and techniques for comparing strings, each
with a specific function. We will examine numerous Python string comparison methods
in this article and comprehend how to use them.

Input: "Geek" == "Geek"


"Geek" < "geek"
"Geek" > "geek"
"Geek" != "Geek"
Output: True
True
False
False
Explanation: In this, we are comparing two strings if they are equal to each other.

Python String Comparison


• Using Relational Operators
• Using Regular Expression
• Using Is Operator
• Creating a user-defined function.

The relational operators compare the Unicode values of the characters of the strings from
the zeroth index till the end of the string. It then returns a boolean value according to the
operator used. It checks Python String Equivalence.
Python

print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")

19
print("Geek" != "Geek")

module. Regular expressions provide a flexible and powerful way to define patterns and
perform pattern-matching operations on strings.

import re

def compare_strings(string1, string2):


pattern = [Link](string2)
match = [Link](pattern, string1)

if match:
print(f"'{string2}' found in '{string1}'")
else:
print(f"'{string2}' not found in '{string1}'")

string1 = "GeeksForGeeks"
string2 = "GeeksFor"
string3 = "Geeks"

compare_strings(string1, string2)
compare_strings(string1, string3)
Output
'GeeksFor' found in 'GeeksForGeeks'
'Geeks' found in 'GeeksForGeeks'

The == operator compares the values of both operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not.
The same is the case for != and is not. Let us understand Python String Equivalence with
an example.

By using relational operators we can only check Python String Equivalence by their
Unicode. In order to compare two strings according to some other parameters, we can
make user-defined functions. In the following code, our user-defined function will
compare the strings based on the number of digits.

20
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There
are many Python modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create our own simple
module, Import Python modules, From statements in Python, we can use the alias to rename
the module, etc.
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also
makes the code logically organized.

Create a Python Module


To create a Python module, write the desired code and save that in a file
with .py extension.
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

Import module in Python


We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module
is present in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a
module.
For example, to import the module [Link], we need to put the following command at the
top of the script.
Syntax to Import Module in Python
import module

21
import calc
print([Link](10, 2))
Output:
12
Import statements

The import statement allows you to import one or more modules into your Python
program, letting you make use of the definitions constructed in those modules.

def greeting(name): ouput: 36


print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

from mymodule import person1


print (person1["age"])

Python from...import statement

We can import specific names from a module without importing the module as a whole. For
example,

# import only pi from math module


from math import pi

print(pi)

# Output: 3.141592653589793

22
dir() function in Python
In Python, the dir() function is a built-in function used to list the attributes (methods,
properties, and other members) of an object. In this article we will see about dir() function
in Python.
Python dir() Function Syntax
Syntax: dir({object})
Parameters :
object [optional] : Takes object name
Returns :
dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function
behaves rather differently with different type of objects, as it aims to produce the most
relevant one, rather than the complete information.
• For Class Objects, it returns a list of names of all the valid attributes and base attributes
as well.
• For Modules/Library objects, it tries to return a list of names of all the attributes,
contained in that module.
• If no parameters are passed it returns a list of names in the current local scope.
dir() is a powerful inbuilt function in Python3, which returns a list of the attributes and
methods of any object (say functions, modules, strings, lists, dictionaries, etc.)

Python dir() function Examples


When No Parameters are Passed
In this example, we are using the dir() function to list object attributes and methods in
Python. It provides a demonstration for exploring the available functions and objects in
our Python environment and modules when we are working with them.
print(dir())

import random import math print(dir())

Applications of Python dir()


• The dir() has it’s own set of uses. It is usually used for debugging purposes in simple
day to day programs, and even in large projects taken up by a team of developers. The

23
capability of dir() to list out all the attributes of the parameter passed, is really useful
when handling a lot of classes and functions, separately.
• The dir() function can also list out all the available attributes for a
module/list/dictionary. So, it also gives us information on the operations we can
perform with the available list or module, which can be very useful when having little
to no information about the module. It also helps to know new modules faster.

Namespaces
A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of
a Python dictionary. Let’s go through an example, a directory-file system structure in
computers. Needless to say, that one can have multiple directories having a file with the
same name inside every directory.

Name (which means name, a unique identifier) + Space(which talks something related to
scope). Here, a name might be of any Python method or variable and space depends upon
the location from where is trying to access a variable or a method.

Types of namespaces :
Some functions like print(), id() are always present, these are built-in namespaces. When a
user creates a module, a global namespace gets created, later the creation of local
functions creates the local namespace. The built-in namespace encompasses the global
namespace and the global namespace encompasses the local namespace.

24

You might also like