Python – Lecture 3 S.Venkatesan Network Security and Cryptography Lab Department of Information Technology Indian Institute of Information Technology, Allahabad venkat@iiita.ac.in 1 IIIT Allahabad Acknowledgement: The example scripts and some figures are copied from various sources. Thanks to all authors and sources which made those contents public and usable for educational purpose 2 IIIT Allahabad Frozenset • The frozenset() is an inbuilt function is Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable. Syntax frozenset(iterable_object_name) Example Student = {"name”, "Ankit", "age”, "Allahabad"} key = frozenset(Student) print(key) Output ({‘name’, ’Ankit,’ ’age’, ’Allahabad’}) IIIT Allahabad 3 Dictionary • A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = thisdict["model"] x = thisdict.get("model”) IIIT Allahabad 4 Dictionary-Examples thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) IIIT Allahabad thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict) 5 Dictionary-Examples thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict print(thisdict) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.clear() print(thisdict) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = thisdict.copy() print(mydict) You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2. IIIT Allahabad 6 Functions • A function is a block of code which only runs when it is called. • You can pass data, known as parameters, into a function and return data as a result. • Syntax def function-name(arguments): statement 1 statement 2 Optional . statement n return variable IIIT Allahabad 7 Example def my_function(fname, lname): print(fname + " " + lname) my_function("Emil", "Refsnes") def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") IIIT Allahabad 8 Arguments ( Keyword Arguments, **kwargs & Arbitrary Arguments, *args) & Return def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") def my_function(x): return 5 * x IIIT Allahabad 9 Recursion def tri_recursion(k): if(k > 0): result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6) IIIT Allahabad 10 import In Python, a module is a self-contained file with Python statements and definitions. For example, file.py, can be considered a module named file. hello.py def my_function(): print("Hello World") import hello hello.my_function() from hello import my_function my_function() hello.py def my_function(): print("Hello World") name = "Nicholas“ import hello hello.my_function() print(hello.name) Question: module vs package IIIT Allahabad 11 Lambda function • • A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax: lambda arguments : expression x = lambda a : a + 10 print(x(5)) x = lambda a, b : a * b print(x(5, 6)) • Advantage: A small "disposable" one-time-use utility code, ordinary functions don't work so well. They can actually makes the code significantly less readable. This is where lambda functions come in. They allow one to inject that disposable utility code straight into the point of the call, where it is necessary. IIIT Allahabad 12 Map function • This function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) • Syntax map(function, iterable) • PARAMETERS – – • Function Numbers (iterable) Return Value – List def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) IIIT Allahabad 13 Filter • It requires the function to return boolean values (true or false) and then passes each element in the iterable through the function, "filtering" away those that are false. • syntax: filter(func, iterable) • func argument is required to return a boolean type. # Python 3 scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65] def is_A_student(score): return score > 75 over_75 = list(filter(is_A_student, scores)) print(over_75) IIIT Allahabad 14 Reduce function • It is defined in the functools module. Like the map and filter functions, the reduce() function receives two arguments, a function and an iterable. However, it doesn't return another iterable, instead it returns a single value. import functools def mult(x,y): print("x=",x," y=",y) return x*y fact=functools.reduce(mult, range(1, 4)) print ('Factorial of 3: ', fact) IIIT Allahabad 15 Python main function • Some programming languages have a special function called main() which is the execution point for a program file. Python interpreter, however, runs each line serially from the top of the file and has no explicit main() function. • A special variable called __name__ provides the functionality of the main function. As it is an in-built variable in python language. def func1(): print 'The value of __name__ is ' + __name__ if __name__ == '__main__': func1() IIIT Allahabad 16 Underscore • Leading double underscore tell python interpreter to rewrite name in order to avoid conflict in subclass. • Interpreter changes variable name with class extension and that feature known as the Mangling. IIIT Allahabad 17 Web References https://www.geeksforgeeks.org/frozenset-in-python/ https://www.w3schools.com/python/python_dictionaries.asp https://www.w3schools.com/python/python_functions.asp https://www.w3schools.com/python/python_lambda.asp https://www.geeksforgeeks.org/python-map-function/ https://stackoverflow.com/questions/18168022/what-is-the-advantageof-lambda-expressions • https://www.programiz.com/python-programming/methods/built-in/map • https://www.tutorialsteacher.com/python/python-reduce-function • • • • • • All the above are accessed between – 17 to 19 November 2020 IIIT Allahabad 18