Unit III Python
Unit III Python
UNIT III Functions – Built in functions – function definition and calling - return statement –
void function – scope and lifetime of variables – args and kwargs – command line arguments -
Tuples – creation – basic tuple operations – tuple() function – indexing – slicing – built-in
functions used on tuples – tuple methods – packing – unpacking – traversing of tuples –
populating tuples – zip() function - Sets – Traversing of sets – set methods – frozenset.
Python Functions
The fundamentals of Python functions, including what they are, their syntax, their primary parts,
return keywords, and major types, will be covered in this tutorial. Additionally, we'll examine
several instances of Python function definitions.
What are Python Functions?
A function is a collection of related assertions that performs a mathematical, analytical, or
evaluative operation. A collection of statements called Python Functions returns the particular
task. Python functions are simple to define and essential to intermediate-level programming. The
exact criteria hold to function names as they do to variable names. The goal is to group up
certain often performed actions and define a function. We may call the function and reuse the
code contained within it with different variables rather than repeatedly creating the same code
block for different input variables.
User-defined and built-in functions are the two main categories of functions in Python. It helps
maintain the programme concise, unique, and well-structured.
Advantages of Functions in Python
Python functions have the following
o By including functions, we can prevent repeating the same code block repeatedly in a
program.
o Python functions, once defined, can be called many times and from anywhere in a
program.
o If our Python program is large, it can be separated into numerous functions which is
simple to track.
o The key accomplishment of Python functions is we can return as many outputs as we
want with different arguments.
However, calling functions has always been overhead in a Python program.
Syntax of Python Function
# An example Python Function
def function_name( parameters ):
# code block
The following elements make up to define a function, as seen above.
o The beginning of a function header is indicated by a keyword called def.
o function_name is the function's name that we can use to separate it from others. We will
use this name to call the function later in the program. In Python, name functions must
follow the same rules as naming variables.
o We pass arguments to the defined function using parameters. However, they are optional.
7.
8. # Calling the function and passing only one argument
9. print( "Passing only one argument" )
10. function(30)
11.
12. # Now giving two arguments to the function
13. print( "Passing two arguments" )
14. function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
2) Keyword Arguments
A function called's arguments are linked to keyword arguments. When invoking a function with
keyword arguments, the user may tell whose parameter value it is by looking at the parameter
label.
We can remove certain arguments or arrange them in a different order since the Python
interpreter will connect the provided keywords to link the values with its parameters. Another
way to use keywords to invoke the function() method is as follows:
Code
1. # Python code to demonstrate the use of keyword arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing arguments without using keyword
8. print( "Without using keyword" )
9. function( 50, 30)
10.
11. # Calling function and passing arguments using keyword
12. print( "With using keyword" )
13. function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
3) Required Arguments
The arguments given to a function while calling in a pre-defined positional sequence are required
arguments. The count of required arguments in the method call must be equal to the count of
arguments provided while defining the function.
We must send two arguments to the function function() in the correct order, or it will return a
syntax error, as seen below.
Code
1. # Python code to demonstrate the use of default arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to
be 30
8. print( "Passing out of order arguments" )
9. function( 30, 20 )
10.
11. # Calling function and passing only one argument
12. print( "Passing only one argument" )
13. try:
14. function( 30 )
15. except:
16. print( "Function needs two positional arguments" )
Output:
Passing out of order arguments
number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments
4) Variable-Length Arguments
We can use special characters in Python functions to pass as many arguments as we want in a
function. There are two types of characters that we can use for this purpose:
1. *args -These are Non-Keyword Arguments
2. **kwargs -These are Keyword Arguments.
4. return num**2
5.
6. # Calling function and passing arguments.
7. print( "With return statement" )
8. print( square( 52 ) )
9.
10. # Defining a function without return statement
11. def square( num ):
12. num**2
13.
14. # Calling function and passing arguments.
15. print( "Without return statement" )
16. print( square( 52 ) )
Output:
With return statement
2704
Without return statement
None
Scope and Lifetime of Variables
The scope of a variable refers to the domain of a program wherever it is declared. A function's
arguments and variables are not accessible outside the defined function. As a result, they only
have a local domain.
The lifespan of a variable in RAM is how long it stays there. A function's lifespan is the same as
that of its internal variables. They are taken away after we exit the function. Consequently, a
function does not keep the value of a variable from previous executions.
Here's a simple example of a variable's scope within a function.
Code
1. # Python code to demonstrate scope and lifetime of variables
2. #defining a function to print a number.
3. def number( ):
4. num = 50
5. print( "Value of num inside the function: ", num)
6.
7. num = 10
8. number()
9. print( "Value of num outside the function:", num)
Output:
Value of num inside the function: 50
Function Description
Python Tuples
A Python Tuple is a group of items that are separated by commas. The indexing, nested objects,
and repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is
immutable.
The distinction between the two is that while we can edit the contents of a list, we cannot alter
the elements of a tuple once they have been assigned.
Example
1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
o Tuples are an immutable data type, which means that once they have been generated,
their elements cannot be changed.
o Since tuples are ordered sequences, each element has a specific order that will never
change.
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one
separated by a comma. Although it is not necessary to include parentheses, doing so is advised.
A tuple can contain any number of items, including ones with different data types (dictionary,
string, float, list, etc.).
Code:
# Python program to show how to create a tuple
1. # Creating an empty tuple
2. empty_tuple = ()
3. print("Empty tuple: ", empty_tuple)
4.
5. # Creating tuple having integers
6. int_tuple = (4, 6, 8, 10, 12, 14)
7. print("Tuple with integers: ", int_tuple)
8.
9. # Creating a tuple having objects of different data types
10. mixed_tuple = (4, "Python", 9.3)
11. print("Tuple with different data types: ", mixed_tuple)
12. )
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
Tuples can be constructed without using parentheses. This is known as triple packing.
Code
1. # Python program to create a tuple without using parentheses
2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11. except:
12. print(TypeError )
Output:
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>
The construction of a tuple from a single member might be hard.
Simply adding parenthesis around the element is insufficient. To be recognised as a tuple, the
element must be followed by a comma.
Code
1. # Python program to show how to create a tuple having a single element
2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Accessing Tuple Elements
We can access the objects of a tuple in a variety of ways.
o Indexing
To access an object of a tuple, we can use the index operator [], where indexing in the tuple starts
from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised if we try
to access an index from the tuple that is outside the range of the tuple index. In this case, an
index above 4 will be out of range.
We cannot give an index of a floating data type or other kinds because the index in Python must
be an integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
Output:
Python
Tuple
tuple index out of range
o Negative Indexing
Python's sequence objects support negative indexing.
The last item of the collection is represented by -1, the second last item by -2, and so on.
Code
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
Syntax
slice(start, end, step)
Parameter Values
Parameter Description
In Python, tuple slicing is a common practise and the most popular method for programmers to
handle practical issues. Think about a Python tuple. To access a variety of elements in a tuple,
you must slice it. One approach is to use the colon as a straightforward slicing operator (:).
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
Output:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
Deleting a Tuple
A tuple's components cannot be altered, as was previously said. As a result, we are unable to get
rid of or remove tuple components.
However, a tuple can be totally deleted with the keyword del.
Code
1. # Python program to show how to delete elements of a Python tuple
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Deleting a particular element of the tuple
5. try:
6. del tuple_[3]
7. print(tuple_)
8. except Exception as e:
9. print(e)
10. # Deleting the variable from the global space of the program
11. del tuple_
12. # Trying accessing the tuple after deleting it
13. try:
14. print(tuple_)
15. except Exception as e:
16. print(e)
Output:
'tuple' object does not support item deletion
name 'tuple_' is not defined
Repetition Tuples in Python
Code
1. # Python program to show repetition in tuples
2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)
Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Python Tuples is a collection of immutable objects that is more like to a list. Python offers a few
ways to work with tuples. These two approaches will be thoroughly covered in this essay with
the aid of some examples.
Using the in keyword, we can determine whether an item is present in the given tuple or not.
Code
1. # Python program to show how to perform membership test for tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)
Output:
True
False
False
True
Iterating Through a Tuple
We can use a for loop to iterate through each element of a tuple.
Code
1. # Python program to show how to iterate over tuple elements
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
Tuples, as opposed to lists, are immutable objects.
This suggests that we are unable to change a tuple's elements once they have been defined. The
nested elements of an element can be changed, though, if the element itself is a changeable data
type like a list.
A tuple can be assigned to many values (reassignment).
Code
1. # Python program to show that Python tuples are immutable objects
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
Output
('apple', 'banana', 'cherry')
Unpacking a tuple:
But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":
fruits = ("apple", "banana", "cherry")
print(green)
print(yellow)
print(red)
Output
apple
banana
cherry
Note: The number of variables must match the number of values in the tuple, if not, you must
use an asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable
name and the values will be assigned to the variable as a list:
print(green)
print(yellow)
print(red)
Output
apple
banana
['cherry', 'strawberry', 'raspberry']
Python zip()
The zip() function returns a zip object, which is an iterator of tuples where the first item in each
passed iterator is paired together, and then the second item in each passed iterator are paired
together etc.
If the passed iterators have different lengths, the iterator with the least items decides the length of
the new iterator.
Syntax
zip(iterator1, iterator2, iterator3 ...)
Parameter Values
Parameter Description
iterator1, iterator2, iterator3 ... Iterator objects that will be joined together
x = zip(a, b)
Output
(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
Python Sets
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces
{}. Python also provides the set() method, which can be used to create the set by the passed
sequence.
Example 1: Using curly braces
1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Example 2: Using set() method
1. Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su
nday"])
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
difference_update() Removes the items in this set that are also included in
another, specified set
Python Frozenset
Definition and Usage
The frozenset() function returns an unchangeable frozenset object (which is like a set object,
only unchangeable).
Syntax
frozenset(iterable)
Parameter Values
Parameter Description
Example
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)
frozenset({'apple', 'banana', 'cherry'})
More Examples
Try to change the value of a frozenset item.
This will cause an error:
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
x[1] = "strawberry"
Output
Traceback (most recent call last):
File "demo_ref_frozenset2.py", line 3, in <module>
x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment