Unit 3
Functions
Python Built-in Functions
The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The python interpreter has several functions that are always present for use. These functions are known as Built-in Functions. There are several built-in functions in Python which are listed below:
Python abs() Function
The python abs() function is used to return the absolute value of a number. It takes only one argument, a number whose absolute value is to be returned. The argument can be an integer and floating-point number. If the argument is a complex number, then, abs() returns its magnitude.
Python abs() Function Example
- # integer number
- Integer = -20
- Print('Absolute value of -40 is:', abs(integer))
- # floating number
- Floating = -20.83
- Print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
Python all() Function
The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the all() function returns True.
Python all() Function Example
- # all values true
- k = [1, 3, 4, 6]
- Print(all(k))
- # all values false
- k = [0, False]
- Print(all(k))
- # one false value
- k = [1, 3, 7, 0]
- Print(all(k))
- # one true value
- k = [0, False, 5]
- Print(all(k))
- # empty iterable
- k = []
- Print(all(k))
Output:
True
False
False
False
True
Python bin() Function
The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.
Python bin() Function Example
- x = 10
- y = bin(x)
- Print (y)
Output:
0b1010
Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.
Python bool() Example
- Test1 = []
- Print(test1,'is',bool(test1))
- Test1 = [0]
- Print(test1,'is',bool(test1))
- Test1 = 0.0
- Print(test1,'is',bool(test1))
- Test1 = None
- Print(test1,'is',bool(test1))
- Test1 = True
- Print(test1,'is',bool(test1))
- Test1 = 'Easy string'
- Print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True
Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version of the bytearray() function.
It can create empty bytes object of the specified size.
Python bytes() Example
- String = "Hello World."
- Array = bytes(string, 'utf-8')
- Print(array)
Output:
b ' Hello World.'
Python callable() Function
A python callable() function in Python is something that can be called. This built-in function checks and returns true if the object passed appears to be callable, otherwise false.
Python callable() Function Example
- x = 8
- Print(callable(x))
Output:
False
Python compile() Function
The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.
Python compile() Function Example
- # compile string source to code
- Code_str = 'x=5\ny=10\nprint("sum =",x+y)'
- Code = compile(code_str, 'sum.py', 'exec')
- Print(type(code))
- Exec(code)
- Exec(x)
Output:
<class 'code'>
Sum = 15
Python exec() Function
The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a single expression.
Python exec() Function Example
- x = 8
- Exec('print(x==8)')
- Exec('print(x+4)')
Output:
True
12
Python sum() Function
As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e., list.
Python sum() Function Example
- s = sum([1, 2,4 ])
- Print(s)
- s = sum([1, 2, 4], 10)
- Print(s)
Output:
7
17
Python any() Function
The python any() function returns true if any item in an iterable is true. Otherwise, it returns False.
Python any() Function Example
- l = [4, 3, 2, 0]
- Print(any(l))
- l = [0, False]
- Print(any(l))
- l = [0, False, 5]
- Print(any(l))
- l = []
- Print(any(l))
Output:
True
False
True
False
Python ascii() Function
The python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.
Python ascii() Function Example
- NormalText = 'Python is interesting'
- Print(ascii(normalText))
- OtherText = 'Pythön is interesting'
- Print(ascii(otherText))
- Print('Pyth\xf6n is interesting')
Output:
'Python is interesting'
'Pyth\xf6n is interesting'
Pythön is interesting
Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.
Python bytearray() Example
- String = "Python is a programming language."
- # string with encoding 'utf-8'
- Arr = bytearray(string, 'utf-8')
- Print(arr)
Output:
Bytearray(b'Python is a programming language.')
Python eval() Function
The python eval() function parses the expression passed to it and runs python expression(code) within the program.
Python eval() Function Example
- x = 8
- Print(eval('x + 1'))
Output:
9
Python float()
The python float() function returns a floating-point number from a number or string.
Python float() Example
- # for integers
- Print(float(9))
- # for floats
- Print(float(8.19))
- # for string floats
- Print(float("-24.27"))
- # for string floats with whitespaces
- Print(float(" -17.19\n"))
- # string float error
- Print(float("xyz"))
Output:
9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'
Python format() Function
The python format() function returns a formatted representation of the given value.
Python format() Function Example
- # d, f and b are a type
- # integer
- Print(format(123, "d"))
- # float arguments
- Print(format(123.4567898, "f"))
- # binary format
- Print(format(12, "b"))
Output:
123
123.456790
1100
Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.
Python frozenset() Example
- # tuple of letters
- Letters = ('m', 'r', 'o', 't', 's')
- FSet = frozenset(letters)
- Print('Frozen set is:', fSet)
- Print('Empty frozen set is:', frozenset())
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()
Python getattr() Function
The python getattr() function returns the value of a named attribute of an object. If it is not found, it returns the default value.
Python getattr() Function Example
- Class Details:
- Age = 22
- Name = "Phill"
- Details = Details()
- Print('The age is:', getattr(details, "age"))
- Print('The age is:', details.age)
Output:
The age is: 22
The age is: 22
Python globals() Function
The python globals() function returns the dictionary of the current global symbol table.
A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes, etc.
Python globals() Function Example
- Age = 22
- Globals()['age'] = 22
- Print('The age is:', age)
Output:
The age is: 22
Python hasattr() Function
The python any() function returns true if any item in an iterable is true, otherwise it returns False.
Python hasattr() Function Example
- l = [4, 3, 2, 0]
- Print(any(l))
- l = [0, False]
- Print(any(l))
- l = [0, False, 5]
- Print(any(l))
- l = []
- Print(any(l))
Output:
True
False
True
False
Python iter() Function
The python iter() function is used to return an iterator object. It creates an object which can be iterated one element at a time.
Python iter() Function Example
- # list of numbers
- List = [1,2,3,4,5]
- ListIter = iter(list)
- # prints '1'
- Print(next(listIter))
- # prints '2'
- Print(next(listIter))
- # prints '3'
- Print(next(listIter))
- # prints '4'
- Print(next(listIter))
- # prints '5'
- Print(next(listIter))
Output:
1
2
3
4
5
Python len() Function
The python len() function is used to return the length (the number of items) of an object.
Python len() Function Example
- StrA = 'Python'
- Print(len(strA))
Output:
6
Python list()
The python list() creates a list in python.
Python list() Example
- # empty list
- Print(list())
- # string
- String = 'abcde'
- Print(list(String))
- # tuple
- Tuple = (1,2,3,4,5)
- Print(list(Tuple))
- # list
- List = [1,2,3,4,5]
- Print(list(List))
Output:
[]
['a', 'b', 'c', 'd', 'e']
[1,2,3,4,5]
[1,2,3,4,5]
Python locals() Function
The python locals() method updates and returns the dictionary of the current local symbol table.
A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes, etc.
Python locals() Function Example
- Def localsAbsent():
- Return locals()
- Def localsPresent():
- Present = True
- Return locals()
- Print('localsNotPresent:', localsAbsent())
- Print('localsPresent:', localsPresent())
Output:
LocalsAbsent: {}
LocalsPresent: {'present': True}
Python map() Function
The python map() function is used to return a list of results after applying a given function to each item of an iterable(list, tuple etc.).
Python map() Function Example
- Def calculateAddition(n):
- Return n+n
- Numbers = (1, 2, 3, 4)
- Result = map(calculateAddition, numbers)
- Print(result)
- # converting map object to set
- NumbersAddition = set(result)
- Print(numbersAddition)
Output:
<map object at 0x7fb04a6bec18>
{8, 2, 4, 6}
Python memoryview() Function
The python memoryview() function returns a memoryview object of the given argument.
Python memoryview () Function Example
- #A random bytearray
- RandomByteArray = bytearray('ABC', 'utf-8')
- Mv = memoryview(randomByteArray)
- # access the memory view's zeroth index
- Print(mv[0])
- # It create byte from memory view
- Print(bytes(mv[0:2]))
- # It create list from memory view
- Print(list(mv[0:3]))
Output:
65
b'AB'
[65, 66, 67]
Python object()
The python object() returns an empty object. It is a base for all the classes and holds the built-in properties and methods which are default for all the classes.
Python object() Example
- Python = object()
- Print(type(python))
- Print(dir(python))
Output:
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__']
Python open() Function
The python open() function opens the file and returns a corresponding file object.
Python open() Function Example
- # opens python.text file of the current directory
- f = open("python.txt")
- # specifying full path
- f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Python chr() Function
Python chr() function is used to get a string representing a character which points to a Unicode code integer. For example, chr(97) returns the string 'a'. This function takes an integer argument and throws an error if it exceeds the specified range. The standard range of the argument is from 0 to 1,114,111.
Python chr() Function Example
- # Calling function
- Result = chr(102) # It returns string representation of a char
- Result2 = chr(112)
- # Displaying result
- Print(result)
- Print(result2)
- # Verify, is it string type?
- Print("is it string type:", type(result) is str)
Output:
ValueError: chr() arg not in range(0x110000)
Python complex()
Python complex() function is used to convert numbers or string into a complex number. This method takes two optional parameters and returns a complex number. The first parameter is called a real and second as imaginary parts.
Python complex() Example
- # Python complex() function example
- # Calling function
- a = complex(1) # Passing single parameter
- b = complex(1,2) # Passing both parameters
- # Displaying result
- Print(a)
- Print(b)
Output:
(1.5+0j)
(1.5+2.2j)
Python delattr() Function
Python delattr() function is used to delete an attribute from a class. It takes two parameters, first is an object of the class and second is an attribute which we want to delete. After deleting the attribute, it no longer available in the class and throws an error if try to call it using the class object.
Python delattr() Function Example
- Class Student:
- Id = 101
- Name = "Pranshu"
- Email = "pranshu@abc.com"
- # Declaring function
- Def getinfo(self):
- Print(self.id, self.name, self.email)
- s = Student()
- s.getinfo()
- Delattr(Student,'course') # Removing attribute which is not available
- s.getinfo() # error: throws an error
Output:
101 Pranshu pranshu@abc.com
AttributeError: course
Python dir() Function
Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be called and must return the list of attributes. It takes a single object type argument.
Python dir() Function Example
- # Calling function
- Att = dir()
- # Displaying result
- Print(att)
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__']
Python divmod() Function
Python divmod() function is used to get remainder and quotient of two numbers. This function takes two numeric arguments and returns a tuple. Both arguments are required and numeric
Python divmod() Function Example
- # Python divmod() function example
- # Calling function
- Result = divmod(10,2)
- # Displaying result
- Print(result)
Output:
(5, 0)
Python enumerate() Function
Python enumerate() function returns an enumerated object. It takes two parameters, first is a sequence of elements and the second is the start index of the sequence. We can get the elements in sequence either through a loop or next() method.
Python enumerate() Function Example
- # Calling function
- Result = enumerate([1,2,3])
- # Displaying result
- Print(result)
- Print(list(result))
Output:
<enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]
Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary provides three different constructors to create a dictionary:
- If no argument is passed, it creates an empty dictionary.
- If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
- If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.
Python dict() Example
- # Calling function
- Result = dict() # returns an empty dictionary
- Result2 = dict(a=1,b=2)
- # Displaying result
- Print(result)
- Print(result2)
Output:
{}
{'a': 1, 'b': 2}
Python filter() Function
Python filter() function is used to get filtered elements. This function takes two arguments, first is a function and the second is iterable. The filter function returns a sequence of those elements of iterable object for which function returns true value.
The first argument can be none, if the function is not available and returns only elements that are true.
Python filter() Function Example
- # Python filter() function example
- Def filterdata(x):
- If x>5:
- Return x
- # Calling function
- Result = filter(filterdata,(1,2,6))
- # Displaying result
- Print(list(result))
Output:
[6]
Python hash() Function
Python hash() function is used to get the hash value of an object. Python calculates the hash value by using the hash algorithm. The hash values are integers and used to compare dictionary keys during a dictionary lookup. We can hash only the types which are given below:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.
Python hash() Function Example
- # Calling function
- Result = hash(21) # integer value
- Result2 = hash(22.2) # decimal value
- # Displaying result
- Print(result)
- Print(result2)
Output:
21
461168601842737174
Python help() Function
Python help() function is used to get help related to the object passed during the call. It takes an optional parameter and returns help information. If no argument is given, it shows the Python help console. It internally calls python's help function.
Python help() Function Example
- # Calling function
- Info = help() # No argument
- # Displaying result
- Print(info)
Output:
Welcome to Python 3.5's help utility!
Python min() Function
Python min() function is used to get the smallest element from the collection. This function takes two arguments, first is a collection of elements and second is key, and returns the smallest element from the collection.
Python min() Function Example
- # Calling function
- Small = min(2225,325,2025) # returns smallest element
- Small2 = min(1000.25,2025.35,5625.36,10052.50)
- # Displaying result
- Print(small)
- Print(small2)
Output:
325
1000.25
Python set() Function
In python, a set is a built-in class, and this function is a constructor of this class. It is used to create a new set using elements passed during the call. It takes an iterable object as an argument and returns a new set object.
Python set() Function Example
- # Calling function
- Result = set() # empty set
- Result2 = set('12')
- Result3 = set('javatpoint')
- # Displaying result
- Print(result)
- Print(result2)
- Print(result3)
Output:
Set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}
Python hex() Function
Python hex() function is used to generate hex value of an integer argument. It takes an integer argument and returns an integer converted into a hexadecimal string. In case, we want to get a hexadecimal value of a float, then use float.hex() function.
Python hex() Function Example
- # Calling function
- Result = hex(1)
- # integer value
- Result2 = hex(342)
- # Displaying result
- Print(result)
- Print(result2)
Output:
0x1
0x156
Python id() Function
Python id() function returns the identity of an object. This is an integer which is guaranteed to be unique. This function takes an argument as an object and returns a unique integer number which represents identity. Two objects with non-overlapping lifetimes may have the same id() value.
Python id() Function Example
- # Calling function
- Val = id("Javatpoint") # string object
- Val2 = id(1200) # integer object
- Val3 = id([25,336,95,236,92,3225]) # List object
- # Displaying result
- Print(val)
- Print(val2)
- Print(val3)
Output:
139963782059696
139963805666864
139963781994504
Python setattr() Function
Python setattr() function is used to set a value to the object's attribute. It takes three arguments, i.e., an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it.
Python setattr() Function Example
- Class Student:
- Id = 0
- Name = ""
- Def __init__(self, id, name):
- Self.id = id
- Self.name = name
- Student = Student(102,"Sohan")
- Print(student.id)
- Print(student.name)
- #print(student.email) product error
- Setattr(student, 'email','sohan@abc.com') # adding new attribute
- Print(student.email)
Output:
102
Sohan
Sohan@abc.com
Python slice() Function
Python slice() function is used to get a slice of elements from the collection of elements. 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.
Python slice() Function Example
- # Calling function
- Result = slice(5) # returns slice object
- Result2 = slice(0,5,3) # returns slice object
- # Displaying result
- Print(result)
- Print(result2)
Output:
Slice(None, 5, None)
Slice(0, 5, 3)
Python sorted() Function
Python sorted() function is used to sort elements. By default, it sorts elements in an ascending order but can be sorted in descending also. It takes four arguments and returns a collection in sorted order. In the case of a dictionary, it sorts only keys, not values.
Python sorted() Function Example
- Str = "javatpoint" # declaring string
- # Calling function
- Sorted1 = sorted(str) # sorting string
- # Displaying result
- Print(sorted1)
Output:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
Python next() Function
Python next() function is used to fetch next item from the collection. It takes two arguments, i.e., an iterator and a default value, and returns an element.
This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.
Python next() Function Example
- Number = iter([256, 32, 82]) # Creating iterator
- # Calling function
- Item = next(number)
- # Displaying result
- Print(item)
- # second item
- Item = next(number)
- Print(item)
- # third item
- Item = next(number)
- Print(item)
Output:
256
32
82
Python input() Function
Python input() function is used to get an input from the user. It prompts for the user input and reads a line. After reading data, it converts it into a string and returns it. It throws an error EOFError if EOF is read.
Python input() Function Example
- # Calling function
- Val = input("Enter a value: ")
- # Displaying result
- Print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
Python int() Function
Python int() function is used to get an integer value. It returns an expression converted into an integer number. If the argument is a floating-point, the conversion truncates the number. If the argument is outside the integer range, then it converts the number into a long type.
If the number is not a number or if a base is given, the number must be a string.
Python int() Function Example
- # Calling function
- Val = int(10) # integer value
- Val2 = int(10.52) # float value
- Val3 = int('10') # string value
- # Displaying result
- Print("integer values :",val, val2, val3)
Output:
Integer values : 10 10 10
Python isinstance() Function
Python isinstance() function is used to check whether the given object is an instance of that class. If the object belongs to the class, it returns true. Otherwise returns False. It also returns true if the class is a subclass.
The isinstance() function takes two arguments, i.e., object and classinfo, and then it returns either True or False.
Python isinstance() function Example
- Class Student:
- Id = 101
- Name = "John"
- Def __init__(self, id, name):
- Self.id=id
- Self.name=name
- Student = Student(1010,"John")
- Lst = [12,34,5,6,767]
- # Calling function
- Print(isinstance(student, Student)) # isinstance of Student class
- Print(isinstance(lst, Student))
Output:
True
False
Python oct() Function
Python oct() function is used to get an octal value of an integer number. This method takes an argument and returns an integer converted into an octal string. It throws an error TypeError, if argument type is other than an integer.
Python oct() function Example
- # Calling function
- Val = oct(10)
- # Displaying result
- Print("Octal value of 10:",val)
Output:
Octal value of 10: 0o12
Python ord() Function
The python ord() function returns an integer representing Unicode code point for the given Unicode character.
Python ord() function Example
- # Code point of an integer
- Print(ord('8'))
- # Code point of an alphabet
- Print(ord('R'))
- # Code point of a character
- Print(ord('&'))
Output:
56
82
38
Python pow() Function
The python pow() function is used to compute the power of a number. It returns x to the power of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e. (x, y) % z.
Python pow() function Example
- # positive x, positive y (x**y)
- Print(pow(4, 2))
- # negative x, positive y
- Print(pow(-4, 2))
- # positive x, negative y (x**-y)
- Print(pow(4, -2))
- # negative x, negative y
- Print(pow(-4, -2))
Output:
16
16
0.0625
0.0625
Python print() Function
The python print() function prints the given object to the screen or other standard output devices.
Python print() function Example
- Print("Python is programming language.")
- x = 7
- # Two objects passed
- Print("x =", x)
- y = x
- # Three objects passed
- Print('x =', x, '= y')
Output:
Python is programming language.
x = 7
x = 7 = y
Python range() Function
The python range() function returns an immutable sequence of numbers starting from 0 by default, increments by 1 (by default) and ends at a specified number.
Python range() function Example
- # empty range
- Print(list(range(0)))
- # using the range(stop)
- Print(list(range(4)))
- # using the range(start, stop)
- Print(list(range(1,7 )))
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
Python reversed() Function
The python reversed() function returns the reversed iterator of the given sequence.
Python reversed() function Example
- # for string
- String = 'Java'
- Print(list(reversed(String)))
- # for tuple
- Tuple = ('J', 'a', 'v', 'a')
- Print(list(reversed(Tuple)))
- # for range
- Range = range(8, 12)
- Print(list(reversed(Range)))
- # for list
- List = [1, 2, 7, 5]
- Print(list(reversed(List)))
Output:
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]
Python round() Function
The python round() function rounds off the digits of a number and returns the floating point number.
Python round() Function Example
- # for integers
- Print(round(10))
- # for floating point
- Print(round(10.8))
- # even choice
- Print(round(6.6))
Output:
10
11
7
Python issubclass() Function
The python issubclass() function returns true if object argument(first argument) is a subclass of second class(second argument).
Python issubclass() Function Example
- Class Rectangle:
- Def __init__(rectangleType):
- Print('Rectangle is a ', rectangleType)
- Class Square(Rectangle):
- Def __init__(self):
- Rectangle.__init__('square')
- Print(issubclass(Square, Rectangle))
- Print(issubclass(Square, list))
- Print(issubclass(Square, (list, Rectangle)))
- Print(issubclass(Rectangle, (list, Rectangle)))
Output:
True
False
True
True
Python str
The python str() converts a specified value into a string.
Python str() Function Example
- Str('4')
Output:
'4'
Python tuple() Function
The python tuple() function is used to create a tuple object.
Python tuple() Function Example
- t1 = tuple()
- Print('t1=', t1)
- # creating a tuple from a list
- t2 = tuple([1, 6, 9])
- Print('t2=', t2)
- # creating a tuple from a string
- t1 = tuple('Java')
- Print('t1=',t1)
- # creating a tuple from a dictionary
- t1 = tuple({4: 'four', 5: 'five'})
- Print('t1=',t1)
Output:
t1= ()
t2= (1, 6, 9)
t1= ('J', 'a', 'v', 'a')
t1= (4, 5)
Python type()
The python type() returns the type of the specified object if a single argument is passed to the type() built in function. If three arguments are passed, then it returns a new type object.
Python type() Function Example
- List = [4, 5]
- Print(type(List))
- Dict = {4: 'four', 5: 'five'}
- Print(type(Dict))
- Class Python:
- a = 0
- InstanceOfPython = Python()
- Print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
Python vars() function
The python vars() function returns the __dict__ attribute of the given object.
Python vars() Function Example
- Class Python:
- Def __init__(self, x = 7, y = 9):
- Self.x = x
- Self.y = y
- InstanceOfPython = Python()
- Print(vars(InstanceOfPython))
Output:
{'y': 9, 'x': 7}
Python zip() Function
The python zip() Function returns a zip object, which maps a similar index of multiple containers. It takes iterables (can be zero or more), makes it an iterator that aggregates the elements based on iterables passed, and returns an iterator of tuples.
Python zip() Function Example
- NumList = [4,5, 6]
- StrList = ['four', 'five', 'six']
- # No iterables are passed
- Result = zip()
- # Converting itertor to list
- ResultList = list(result)
- Print(resultList)
- # Two iterables are passed
- Result = zip(numList, strList)
- # Converting itertor to set
- ResultSet = set(result)
- Print(resultSet)
Output:
[]
{(5, 'five'), (4, 'four'), (6, 'six')}
Modules in python
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py
Defprint_func( par ):
Print "Hello : ", par
Return
The import Statement
You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −
Import module1[, module2[,... ModuleN]
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script −
#!/usr/bin/python
# Import module support
Import support
# Now you can call defined function that module as follows
Support.print_func("Zara")
When the above code is executed, it produces the following result −
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.
The from...import Statement
Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −
Frommodname import name1[, name2[, ... NameN]]
For example, to import the function fibonacci from the module fib, use the following statement −
From fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using the following import statement −
Frommodname import *
This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following sequences −
- The current directory.
- If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
- If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.
Here is a typical PYTHONPATH from a Windows system −
Set PYTHONPATH = c:\python20\lib;
And here is a typical PYTHONPATH from a UNIX system −
Set PYTHONPATH = /usr/local/lib/python
Namespaces and Scoping
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python
Money = 2000
DefAddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
Print Money
AddMoney()
Print Money
The dir( ) Function
The dir() built-in function returns a sorted list of strings containing the names defined by a module.
The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −
#!/usr/bin/python
# Import built-in module math
Import math
Content = dir(math)
Print content
When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.
The globals() and locals() Functions
The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.
The reload() Function
When the module is imported into a script, the code in the top-level portion of a module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −
Reload(module_name)
Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −
Reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code −
#!/usr/bin/python
Def Pots():
Print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above −
- Phone/Isdn.py file having function Isdn()
- Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
- Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows −
From Pots import Pots
FromIsdn import Isdn
From G3 import G3
After you add these lines to __init__.py, you have all of these classes available when you import the Phone package.
#!/usr/bin/python
# Now import your Phone Package.
Import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result −
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.
Functions ar the foremost necessary side of associate application. A perform may be outlined because the organized block of reusable code, which may be known as whenever needed.
Python permits United States of America to divide an oversized program into the fundamental building blocks referred to as a perform. The perform contains the set of programming statements fencelike by . A perform may be known as multiple times to supply reusability and modularity to the Python program.
The perform helps to software engineer to interrupt the program into the smaller half. It organizes the code terribly effectively and avoids the repetition of the code. Because the program grows, perform makes the program a lot of organized.
Python offer United States of America varied constitutional functions like range() or print(). Although, the user will produce its functions, which may be known as user-defined functions.
There ar primarily 2 forms of functions.
• User-define functions - The user-defined functions ar those outline by the user to perform the precise task.
• Built-in functions - The constitutional functions ar those functions that ar pre-defined in Python.
In this tutorial, we'll discuss the user outline functions.
Advantage of Functions in Python
There ar the subsequent blessings of Python functions.
• Using functions, we will avoid revising constant logic/code title of respectin and once more in a very program.
• We will decision Python functions multiple times in a very program and anyplace in a very program.
• We will track an oversized Python program simply once it's divided into multiple functions.
• Reusability is that the main action of Python functions.
• However, perform vocation is usually overhead in a very Python program.
Creating a perform
Python provides the def keyword to outline the perform. The syntax of the outline perform is given below.
Syntax:
1. defmy_function(parameters):
2. function_block
3. come back expression
Let's perceive the syntax of functions definition.
• The def keyword, together with the perform name is employed to outline the perform.
• The symbol rule should follow the perform name.
• A perform accepts the parameter (argument), and that they may be facultative.
• The perform block is started with the colon (:), and block statements should be at constant indentation.
• The come back statement is employed to come back the worth. A perform will have only 1 come back
Function Calling
In Python, after the function is created, we can call it from another function. A function must be defined before the function call; otherwise, the Python interpreter gives an error. To call the function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello World".
- #function definition
- Def hello_world():
- Print("hello world")
- # function calling
- Hello_world()
Output:
Hello world
The return statement
The return statement is used at the end of the function and returns the result of the function. It terminates the function execution and transfers the result where the function is called. The return statement cannot be used outside of the function.
Syntax
- Return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller function. If the return statement has no expression or does not exist itself in the function then it returns the None object.
Consider the following example:
Example 1
- # Defining function
- Def sum():
- a = 10
- b = 20
- c = a+b
- Return c
- # calling sum() function in print statement
- Print("The sum is:",sum())
Output:
The sum is: 30
In the above code, we have defined the function named sum, and it has a statement c = a+b, which computes the given values, and the result is returned by the return statement to the caller function.
Example 2 Creating function without return statement
- # Defining function
- Def sum():
- a = 10
- b = 20
- c = a+b
- # calling sum() function in print statement
- Print(sum())
Output:
None
In the above code, we have defined the same function without the return statement as we can see that the sum() function returned the None object to the caller function.
Arguments in function
The arguments are types of information which can be passed into the function. The arguments are specified in the parentheses. We can pass any number of arguments, but they must be separate them with a comma.
Consider the following example, which contains a function that accepts a string as the argument.
Example 1
- #defining the function
- Def func (name):
- Print("Hi ",name)
- #calling the function
- Func("Devansh")
Output:
Hi Devansh
Example 2
- #Python function to calculate the sum of two variables
- #defining the function
- Def sum (a,b):
- Return a+b;
- #taking values from the user
- a = int(input("Enter a: "))
- b = int(input("Enter b: "))
- #printing the sum of a and b
- Print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
Call by reference in Python
In Python, call by reference means passing the actual value as an argument in the function. All the functions are called by reference, i.e., all the changes made to the reference inside the function revert back to the original value referred by the reference.
Example 1 Passing Immutable Object (List)
- #defining the function
- Def change_list(list1):
- List1.append(20)
- List1.append(30)
- Print("list inside function = ",list1)
- #defining the list
- List1 = [10,30,40,50]
- #calling the function
- Change_list(list1)
- Print("list outside function = ",list1)
Output:
List inside function = [10, 30, 40, 50, 20, 30]
List outside function = [10, 30, 40, 50, 20, 30]
Example 2 Passing Mutable Object (String)
- #defining the function
- Def change_string (str):
- Str = str + " Hows you "
- Print("printing the string inside function :",str)
- String1 = "Hi I am there"
- #calling the function
- Change_string(string1)
- Print("printing the string outside function :",string1)
Output:
Printing the string inside function : Hi I am there Hows you
Printing the string outside function : Hi I am there
Types of arguments
There may be several types of arguments which can be passed at the time of function call.
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required Arguments
Till now, we have learned about function calling in Python. However, we can provide the arguments at the time of the function call. As far as the required arguments are concerned, these are the arguments which are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, the Python interpreter will show the error.
Consider the following example.
Example 1
- Def func(name):
- Message = "Hi "+name
- Return message
- Name = input("Enter the name:")
- Print(func(name))
Output:
Enter the name: John
Hi John
Example 2
- #the function simple_interest accepts three arguments and returns the simple interest accordingly
- Def simple_interest(p,t,r):
- Return (p*t*r)/100
- p = float(input("Enter the principle amount? "))
- r = float(input("Enter the rate of interest? "))
- t = float(input("Enter the time in years? "))
- Print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount: 5000
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0
Example 3
- #the function calculate returns the sum of two arguments a and b
- Def calculate(a,b):
- Return a+b
- Calculate(10) # this causes an error as we are missing a required arguments b.
Output:
TypeError: calculate() missing 1 required positional argument: 'b'
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not provided at the time of function call, then that argument can be initialized with the value given in the definition even if the argument is not specified at the function call.
Example 1
- Def printme(name,age=22):
- Print("My name is",name,"and age is",age)
- Printme(name = "john")
Output:
My name is John and age is 22
Example 2
- Def printme(name,age=22):
- Print("My name is",name,"and age is",age)
- Printme(name = "john") #the variable age is not passed into the function however the default value of age is considered in the function
- Printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as age
Output:
My name is john and age is 22
My name is David and age is 10
Variable-length Arguments (*args)
In large projects, sometimes we may not know the number of arguments to be passed in advance. In such cases, Python provides us the flexibility to offer the comma-separated values which are internally treated as tuples at the function call. By using the variable-length arguments, we can pass any number of arguments.
However, at the function definition, we define the variable-length argument using the *args (star) as *<variable - name >.
Consider the following example.
Example
- Def printme(*names):
- Print("type of passed argument is ",type(names))
- Print("printing the passed arguments...")
- For name in names:
- Print(name)
- Printme("john","David","smith","nick")
Output:
Type of passed argument is <class 'tuple'>
Printing the passed arguments...
John
David
Smith
Nick
In the above code, we passed *names as variable-length argument. We called the function and passed values which are treated as tuple internally. The tuple is an iterablesequence the same as the list. To print the given values, we iterated *arg names using for loop.
Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling and definition. If the same match is found, the values of the arguments are copied in the function definition.
Consider the following example.
Example 1
- #function func is called with the name and message as the keyword arguments
- Def func(name,message):
- Print("printing the message with",name,"and ",message)
- #name and message is copied with the values John and hello respectively
- Func(name = "John",message="hello")
Output:
Printing the message with John and hello
Example 2 providing the values in different order at the calling
- #The function simple_interest(p, t, r) is called with the keyword arguments the order of arguments doesn't matter in this case
- Def simple_interest(p,t,r):
- Return (p*t*r)/100
- Print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:
Simple Interest: 1900.0
If we provide the different name of arguments at the time of function call, an error will be thrown.
Consider the following example.
Example 3
- #The function simple_interest(p, t, r) is called with the keyword arguments.
- Def simple_interest(p,t,r):
- Return (p*t*r)/100
- # doesn't find the exact match of the name of the arguments (keywords)
- Print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))
Output:
TypeError: simple_interest() got an unexpected keyword argument 'time'
The Python allows us to provide the mix of the required arguments and keyword arguments at the time of function call. However, the required argument must not be given after the keyword argument, i.e., once the keyword argument is encountered in the function call, the following arguments must also be the keyword arguments.
Consider the following example.
Example 4
- Def func(name1,message,name2):
- Print("printing the message with",name1,",",message,",and",name2)
- #the first argument is not the keyword argument
- Func("John",message="hello",name2="David")
Output:
Printing the message with John , hello ,and David
The following example will cause an error due to an in-proper mix of keyword and required arguments being passed in the function call.
Example 5
- Def func(name1,message,name2):
- Print("printing the message with",name1,",",message,",and",name2)
- Func("John",message="hello","David")
Output:
SyntaxError: positional argument follows keyword argument
Python provides the facility to pass the multiple keyword arguments which can be represented as **kwargs. It is similar as the *args but it stores the argument in the dictionary format.
This type of arguments is useful when we do not know the number of arguments in advance.
Consider the following example:
Example 6: Many arguments using Keyword argument
- Def food(**kwargs):
- Print(kwargs)
- Food(a="Apple")
- Food(fruits="Orange", Vagitables="Carrot")
Output:
{'a': 'Apple'}
{'fruits': 'Orange', 'Vagitables': 'Carrot'}
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
- Global variables
- Local variables
The variable defined outside any function is known to have a global scope, whereas the variable defined inside a function is known to have a local scope.
Consider the following example.
Example 1 Local Variable
- Def print_message():
- Message = "hello !! I am going to print a message." # the variable message is local to the function itself
- Print(message)
- Print_message()
- Print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
Hello !! I am going to print a message.
File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
Print(message)
NameError: name 'message' is not defined
Example 2 Global Variable
- Def calculate(*args):
- Sum=0
- For arg in args:
- Sum = sum +arg
- Print("The sum is",sum)
- Sum=0
- Calculate(10,20,30) #60 will be printed as the sum
- Print("Value of sum outside the function:",sum) # 0 will be printed Output:
Output:
The sum is 60
Value of sum outside the function: 0
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −
#!/usr/bin/python
# Function definition is here
Defprintme(str):
"This prints a passed string into this function"
Printstr
Return;
# Now you can call printme function
Printme("I'm first call to user defined function!")
Printme("Again second call to the same function")
When the above code is executed, it produces the following result −
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −
#!/usr/bin/python
# Function definition is here
Defchangeme(mylist):
"This changes a passed list into this function"
Mylist.append([1,2,3,4]);
Print"Values inside the function: ",mylist
Return
# Now you can call changeme function
Mylist=[10,20,30];
Changeme(mylist);
Print"Values outside the function: ",mylist
Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
#!/usr/bin/python
# Function definition is here
Defchangeme(mylist):
"This changes a passed list into this function"
Mylist=[1,2,3,4];# This would assig new reference in mylist
Print"Values inside the function: ",mylist
Return
# Now you can call changeme function
Mylist=[10,20,30];
Changeme(mylist);
Print"Values outside the function: ",mylist
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
You can call a function by using the following types of formal arguments −
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −
#!/usr/bin/python
# Function definition is here
Defprintme( str ):
"This prints a passed string into this function"
Printstr
Return;
# Now you can call printme function
Printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
Printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −
#!/usr/bin/python
# Function definition is here
Defprintme( str ):
"This prints a passed string into this function"
Printstr
Return;
# Now you can call printme function
Printme(str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python
# Function definition is here
Defprintinfo( name, age ):
"This prints a passed info into this function"
Print "Name: ", name
Print "Age ", age
Return;
# Now you can call printinfo function
Printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
#!/usr/bin/python
# Function definition is here
Defprintinfo( name, age = 35 ):
"This prints a passed info into this function"
Print "Name: ", name
Print "Age ", age
Return;
# Now you can call printinfo function
Printinfo( age=50, name="miki" )
Printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
Deffunctionname([formal_args,] *var_args_tuple ):
"function_docstring"
Function_suite
Return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −
#!/usr/bin/python
# Function definition is here
Defprintinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
Print "Output is: "
Print arg1
Forvar in vartuple:
Printvar
Return;
# Now you can call printinfo function
Printinfo( 10 )
Printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
The Anonymous Functions
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
- Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
- An anonymous function cannot be a direct call to print because lambda requires an expression
- Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
- Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
Lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
#!/usr/bin/python
# Function definition is here
Sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
Print "Value of total : ", sum( 10, 20 )
Print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
The return Statement
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows −
#!/usr/bin/python
# Function definition is here
Def sum( arg1, arg2 ):
# Add both the parameters and return them."
Total = arg1 + arg2
Print "Inside the function : ", total
Return total;
# Now you can call sum function
Total = sum( 10, 20 );
Print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
An identifier is a name used for a class, a variable, a method, or a parameter. The following definitions are useful:
- Formal parameter — the identifier used in a method to stand for the value that is passed into the method by a caller.
- For example, amount is a formal parameter of processDeposit
- Actual parameter — the actual value that is passed into the method by a caller.
- For example, the 200 used when processDeposit is called is an actual parameter.
- Actual parameters are often called arguments
When a method is called, the formal parameter is temporarily "bound" to the actual parameter. The method uses the formal parameter to stand for the actual value that the caller wants to be used.
For example, here the processDeposit method uses the formal parameter amount to stand for the actual value used in the procedure call:
Balance = balance + amount ;
Note: formal parameters are bound to an actual value only as long as their method is active. When a method returns to its caller, the formal parameters no longer contain any values. They cannot be used to store the state of an object.
Actual Parameter | Formal Parameter |
The arguments that are passed in a function call are called actual arguments. | The formal arguments are the parameters/arguments in a function declaration. |
Data type not required. But data type should match with corresponding data type of formal parameters. | Data types needs to be mentioned. |
Actual parameters are the parameters which you specify when you call the Functions or Procedures. | A formal parameter is a parameter which you specify when you define the function. |
The actual parameters are passed by the calling function. | The formal parameters are in the called function. |
Ex: | Ex: |
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Python Recursive Function
In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.
Recursive Function in Python
Following is an example of a recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function
Deffactorial(x):
"""This is a recursive function
To find the factorial of an integer"""
If x == 1:
Return1
Else:
Return (x * factorial(x-1))
Num = 3
Print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself.
When we call this function with a positive integer, it will recursively call itself by decreasing the number.
Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps.
Factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1
3 * 2 # return from 2nd call
6 # return from 1st call
Let's look at an image that shows a step-by-step process of what is going on:
Working of a recursive factorial function
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results in RecursionError. Let's look at one such condition.
Defrecursor():
Recursor()
Recursor()
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Advantages of Recursion
- Recursive functions make the code look clean and elegant.
- A complex task can be broken down into simpler sub-problems using recursion.
- Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
- Sometimes the logic behind recursion is hard to follow through.
- Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
- Recursive functions are hard to debug.
The most basic organisation in Python is that the sequence. Every component of a sequence is assigned variety - its position or index. The primary index is zero, the second index is one, and then forth.
Python has six inherent varieties of sequences, however the foremost common ones ar lists and tuples, that we'd see during this tutorial.
There ar bound stuff you will do with all the sequence sorts. These operations embrace classification, slicing, adding, multiplying, and checking for membership. Additionally, Python has inherent functions for locating the length of a sequence and for locating its largest and smallest parts.
Python Lists
The list is the most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets. For example −
List1 =['physics','chemistry',1997,2000];
List2 =[1,2,3,4,5];
List3 =["a","b","c","d"];
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −
#!/usr/bin/python3
List1 =['physics','chemistry',1997,2000]
List2 =[1,2,3,4,5,6,7]
Print("list1[0]: ", list1[0])
Print("list2[1:5]: ", list2[1:5])
When the above code is executed, it produces the following result −
List1[0]: physics
List2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −
#!/usr/bin/python3
List=['physics','chemistry',1997,2000]
Print("Value available at index 2 : ", list[2])
List[2]=2001
Print("New value available at index 2 : ", list[2])
Note− The append() method is discussed in the subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 : 1997
New value available at index 2 : 2001
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting. You can use the remove() method if you do not know exactly which items to delete. For example −
#!/usr/bin/python3
List=['physics','chemistry',1997,2000]
Print(list)
Del list[2]
Print("After deleting value at index 2 : ", list)
When the above code is executed, it produces the following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Note−remove() method is discussed in subsequent section.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python Expression | Results | Description |
Len([1, 2, 3]) | 3 | Length |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | Concatenation |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | Repetition |
3 in [1, 2, 3] | True | Membership |
For x in [1,2,3] : print (x,end = ' ') | 1 2 3 | Iteration |
Indexing, Slicing and Matrixes
Since lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming the following input −
L =['C++'', 'Java', 'Python']
Python Expression | Results | Description |
L[2] | 'Python' | Offsets start at zero |
L[-2] | 'Java' | Negative: count from the right |
L[1:] | ['Java', 'Python'] | Slicing fetches sections |
Built-in List Functions and Methods
Python includes the following list functions −
Sr.No. | Function & Description |
1 | Len(list) Gives the total length of the list. |
2 | Max(list) Returns item from the list with max value. |
3 | Min(list) Returns item from the list with min value. |
4 | List(seq) Converts a tuple into list. |
Python includes the following list methods −
Sr.No. | Methods & Description |
1 | List.append(obj) Appends object obj to list |
2 | List.count(obj) Returns count of how many times obj occurs in list |
3 | List.extend(seq) Appends the contents of seq to list |
4 | List.index(obj) Returns the lowest index in list that obj appears |
5 | List.insert(index, obj) Inserts object obj into list at offset index |
6 | List.pop(obj = list[-1]) Removes and returns last object or obj from list |
7 | List.remove(obj) Removes object obj from list |
8 | List.reverse() Reverses objects of list in place |
9 | List.sort([func]) Sorts objects of list, use compare func if given |
Reference Books:
1 Computers Today by Sanders.
2 Fundamentals of Computers TTTI Publication.
3 Learning Python by Mark Lutz, 5th edition
4 Python cookbook, by David Beazley , 3rd Edition
5 Python Essential Reference, by David Beazley , 4th edition
6 Python in a Nutshell, by Alex Mortelli, 2nd Edition.
7 Python programming: An Introduction to computer science, by John Zelle, 2nd Edition.