UNIT II
[Link]() function in Python
There is a built-in math module in Python that consists of different
useful mathematical utilities for calculations.
One such built-in function of the math module is
the [Link]() function. This function accepts a numeric input and
returns the floor value by rounding down it to the nearest integer.
Let us consider the following example demonstrating the same:
1. # importing the floor() function from the math module
2. from math import floor
3.
4. # declaring the variables
5. a = 5.34
6. b = -5.34
7. # using the floor() function
8. c = floor(a)
9. d = floor(b)
10. # printing the values
11. print("Floor value of", a, "=", c)
12. print("Floor value of", b, "=", d)
Output:
Floor value of 5.34 = 5
Floor value of -5.34 = 6
Boolean Expression:
Boolean Values
In programming you often need to know if an expression
is True or False.
You can evaluate any expression in Python, and get one of two
answers, True or False.
Print a message based on whether the condition is True or False:
EXAMPLE1:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Most Values are True
Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
Example
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Some Values are False
In fact, there are not many values that evaluate to False, except
empty values, such as (), [], {}, "", the number 0, and the
value None. And of course the value False evaluates to False.
Example
The following will return False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Example
Print "YES!" if the function returns True, otherwise print "NO!":
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
4.2 Conditional execution
In order to write useful programs, we almost always need the ability to check certain
conditions and change the behavior of the program accordingly. Conditional
statements give us this ability. The simplest form is the if statement:
if (x > 0) {
cout << "x is positive" << endl;
}
The expression in parentheses is called the condition. If it is true, then the statements
in brackets get executed. If the condition is not true, nothing happens.
The condition can contain any of the comparison operators:
x == y // x equals y
x != y // x is not equal to y
x > y // x is greater than y
x < y // x is less than y
x >= y // x is greater than or equal to y
x <= y // x is less than or equal to y
Although these operations are probably familiar to you, the syntax C++ uses is a little
different from mathematical symbols like =, neq and le. A common error is to use a
single = instead of a double ==. Remember that = is the assignment operator, and == is
a comparison operator. Also, there is no such thing as =< or =>.
The two sides of a condition operator have to be the same type. You can only
compare ints to ints and doubles to doubles. Unfortunately, at this point you can't
compare Strings at all! There is a way to compare Strings, but we won't get to it for
a couple of chapters.
4.3 Alternative execution
A second form of conditional execution is alternative execution, in which there are
two possibilities, and the condition determines which one gets executed. The syntax
looks like:
if (x%2 == 0) {
cout << "x is even" << endl;
} else {
cout << "x is odd" << endl;
}
If the remainder when x is divided by 2 is zero, then we know that x is even, and this
code displays a message to that effect. If the condition is false, the second set of
statements is executed. Since the condition must be true or false, exactly one of the
alternatives will be executed.
As an aside, if you think you might want to check the parity (evenness or oddness) of
numbers often, you might want to "wrap" this code up in a function, as follows:
void printParity (int x) {
if (x%2 == 0) {
cout << "x is even" << endl;
} else {
cout << "x is odd" << endl;
}
}
Now you have a function named printParity that will display an appropriate
message for any integer you care to provide. In main you would call this function as
follows:
printParity (17);
Always remember that when you call a function, you do not have to declare the types
of the arguments you provide. C++ can figure out what type they are. You should
resist the temptation to write things like:
int number = 17;
printParity (int number); // WRONG!!!
4.4 Chained conditionals
Sometimes you want to check for a number of related conditions and choose one of
several actions. One way to do this is by chaining a series of ifs and elses:
if (x > 0) {
cout << "x is positive" << endl;
} else if (x < 0) {
cout << "x is negative" << endl;
} else {
cout << "x is zero" << endl;
}
These chains can be as long as you want, although they can be difficult to read if they
get out of hand. One way to make them easier to read is to use standard indentation, as
demonstrated in these examples. If you keep all the statements and squiggly-braces
lined up, you are less likely to make syntax errors and you can find them more quickly
if you do.
4.5 Nested conditionals
In addition to chaining, you can also nest one conditional within another. We could
have written the previous example as:
if (x == 0) {
cout << "x is zero" << endl;
} else {
if (x > 0) {
cout << "x is positive" << endl;
} else {
cout << "x is negative" << endl;
}
}
There is now an outer conditional that contains two branches. The first branch
contains a simple output statement, but the second branch contains
another if statement, which has two branches of its own. Fortunately, those two
branches are both output statements, although they could have been conditional
statements as well.
Notice again that indentation helps make the structure apparent, but nevertheless,
nested conditionals get difficult to read very quickly. In general, it is a good idea to
avoid them when you can.
On the other hand, this kind of nested structure is common, and we will see it again,
so you better get used to it.
NumPy Array Iteration
NumPy provides an iterator object, i.e., nditer which can be used to
iterate over the given array using python standard Iterator interface.
Consider the following example.
1. import numpy as np
2. a = [Link]([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
3. print("Printing array:")
4. print(a);
5. print("Iterating over the array:")
6. for x in [Link](a):
7. print(x,end=' ')
Output:
Printing array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3
Order of Iteration
As we know, there are two ways of storing values into the numpy
arrays:
1. F-style order
2. C-style order
Let's see an example of how the numpy Iterator treats the specific
orders (F or C).
Example
1. import numpy as np
2.
3. a = [Link]([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
4.
5. print("\nPrinting the array:\n")
6.
7. print(a)
8.
9. print("\nPrinting the transpose of the array:\n")
10. at = a.T
11.
12. print(at)
13.
14. print("\nIterating over the transposed array\n")
15.
16. for x in [Link](at):
17. print(x, end= ' ')
18.
19. print("\nSorting the transposed array in C-style:\n")
20.
21. c = [Link](order = 'C')
22.
23. print(c)
24.
25. print("\nIterating over the C-style array:\n")
26. for x in [Link](c):
27. print(x,end=' ')
28.
29.
30. d = [Link](order = 'F')
31.
32. print(d)
33. print("Iterating over the F-style array:\n")
34. for x in [Link](d):
35. print(x,end=' ')
Output:
Printing the array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the transposed array
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the C-style array:
1 2 10 2 4 20 3 5 39 4 6 3 [[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the F-style array:
1 2 3 4 2 4 5 6 10 20 39 3
Creating String in Python
We can create a string by enclosing the characters in single-quotes
or double- quotes. Python also provides triple-quotes to represent
the string, but it is generally used for multiline string or docstrings.
1. #Using single quotes
2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from
0. For example, The string "HELLO" is indexed as given
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the
individual characters of the string. However, we can use the : (colon)
operator in Python to access the substring from the given string.
Consider the following example.
Here, we must notice that the upper range given in the slice
operator is always exclusive i.e., if str = 'HELLO' is given, then
str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
Consider the following example:
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a
new string. The string object doesn't support item assignment i.e., A
string can only be replaced with new string since its content cannot
be partially replaced. Strings are immutable in Python.
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
Traceback (most recent call last):
File "[Link]", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment
Deleting the String
As we know that strings are immutable. We cannot delete or remove
the characters from the string. But we can delete the entire string
using the del keyword.
1. str = "JAVATPOINT"
2. del str[1]
Output:
TypeError: 'str' object doesn't support item deletion
Now we are deleting entire string.
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
NameError: name 'str1' is not defined
Python List
In Python, the sequence of various data types is stored in a list. A
list is a collection of different kinds of values or items. Since Python
lists are mutable, we can change their elements after forming. The
comma (,) and the square brackets [enclose the List's items] serve
as separators.
Although six Python data types can hold sequences, the List is the
most common and reliable form. A list, a type of sequence data, is
used to store the collection of data. Tuples and Strings are two
similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays
defined in other languages, such as Array List in Java and Vector in
C++. A list is a collection of items separated by commas and
denoted by the symbol [].
1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10. print(type(list1))
11. print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9]
['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:
o The lists are in order.
o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.
Ordered List Checking
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b
Output:
False
The indistinguishable components were remembered for the two
records; however, the subsequent rundown changed the file position
of the fifth component, which is against the rundowns' planned
request. False is returned when the two lists are compared.
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:
True
Records forever protect the component's structure. Because of this,
it is an arranged collection of things.
Let's take a closer look at the list example.
Code
1. # list example in detail
2. emp = [ "John", 102, "USA"]
3. Dep1 = [ "CS",10]
4. Dep2 = [ "IT",11]
5. HOD_CS = [ 10,"Mr. Holding"]
6. HOD_IT = [11, "Mr. Bewon"]
7. print("printing employee data ...")
8. print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp
[2]))
9. print("printing departments ...")
10. print("Department 1:\nName: %s, ID: %d\n Department 2:\n N
ame: %s, ID: %s"%( Dep1[0], Dep2[1], Dep2[0], Dep2[1]))
11. print("HOD Details ....")
12. print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
13. print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
14. print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type
(HOD_IT))
Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class '
list '>
In the preceding illustration, we printed the employee and
department-specific details from lists that we had created. To better
comprehend the List's concept, look at the code above.
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing.
The slice operator [] can be used to get to the List's components.
The index ranges from 0 to length -1. The 0th index is where the
List's first element is stored; the 1st index is where the second
element is stored, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
o The beginning indicates the beginning record position of the
rundown.
o The stop signifies the last record position of the rundown.
o Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index,
and the value of the end parameter is the number of elements that
are "stepped" through. The default value for the step is one without
a specific value. Inside the resultant Sub List, the same with record
start would be available, yet the one with the file finish will not. The
first element in a list appears to have an index of zero.
Consider the following example:
Code
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default, the index value is 0 so its starts from the 0th element
and go for index -1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
ADVERTISEMENT
ADVERTISEMENT
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Python Tuples
A comma-separated group of items is called a Python triple. The
ordering, settled items, and reiterations of a tuple are to some
degree like those of a rundown, but in contrast to a rundown, a tuple
is unchanging.
The main difference between the two is that we cannot alter the
components of a tuple once they have been assigned. On the other
hand, we can edit the contents of a list.
Example
1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
o Tuples are an immutable data type, meaning their elements
cannot be changed after they are generated.
o Each element in a tuple has a specific order that will never
change because tuples are ordered sequences.
Forming a Tuple:
All the objects-also known as "elements"-must be separated by a
comma, enclosed in parenthesis (). Although parentheses are not
required, they are recommended.
Any number of items, including those with various data types
(dictionary, string, float, list, etc.), can be contained in a tuple.
Code
1. # Python program to show how to create a tuple
2. # Creating an empty tuple
3. empty_tuple = ()
4. print("Empty tuple: ", empty_tuple)
5.
6. # Creating tuple having integers
7. int_tuple = (4, 6, 8, 10, 12, 14)
8. print("Tuple with integers: ", int_tuple)
9.
10. # Creating a tuple having objects of different data types
11. mixed_tuple = (4, "Python", 9.3)
12. print("Tuple with different data types: ", mixed_tuple)
13.
14. # Creating a nested tuple
15. nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
16. print("A nested tuple: ", nested_tuple)
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not necessary for the construction of multiples. This
is known as triple pressing.
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 development of a tuple from a solitary part may be complex.
Essentially adding a bracket around the component is lacking. A
comma must separate the element to be recognized as a tuple.
Code
1. # Python program to show how to create a tuple having a single ele
ment
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
A tuple's objects can be accessed in a variety of ways.
Indexing
Indexing We can use the index operator [] to access an object in a
tuple, where the index starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index
Error will be raised assuming we attempt to get to a list from the
Tuple that is outside the scope of the tuple record. An index above
four will be out of range in this scenario.
Because the index in Python must be an integer, we cannot provide
an index of a floating data type or any other type. If we provide a
floating index, the result will be TypeError.
The method by which elements can be accessed through nested
tuples can be seen in the example below.
Code
1. # Python program to show how to access tuple elements
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. print(tuple_[0])
5. print(tuple_[1])
6. # trying to access element index more than the length of a tuple
7. try:
8. print(tuple_[5])
9. except Exception as e:
10. print(e)
11. # trying to access elements through the index of floating data
type
12. try:
13. print(tuple_[1.0])
14. except Exception as e:
15. print(e)
16. # Creating a nested tuple
17. nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
18.
19. # Accessing the index of a nested tuple
20. print(nested_tuple[0][3])
21. print(nested_tuple[1][1])
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
Differences between Lists and Tuples
In most cases, lists and tuples are equivalent. However, there are
some important differences to be explored in this article.
List and Tuple Syntax Differences
The syntax of a list differs from that of a tuple. Items of a tuple are
enclosed by parentheses or curved brackets (), whereas items of a
list are enclosed by square brackets [].
Example Code
1. # Python code to show the difference between creating a list and a
tuple
2.
3. list_ = [4, 5, 7, 1, 7]
4. tuple_ = (4, 1, 8, 3, 9)
5.
6. print("List is: ", list_)
7. print("Tuple is: ", tuple_)
Output:
List is: [4, 5, 7, 1, 7]
Tuple is: (4, 1, 8, 3, 9)
Mutable List vs. Immutable Tuple
An important difference between a list and a tuple is that lists are
mutable, whereas tuples are immutable. What exactly does this
imply? It means a list's items can be changed or modified, whereas
a tuple's items cannot be changed or modified.
We can't employ a list as a key of a dictionary because it is mutable.
This is because a key of a Python dictionary is an immutable object.
As a result, tuples can be used as keys to a dictionary if required.
Let's consider the example highlighting the difference between lists
and tuples in immutability and mutability.
Example Code
1. # Updating the element of list and tuple at a particular index
2.
3. # creating a list and a tuple
4. list_ = ["Python", "Lists", "Tuples", "Differences"]
5. tuple_ = ("Python", "Lists", "Tuples", "Differences")
6.
7. # modifying the last string in both data structures
8. list_[3] = "Mutable"
9. print( list_ )
10. try:
11. tuple_[3] = "Immutable"
12. print( tuple_ )
13. except TypeError:
14. print( "Tuples cannot be modified because they are immuta
ble" )
Output:
['Python', 'Lists', 'Tuples', 'Mutable']
Tuples cannot be modified because they are immutable
Python slice() Function
In Python, we have a number of inbuilt functions. One such function
is the Python slice() function. The Python slice function is used to get
a slice or a portion of elements from the collection of elements such
as a list, tuple, or string.
The slice function offers a simple and effective method for
extracting a portion of data and modifying data from a sequence of
elements.
You can use the slice function to encapsulate slice logic, such as
start, stop, and step parameters.
Python provides two overloaded slice functions. The first function
takes a single argument, while the second function takes three
arguments and returns a slice object. This slice object can be used
to get a subsection of the collection. For example, if we want to get
the first two elements from the list of elements, here slice can be
used.
Python slice() Function Example 1 - Creating a slice object
1. # Python program to demonstrate
2. # how to create a slice() object
3.
4. # Calling function
5. slice1 = slice(5) # returns a slice object
6. slice2 = slice(0,5,3) # returns a slice object
7.
8. # Displaying the result
9. print(slice1)
10. print(slice1)
Output:
slice(None, 5, None)
slice(0, 5, 3)
Python slice() Function Example 2 - Using a slice object
Let's use this slice object to extract data from a list of elements:
1. # Python program to demonstrate
2. # how to use a slice() object
3.
4. # Calling function
5. slice1 = slice(5) # returns a slice object
6. slice2 = slice(0, 5, 3) # returns a slice object
7.
8. # Defining a list
9. my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
10.
11. # Extracting data and displaying the result
12. print("Slice 1 of My list:", my_list[slice1])
13. print("Slice 2 of My list:", my_list[slice2])
Output:
Slice 1 of My list: [1, 2, 3, 4, 5]
Slice 2 of My list: [1, 4]
List All Functions of a Python Module
Before we learn about the methods from which we can list down all
the functions present in a Python module, we have to understand
where and why we need to know how many functions are present in
the module. Answering this question not only will solve the doubt
which is coming to mind of most of us, but it will also make us
keener for learning the methods. Therefore, first, we will see the
reasons that are given below, for which we need to check out the
functions present in a Python module:
Following are the methods which will help us in looking for
all the functions present in a Python module:
o By dir() method
o By Inspect module
Method 1: Using the dir() Function:
We can list down all the functions present in a Python module by
simply using the dir() method in the Python shell or in the
command prompt shell. We have first to import the module in the
Python shell, and then we have to write the module name in
the dir() method, and it will return the list of all functions present in
a particular Python module. Let's understand the implementation of
this method through the following example program.
Example 1:
Look at the following Python program where we have used the
statistics module in the dir() function:
1. # Import the statistics Module
2. import statistics
3. # Use statistics inside dir() method
4. dir(statistics)
Method 2: Using Inspect Module:
In this method, we will use isfunction and getmembers function from
the inspect module (A build-in module of Python) to list down all the
functions present in a Python module. We will loop over the module
which functions we want to list out using the for loop. One thing we
should note here is that we can't list out functions of built-in
modules of Python using this method as the type of functions
present in any built-in module is not considered as a function for the
inspect module. Let's understand the implementation of this method
through the following example:
Example 2:
Look at the following Python program where we have used the
Numpy module inside the inspect module's functions:
1. # Import the getmembers and isfunction from the Inspect module
2. from inspect import getmembers, isfunction
3. # Import the Numpy Module
4. import numpy
5. # Use for loop on the Numpy Module with isfunction() and getmemb
ers() function
6. print(a for a in getmembers(numpy) if isfunction(a[1]))
Output:
['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning',
'DataSource', 'E
Arguments and Parameters in Python
Be it any programming language, Arguments and Parameters are
the two words that cause a lot of confusion to programmers.
Sometimes, these two words are used interchangeably, but actually,
they have two different yet similar meanings. This tutorial explains
the differences between these two words and dives deep into the
concepts with examples.
Both arguments and parameters are variables/ constants passed
into a function. The difference is that:
1. Arguments are the variables passed to the function in the
function call.
2. Parameters are the variables used in the function definition.
3. The number of arguments and parameters should always be
equal except for the variable length argument list.
Example:
1. def add_func(a,b):
2. sum = a + b
3. return sum
4. num1 = int(input("Enter the value of the first number: "))
5. num2 = int(input("Enter the value of the second number: "))
6. print("Sum of two numbers: ",add_func(num1, num2))
Output:
Enter the value of the first number: 5
Enter the value of the second number: 2
Sum of two numbers: 7
Points to grasp from the Example:
1. (num1, num2) are in the function call, and (a, b) are in the
function definition.
2. (num1, num2) are arguments and (a, b) are parameters.
Mechanism:
Observe that in the above example, num1 and num2 are the values
in the function call with which we called the function. When the
function is invoked, a and b are replaced with num1 and num2, the
operation is performed on the arguments, and the result is returned.
Functions are written to avoid writing frequently used logic again
and again. To write a general logic, we use some variables, which
are parameters. They belong to the function definition. When we
need the function while writing our program, we need to apply the
function logic on the variables we used in our program, called
the arguments. We then call the function with the arguments.
Types of Arguments:
Based on how we pass arguments to parameters, arguments are of
two types:
1. Positional arguments
2. Keyword arguments
o Given some parameters, if the respective arguments are
passed in order one after the other, those arguments are
called the "Positional arguments."
o If the arguments are passed by assigning them to their
respective parameters in the function call with no significance
to the passing order, they are called "Keyword arguments".
Example:
1. def details(name, age, grade):
2. print("Details of student:", name)
3. print("age: ", age)
4. print("grade: ", grade)
5. details("Raghav", 12, 6)
6. details("Santhosh", grade = 6, age = 12)
Output:
Details of student: Raghav
age: 12
grade: 6
Details of student: Santhosh
age: 12
grade: 6