Python Unit 3
Python Unit 3
_________________________________________________________________________________________________________
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
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.
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.
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:
Function Arguments
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")
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.
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.
# local variable
s = "I love Geeksforgeeks"
print(s)
# Driver code
f()
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.
def outer():
a=5
def inner():
nonlocal a
a = 10
inner()
print(a)
outer()
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)
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.
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
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)
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).
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.
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.
13
String Special Operators
[] 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
See at next
% Format - Performs String formatting
section
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.
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'.
expandtabs(tabsize=8)
8
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if
tabsize not provided.
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.
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.
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.
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.
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.
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
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.
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.
We can import specific names from a module without importing the module as a whole. For
example,
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.)
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