Python For Computational Problem Solving - List - PDF
Document Details
Uploaded by QuaintLapSteelGuitar
PES University
Mohan Kumar AV, Sindhu Pai
Tags
Summary
This presentation explains Python lists, including their characteristics, creation, and common functions. It provides a linear data structure for storing multiple items under a single variable for easier handling and access.
Full Transcript
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering...
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 2 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List A List is a Collection. List is an ordered sequence of items. Values in the list are called elements / items. A collection allows us to put many things / values under a single name called “variable”. List is a linear data structure where elements have linear ordering. 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Creation of list List items are surrounded by square brackets and the elements in the list are separated by commas. politicians=['modi', 'rahul', 'mamta', 'kejriwal'] A list element can be any Python object - even another list. politicians=['modi', 'yediyurappa','devegowda',['parikar', 'swaraj', 'jately']] A list can be empty. lst=[ ] 4 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List List characteristics: Elements in the list can be heterogeneous in nature. Items in the lists can be of different data types. Ex: hetero_list=[1,"rahul",3.5,{1,2,3}] Homogeneous list Ex: sports=["tendulkar","bolt"," federer","messi"] List elements can be accessed by index. 5 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List List characteristics: Lists are mutable. List is iterable - is eager and not lazy. Assignment of one list to another causes both to refer to the same list. List can be sliced. This creates a new (sub)list. 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Elements are accessed using indexing operation or by subscripting. >>> numbers = [ 12,78,33,32.7,11.9,83,78] >>> print ( numbers ) 78 Note: List index always starts with 0 , also called as zero based indexing. 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Lists are mutable, as list can grow or shrink. o We can change an element of a list. Ex: >>> numbers=[55,88,45,12] >>> numbers=10 # index operation is used. >>> numbers [10, 88, 45, 12] 8 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List List is iterable - is eager and not lazy. Ex: (i) numbers=[55,88,45,12] Ex: (ii) number=[10,20,30,40,50] for i in numbers: i=0 print(i, end =' ') while(i> list1=[12,44,55,89,11,24] >>> list2=list1 >>> print(id(list1)) 2894590353408 >>> print(id(list2)) 2894590353408 Note: In Python, the id() function is a built-in function that returns the unique identifier of an object. 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Given lst1 = [12,44,55,89,11,24] >>> lst2 = lst1[::] # creates a copy of lst1. Not same as lst2 = lst1 >>> print(id(lst1)) 2894635511936 >>> print(id(lst2)) #These two are different values 2894635298304 11 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List List can be sliced. This creates a new (sub)list. Ex: >>> lst = [9, 41, 12, 3, 74, 15] >>> lst1=[10,20,[30,40,50]] >>> lst[1:3] >>> lst1 [41,12] 40 >>> lst[:4] [9, 41, 12, 3] >>> lst[3:] [3, 74, 15] >>> lst[:] [9, 41, 12, 3, 74, 15] 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Built in Functions There are a number of functions built into Python that take lists as parameters. >>> nums = [3, 41, 12, 9, 74, 15] >>> print(len(nums)) 6 >>> print(max(nums)) 74 >>> print(min(nums)) 3 >>> print(sum(nums)) 154 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Concatenation We can create a new list by adding two existing lists together. Ex: >>> list1 = [87,46,34,40,12] >>> list2 =[23,32,86,32,11] >>> list1 + list2 #concatenates two lists [87,46,34,40,12, 23,32,86,32,11] 14 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Repetition Operation allows multiplying the list n times. Ex: >>> list1 = [23,32,86,32,11] >>> list1 * 2 [23,32,86,32,11, 23,32,86,32,11] 15 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Membership Operator: in and not in It returns true if a particular item exists in the list otherwise false. Ex: >>> list1 = [10,2.2,[22,33,43],['python'] ] # heterogeneous list. >>> 'python' in list1 True 16 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List The not in operator returns True if the element is not present in the tuple, else it returns False. Ex: >>> list1 = [10,2.2,[22,33,43], ['python’]] # heterogeneous list. >>> 'ruby' not in list1 True 17 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Comparison We may at times need to compare data items in the two lists to perform certain operations by using == operator. Ex: >>> list1 = [10,2.2,(22,33,43] >>> list2=[2,3,4] >>> list1==list2 False >>> list1!=list2 True 18 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List The operations can be performed on List : append() Allows to add element at the end of list. Ex: >>> list1 = [10,20,30,40,50] >>> list1.append(22) >>> list1 [10,20,30,40,50,22] 19 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List insert(pos,val) Allows to add an element at particular position in the list. Ex: >>> list1 = [10,20,30,40,50] >>> list1.insert(3,55) >>> list1 [10,20,30,55,40,50] 20 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List extend() Adds the specified list elements (or any iterable) to the end of the current list. Ex: >>> list1 = [10,20,30,40,50] >>> list1.extend([11,22,33,44,55]) >>> list1 [10,20,30,40,50,11,22,33,44,55] 21 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List pop() & remove() Allows to remove element from a list by using pop() or remove() functions. One uses index value (pop),another uses value(remove) as reference to remove the element. Ex: >>> list1 = [10,20,30,40,50] >>>list1.pop(2) # using pop() >>> list1.remove(40) #using remove() >>> list1 >>> list1 [10,20,40,50] [10,20,30,50] 22 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List count(val) Returns number of occurrences of value. Ex: >>> list1 = [10,20,30,40,50] >>> list1.count(20) 1 23 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List copy() Return a shallow copy of a list, which returns a new list without modifying the original lists. Ex: >>> lis = [‘23’,’13’,’45’] >>> new_list = lis.copy() >>> print('Copied List:', new_list) 24 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Index (val) Return first index of a value. Raises Value error if the value is not present. Ex: >>> list1 = [45,20,30,15,67] >>> list1.index(20) 1 25 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Sorting Allows to arrange the elements of a list. Ex: >>> list1 = [10, 1, -2, 2, 9] >>> list1.sort() >>> list1 [-2, 1, 2, 9, 10] 26 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List dir() Returns all properties and methods of the specified object, without the values. Ex: number = # returns valid attributes of the number list print(dir(number)) 27 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Use of for and while Loops for list 1. for loop 2. while loop 28 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List 1. List using for Loop The for loop in Python is used to iterate over a sequence or other iterable objects. Iterating over a sequence is called traversal. Loop continues until we reach the last item in the sequence The body of for loop is separated from the rest of the code using indentation. 29 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Accessing Element Output a = [34,100,23,45,56,145] 34 100 23 45 56 145 for i in a: print(i) Accessing Element Output a = [34,100,23,45,56,145] 012345 for i in range(0,len(a),1): print(i) Accessing Element Output a = [34,100,23,45,56,145] 34 100 23 45 56 145 for i in range(0,len(a),1): print(a[i]) 30 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List 2. List using while loop: The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. 31 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING List Ex: Python code to find Sum of elements in a list. a=[1,2,3,4,5] i=0 s=0 while i>> t1= () >>> print(type(t1)) # Tuple with two elements. >>> t3= (1,2) 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Tuple with a single element Ex: >>> t1= (1) >>> print(type(t1)) # >> t1=(1,2,3,4) >>> t2=t1[::] >>> print(id(t1)) 2940764604192 >>> print(id(t2)) 2940764604192 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Slicing a tuple 11 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Slicing a tuple 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Slicing a tuple 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Slicing a tuple 14 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Built in Functions Method Description Example len(tup) Gives the total length of the tuple. >>> tuple1 = (10,20,30,40,50) >>> len(tuple1) 5 sorted() Takes elements in the tuple and returns a >>> tuple1 = (‘rama’,’shama’,’bhama’,’balarama’) new sorted list. It should be noted that, >>> sorted(tuple1) sorted () does not make any change to [‘balarama’,bhama’,’rama’,’shama’] the original tuple 15 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Built in Functions Method Description Example min() Returns the element from tuple with max >>> tuple1=(22,33,11,55,44,120) value >>> min(tuple1) 11 max() Returns the element from tuple with min value >>> tuple1=(22,33,11,55,44,120) >>> max(tuple1) 120 sum() Returns the sum of elements of the tuple. >>> tuple1=(22,33,11,55,44,120) >>> sum(tuple1) 285 16 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Built in Functions Method Description Example tuple(seq) Convert sequence into tuple >>> tuple1 = tuple() >>> tuple1 () >>> tuple1 = tuple(‘a e I o u')#string >>> tuple1 ('a', 'e', 'i', 'o', 'u') >>> tuple2 = tuple([1,2,3]) #list >>> tuple2 (1, 2, 3) >>> tuple3 = tuple(range(5)) >>> tuple3 (0, 1, 2, 3, 4) 17 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Concatenation: allows us to join two tuples by using operator ‘+’. Ex: >>> tuple1 = (11,33,55,77,99) >>> tuple2 = (22,44,66,88,100) >>> tuple1 + tuple2 #Concatenates two tuples (11, 33, 55, 77, 99, 22, 44, 66, 88 100) 18 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Repetition: The repetition operator enables the tuple elements to be repeated multiple times. The repetition operator requires the first operand to be a tuple and the second operand to be an integer only. Ex: >>> t1=(1,2,3,4) >>> t1*2 (1, 2, 3, 4, 1, 2, 3, 4) >>> t1 * t1 Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'tuple 19 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Membership Operator: in and not in It returns true if a particular item exists in the tuple otherwise false Ex: >>> tuple1 = (1,2.2,[22,33,43],”python”) >>> “python” in tuple1 True 20 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple The not in operator returns True if the element is not present in the tuple, else it returns False. Ex: >>> tuple1 = (1,2.2, [22,33,43],”python”) >>> “PYTHON “ not in tuple1 True 21 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Tuple Functions : Method Description Example count() Returns the count of the items. >>> tuple1 = (10,20,30,10,40,10,50) >>> tuple1.count(10) 3 >>> tuple1.count(90) 0 index() Returns the index of the item >>> tuple1 = (10,20,30,40,50) specified >>> tuple1.index(30) 2 >>> tuple1.index(90) ValueError: tuple.index(x): x not in tuple. 22 THANK YOU Mohan Kumar AV, Sindhu Pai Team Python - 2022 Department of Computer Science and Engineering 23 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 2 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary A “bunch” of values, each with its own label. Bag passport money 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Dictionary Dictionary is a data structure that organizes data into key and value pairs. Dictionary Creation >>> phonebook={} #Creation of empty Dictionary >>> phonebook={"Johan":938477565} #Dictionary with one key-value pair >>> phonebook={"Johan":938477565,"Jill":938547565} #Dictionary with two key-value pair 4 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary >>> eng2french={ 1:’un’, 2:’deux’, 3:’trios’, 4:’quatre’, 5:’cinq } To access values in the dictionary, we use the keys. >>> print(end2french) #will give you ‘deux’ #unordered >>> d={'w':11,'a':33,'e':44} >>> f= {'e':44,'w':11,'a':33} >>> print(d==f) True 5 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Characteristics: Dictionary is a data structure that organizes data into key and value pairs. d={1:"one",2:"two",3:"three",4:"four"} In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key “maps to” a value. Dictionary is mutable, associative data structure of variable length of key-value pairs. 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Each key is of any immutable type associated with a single value. >>> d={1:"one",2:"two",3:"three",4:"four"} >>> d1={[1,2]:"hello"} Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' The values can be of any type. >>> d={1:"one", 2:[23,33] , 3:"three", 4:"four"} 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary If you assign a value to a key, then later in the same dictionary have the same key assigned to a new value, the previous value will be overwritten. >>> d={1:"one",2:"two",3:"three"} >>> d={1:"one",2:"two",3:"three",1:"five"} >>> d {1: 'five', 2: 'two', 3: 'three'} 8 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary The items (key-value pair) in dictionary is unordered type, which means that the order isn’t decided by the programmer but rather the interpreter. The ordering is based on a concept called “Hashing”. Note: hash() function in python is used to return a hashed integer value of the object we pass as a parameter into it. 9 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Common operation on Dictionary len() min() max() ❑ Note: Does not support ‘+’ and ‘*’ operations. 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. get(): returns the value for a given key, if present. >>> print(phonebook.get('Jill’)) 938547565 items(...) D.items() -> a set-like object providing a view on D’s items. >>> phonebook.items() dict_items([('Johan', 938477565), ('Jill', 938547565)]) 11 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. keys(...) D.keys() -> a set-like object providing a view on D’s keys. >>> phonebook.keys() dict_keys(['Johan', 'Jill']) 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. pop(...) D.pop(key) -> v, remove specified key and return the corresponding value. If key is not found, otherwise KeyError is raised. >>> phonebook.pop(‘Jill’) 938547565 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. popitem(...) D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. >>> person = {'name': 'Phill', 'age': 22, 'salary': 3500.0} >>> result = person.popitem() >>> print('Return Value = ', result) Return Value = ('salary', 3500.0) >>> print('person = ', person) person = {'name': 'Phill', 'age': 22} 14 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. setdefault(...) D.setdefault(key,value) -> if the key is in the dictionary, returns its value. If the key is not present, insert key with a value of dictionary and return dictionary. >>> person = {'name': 'Phill', 'age': 22} >>> age = person.setdefault('age’) >>> print('person = ',person) >>> print('Age = ',age) 15 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. update(...) D.update() -> It will update to the dictionary. >>> marks = {'Physics':67, 'Maths':87} >>> internal_marks = {'Practical':48} >>> marks.update(internal_marks) >>> print(marks) {'Physics': 67, 'Maths': 87, 'Practical': 48} 16 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Functions to play with dictionary. values(...) D.values() -> returns a view object that displays a list of all the values in the dictionary. >>> marks = {'Physics':67, 'Maths':87} >>> print(marks.values()) dict_values([67, 87]) 17 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Use of for and while Loops for Dictionary 1. for loop Ex: (1) dict = {'a': 'pencil', 'b': ‘eraser', 'c': 'sharpner’} for key, value in dict.items(): print(key, value) Ex: (2) dict = {'a': 'juice', 'b': 'grill', 'c': 'corn’} for key in dict: print(key, dict[key]) 18 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dictionary Use of for and while Loops for Dictionary 2. while loop Ex: books={"learning python": "Mark Lutz", "think python": "Allen B. Downey", "Fluent Python": "Luciano Ramalho"} key=list(books) #converts keys into a list i=0 while i>> dir(set) o ['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update'] 8 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Methods in detail len() Returns the number of elements in a >>> set1={22,33,11,55,44,120} container set. >>> len(set1) 6 max() Returns the element from Set with >>> set1={42,73,25,75,64,145} maximum value >>> max(set1) 25 min() Returns the element from Set with >>> set1={25,43,21,66,45,120} maximum value >>> min(set1) 21 sum() Returns the sum of elements of the Set. >>> set1={4,10,2,7,25} >>> sum(set1) 7 9 48 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common methods of Set sorted() Returns the sorted sequence or sorted >>> set1={22,33,11,55,44,120} collection in the form of list. >>> sorted(set1) [11, 22, 33, 44, 55, 120] >>> s4={"pes",0,1} >>> sorted(s4) Traceback (most recent call last): File "", line 1, in TypeError: '>> s1={1,2,3,4,5,6} >>> print(1 in s1) True >>> print('a' in s1) False Membership(not in) operator- Returns True if the element is not present in the set, else return False. >>> s1={1,2.34,(34,22),"python"} >>> "PYTHON" not in s1 True >>> (34,22) not in s1 False 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set union()- Return the union of sets as a new set. (i.e. all elements that are in either set.). >>> s1={1,2,3,4,5,6} >>> s2={6,5,7,8,9,10} >>> print(s1.union(s2)) or >>> print(s1|s2) {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} intersection()- Return the intersection of sets as a new set. (i.e. all elements that are in both sets.). >>> s1={1,2,3,4,5,6} >>> s2={6,5,7,8,9,10} >>> print(s1.intersection(s2)) or >>> print(s1&s2) {5, 6} {5, 6} 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set difference()- Return the difference of two or more sets as a new set. >>> s1={1,2,3,4,5,6} >>> s2={6,5,7,8,9,10} >>> print(s1.difference(s2)) or >>> print(s1-s2) {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} add()- adds an element in a container set. >>> s1={1,2,3,4,5,6} >>>s1={1,2,3,4,5,6} >>> s1.add(7) >>> s1.add(“pes”) >>> s1 >>> s1 {1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, “pes”} 14 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set symmetric_difference()- Return a set with the symmetric differences of two sets. >> s1={1,2,3,4,5,6} >>> s2={6,5,7,8,9,10} >>> print(s1.symmetric_difference(s2)) or >>> print(s1^s2) {1, 2, 3, 4, 7, 8, 9, 10} {1, 2, 3, 4, 7, 8, 9, 10} remove()- Removes the specified item in a set. If the item to remove does not exist, remove() will raise an error. >>> s1={1,2,3,4,5,6} >>> s1.remove(5) or >>> s1.remove(7) >>> print(s1) Displays an Error. {1, 2, 3, 4, 6} 15 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set discard()- Removes the specified item in a set. If the item to remove does not exist, discard() will NOT raise an error. >>> s1={1,2,3,4,5,6} >>> s1.remove(6) or >>> s1.discard(7) >>> print(s1) Doesn’t Displays an Error. {1, 2, 3, 4, 5} pop()- Removes an item in a set. Sets are unordered, so when using the pop() method, doesn’t know which item that gets removed. >>> s1={1,2,3,4,5,6} >>> s1.pop() 1 >>> print(s1) {2, 3, 4, 5, 6} 16 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set update()- updates the current set, by adding items from another set (or any other iterable). If the element is present in both the sets, only one appearance of element present in updated set >>> s1={120,12,23} >>> s1.update([22,15,67,"pes"]) >>> s1 {67, 12, 15, 22, 23, 120, 'pes’} intersection_update()- Removes the items that is not present in both sets. >>> set1={"apple", "banana", "cherry"} >>> set2={"google", "microsoft", "apple"} >>> set1.intersection_update(set2) >>> set1 {'apple'} 17 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set difference_update()- Removes the items that exists in both sets. >>> set1={"apple", "banana", "cherry"} >>> set2={"google", "microsoft", "apple"} >>> set1.difference_update(set2) >>> set1 {'cherry', 'banana’} Symmetric_difference_update()- Updates the original set by removing items that are present in both sets, and inserting the other items. >>> set1={"apple", "banana", "cherry"} >>> set2={"google", "microsoft", "apple"} >>> set1.symmetric_intersection_update(set2) >>> set1 {'microsoft', 'apple', 'cherry', 'google', 'banana'} 18 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set issubset()- Returns True if all items in set ‘x’ are present in set ‘y’. >>> x = {"a", "b", "c"} >>> y = {"f", "e", "d", "c", "b", "a"} >>> x.issubset(y) True >>> y.issubset(x) False issuperset()- Returns True if all items in set ‘y’ are present in set ‘x’. >>> x = {"f", "e", "d", "c", "b", "a"} >>> y = {"a", "b", "c"} >>> x.issuperset(y) True >>> y.issuperset(x) 19 False PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of set isdisjoint()- Returns True if no items in set s1 is present in set s2. >>> s1={1,2,5} >>> s2={11,22,55} >>> s1.isdisjoint(s2) True clear()- Removes all the elements in a set. >>> x = {"f", "e", "d", "c", "b", "a"} >>> x.clear() >>> x set() 20 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Example code 1: Display the elements of a set one by one in separated by a space between each of them. a = { 10, 30, 10, 40, 20, 50, 30 } for i in a : print(i, end = “ “ ) output:40 10 50 20 30 21 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Example code 2: Create a set of numbers from 2 to n. Steps: create an empty set and add the elements to it. s = set() n=int(input(“enter the value of n”)) #5 for i in range(2,n+1): s.add(i) print(s) Output: {14} 22 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Example code 3: Program to check whether a set is empty or not. Version 1: Version 2: s1=set() s1=set() if len(s1)==0: if(s1): print("set is empty") print("set is empty") else: else: print("not empty") print(“not empty”) Output: set is empty 23 Note: Empty data structure is False THANK YOU Dr. Chetana Srinivas and Prof.Sindhu R Pai Team Python - 2022 Department of CSE(AI & ML) and CSE 24 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dr. Chetana Srinivas and Prof. Sindu R Pai Department of CSE(AI&ML) and CSE PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Strings Dr. Chetana Srinivas and Prof. Sindu R Pai Department of CSE(AI&ML) and CSE PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Strings Processing in python A string is a collection of characters or a sequence of characters. o Creating strings is as straight forward as assigning a value to a variable. Ex: var1= ““ # empty string. var="python" var=“”” this is python””” 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Characteristics o A string has zero or more characters. >>> str1=" “ >>> str1="p" >>> str2="python“ >>> str3 = ‘’’python pro ‘’’ o Each character of a string can be accessed by using the index that starts from 0. Negative indices are allowed. Example:- >>> str2 'p’ >>> str2[-1] ‘n’ o The index value can be an expression that is computed. >>> str2[2+3] 4 'n’ PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Characteristics o Immutable – cannot modify the individual characters in a string. One cannot add, delete, or replace characters of a string. Example:- str2="python" >>> str2='T' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment o Iterable - for i in str2: 5 print(i) PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Methods of String All string operations that “modify” a string return a new string that is a modified version of the original string. 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common methods of String o The len(str) returns the number of characters in a string. >>> str1="python" >>> len(str1) 6 o s.index(chr) returns the index of the first occurrence of chr in s. >>> str1="python programming“ >>> str1.index('prog’) >>> str1.index(‘p’) 7 0 o count() - Returns the number of times a specified value / character occurs in a string. >>> str1="Welcome to Python Class“ >>> str1.count('s’) 2 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common methods of String o len(str) returns the number of characters in a string. >>> str1="python" >>> len(str1) 6 min and max functions as applied to strings return the smallest and largest character respectively based on the underlying Unicode encoding. For example, all lowercase letters are larger have a larger Unicode value than all uppercase letters. o Example:- >>> str1="Python“ >>> min(str1) 'P’ >>> max(str1) 'y' 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common operators applied on string Concatenation (+) operator can be used to add multiple strings together. >>> str1="Python“ >>> str2="Language" >>> str1+str2 'PythonLanguage’ Repetition (*) operator returns is used to repeat the string to a certain length. >>> str1="Python Programming" >>> str1*2 'Python ProgrammingPython Programming' 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common operators applied on string Scope resolution (::) operator assigns the characters of string str1 into an another string str2. >>> str1="Python Programming" >>> str2=str1[::] // same as str2=str1 >>> str2 'Python Programming’ >>> id(str1) 1534440206336 >>> id(str2) 1534440206336 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common operators applied on string Membership (in) operator returns True if a sequence with the specified value is present in the string otherwise False. >>> str2="Language" >>> "Lang" in "Language" True >>> "Png" in "Language" False Membership (not in) operator returns True if a sequence with the specified value is is not present in the string otherwise False.. >>> str1="Language" >>> "LAN" not in str1 True >>> "Lang" not in str1 14 False PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Common operators applied on string The slice operator s[start:end] returns the substring starting with index start, up to but not including index end. o Example:- >>> s = 'Monty Python’ >>> s[0:4] Mont >>> s[6:7] P >>> s[6:20] Python 15 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific methods of String o The dir() function returns all properties and methods of the specified object. >>>dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific methods of String o index(chr) returns the index of the first occurrence of chr in s. >>> str1="python programming“ >>> str1.index('prog’) >>> str1.index(‘p’) 0 o count() - Returns the number of times a specified value / character occurs in a string. >>> str1="Welcome to Python Class“ >>> str1.count('s’) 2 11 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string startswith(prefix,start,end) returns True if string starts with the given prefix otherwise returns False. prefix – A string that needs to be checked. start – starting position where prefix is needed to be checked within the string. end- Ending position where prefix is needed to be checked within the string. Ex:- >>> str1.startswith("W",0) True >>> str1.startswith("W",1) False >>> str1.startswith("App",5,8) True >>> str1.startswith("App",6,9) False 16 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string endswith(search_string,start,end) returns True if original string ends with the search_string otherwise returns False. search_string – A string to be searched. start – starting position of the string from where the search_string is to be searched. end- Ending position of the string to be considered for searching. Ex:- >>> str1="Welcome to Python Class“ >>> str1.endswith("Class",18,22) >>> str1.endswith("Class") False >>> str1.endswith("Class") >>> str1.endswith("Class",18,23) True True >>> str1.endswith("Class",18) True >>> str1.endswith("Class",19) False 17 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o There are a number of methods specific to strings in addition to the general sequence operations. o String processing involves search. o The find(substring,start,end) method returns the index location of the first occurrence of a specified substring. If not found, returms -1. Substring- The substring to search for. start – where to start the search. Default is 0. end – where to end the search. Default is 0. >>> s3="chocolate“ >>>s3.find(“c”,4,9) >>> s3.find("c") -1 0 >>> s3.find("z") >>>s3.find(“c”,3,9) -1 3 18 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The rfind(substring,start,end) method returns the index location of the last occurrence of a specified substring. If not found, returns -1. Substring- The substring to search for. start – where to start the search. Default is 0. end – where to end the search. Default is 0. >>> s3="chocolate“ >>> s3.rfind("c") 3 >>> s3.rfind("c",-6,-1) 3 >>> s3.rfind("c",4,9) >>> s3.rfind("c",1,2) -1 -1 >>>str1.rfind("c",0) 3 19 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The strip(characters) method removes characters from both left and right based on the argument. o The lstrip(characters) method removes characters from left based on the argument. o The rstrip(characters) method removes characters from right based on the argument. >>> str1=" Welcome to Python class " >>> str1.strip() 'Welcome to Python class’ >>> str1.lstrip() 'Welcome to Python class ‘ >>> str1.rstrip() ' Welcome to Python class' 20 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o >>> str1="madam" >>> str1.strip('m’) 'ada' o >>> str1.lstrip('m’) 'adam' o >>> str1.rstrip('m’) 'mada' o >>> str1.rstrip('ma’) 'mad' o >>> str1.rstrip('maz’) 'mad' o >>> str1.rstrip('mjaz’) 'mad' 21 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The replace method produces a new string with every occurrence of a given substring within the original string replaced with another. o >>> s1.replace("a","b") 'whbtsbpp' o >>> s1.replace("a","b",1) 'whbtsapp' o >>> s1.replace("a","b",2) 'whbtsbpp' o >>> s1.replace("a","b",0) 'whatsapp' o >>> s1.replace("at","b",1) 'whbsapp' o >>> s1.replace("at","b",2) 'whbsapp' 22 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The title() method returns a string where the first character in every word is upper case. o >>> str1="people education society" >>> str1.title() 'People Education Society’ o The capitalize() method returns a string where the first character is upper case, and the rest is lower case. >>> s1="Python" >>> s1.capitalize() 'Python' 23 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator. Example:- >>> s2="abc" >>> s1="abc" >>> s2="xyz" >>> s1.join(s2) 'xabcyabcz’ 24 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string The split() method splits a string into a list. Example:- o >>> str1="When someone is lost, dare to help them find the way." >>> str1.split() ['When', 'someone', 'is', 'lost,', 'dare', 'to', 'help', 'them', 'find', 'the', 'way.’] o >>> str1.split("i") ['When someone ', 's lost, dare to help them f', 'nd the way.’] o >>> str1.split("i",1) ['When someone ', 's lost, dare to help them find the way.’] o >>> str1.split("i",1,2) Traceback (most recent call last): File "", line 1, in TypeError: split() takes at most 2 arguments (3 given) 25 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. >>> s1=“ “ >>> s1="543a" >>> s1.isspace() >>> s1.isspace() True False o The ljust() method will left align the string, using a specified character and returns a new string >>> s3="chocolate" >>> s3.ljust(20) 'chocolate ‘ >>> s3.ljust(20,"#") 'chocolate###########' 26 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The rjust() method will right align the string, using a specified character and returns a new string >>> s3="chocolate" >>> s3.rjust(20) ' chocolate’ >>> s3.rjust(20,"$") '$$$$$$$$$$$chocolate' o The center() method will center align the string, using a specified character and returns a new string. >>> s3="chocolate" >>> s3.center(20) ' chocolate ‘ >>> s3.center(20,'*’) '*****chocolate******' 27 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string o The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. >>> s3.zfill(10) '0chocolate’ >>> s3.zfill(20) '00000000000chocolate’ oThe isnumeric() method returns True if all the characters are numeric (0-9), else False. >>> s1="543“ >>> s1="543a" >>> s1.isnumeric() >>> s1.isnumeric() True False 28 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Specific functions of string 32 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Try these functions!! o encode() o decode() o maketrans() o translate() o partition() 29 THANK YOU Dr. Chetana Srinivas, Prof.Sindhu R Pai Team Python - 2022 Department of CSE(AI & ML) and CSE 33 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Mohan Kumar AV, Sindhu Pai Department of Computer Science and Engineering 2 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Different ways of giving input to the program: Using command line arguments. Through the keyboard , using input() function. In both the cases the amount of input given would be minimal and also prone to errors. This is where the files comes in to picture. 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Advantages of Files: Data is persistent even after the termination of the program. The data set can be much larger. The data can be input much more quickly and with less chance of error. Python, a file operation takes place in the following order: 1.Open a file 2.Read or write (perform operation) 3.Close the file 4 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Functions: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened. mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other modes are ‘a’, ‘a+’, etc. Lets not worry about other parameters. 5 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Opening a file: A file opening may not always succeed. If it fails, it throws an exception. A few possible exceptions: - opening a non-existent file for reading. - opening a file for writing where directory does not allow us to create files. If the required file exists then, a file object is returned. OS provides the required resources when the file gets created. 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files read() After we open a file, we use the read() method to read its contents. File can be read in different ways: read() - returns the contents of the file. readline() - reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end. readlines() - returns a list containing each line in the file as a list item. 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Writing to a file: In order to write it to a file we may use: - write() - print() close() - We return the resources utilized back to OS by calling a function called close on the open file. 8 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Files Example: file1 = open("test.txt", "r") # open a file read_content = file1.read() # read the file print(read_content) file1.close() # close the file 9 THANK YOU Mohan Kumar AV, Sindhu Pai Team Python - 2022 Department of Computer Science and Engineering 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dr. Chetana Srinivas and Prof. Sindhu R Pai, Department of CSE (AI&ML) and CSE 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Functions – Definition and Call Dr. Chetana Srinivas and Prof. Sindhu R Pai, Department of CSE(AI & ML) and CSE 2 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Functions What are functions? A function is a self contained block of code that performs a specific task Functions ideally take input, performs a set of operations and returns an output to the program that invoked it. 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Advantages of functions Reducing duplication of code and the complexity of the program through modularity. Improves the readability, enhances the clarity of the program. Promotes reuse of code. Debugging and maintenance becomes easier 4 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Functions - Types Types of Functions in Python Programming: Built-in functions or Pre-defined – Standard library functions. User defined functions - Defined by user for specific application in-order to reduce complexity of large programs. 5 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Built – in Functions Built-in functions or Pre-defined – These functions are built into the Python interpreter and can be used/called without the need for additional code. Examples: print() – Outputs a message to the console or standard output device. Input() - Takes user input from the console or standard input device. len() - Returns the length of an object, such as a string, list, or tuple. type() - Returns the data type of an object. sorted() - Sorts a list or sequence in ascending order. abs() - Returns the absolute value of a number. 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING User – Defined Functions User defined functions – These are the functions defined by the user to aid them in achieving the specific goal. The python interpreter also supports the user-defined functions created as per the user requirement. The main purpose of these functions is to help in organizing the programs into logical segments that work together to solve a specific part of our problem. Definition: A function is a block of code which only runs when it is called. Can pass data, known as parameters (optional), into a function. A function can return data as a result. 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING User – Defined Functions A function has two parts – leader and suite The leader starts with the keyword def then the function name function name is an identifier that starts with alphabets [a- z or A-Z] or _ and then followed by any number of letter of English or _ or digit. followed by a pair of round parentheses then a colon. suite follows – suite can have any valid statement of Python including another function definition. All the statements within the function must be indented. Finally, use the return (optional) keyword to return the output of the function. Function must be defined preceding their usage in the program code. Syntax: def function_name(parameters): #suite 8 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Processing of Functions When the function is defined, header or the leader is processed, the user is provided a name or a handle which is the same as the function name. A function entity with the function name in the definition along with the suite is stored. Each entity in Python has a reference count. At this point of translation, only leader is processed and the suite is not processed. 9 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function: Call Name of the function followed by parentheses causes a function call This results in transfer of control to the leader of the function and then the suite is executed After that, the control comes back to the point after the function call in the user’s code. A pair of round parenthesis () is called a function call operator. 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function: Call 11 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Activation record When the function call is made, an activation record is created which will have Parameters:- nothing but the arguments. local variables:- variables created with in the suite of the function. return address:- location to which the control of the program should be transferred once the function terminates. temporary variables:- unnamed variables required by the translator return value:- value to be passed back to the caller. The activation record is created for every call of the function. At the end of the function, if no other callable can refer to the activation record, it will be removed. 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Example 1:- def area_rect(x,y) : a=x*y return a a=area_rect(5,6) print("area =",a) Output: area = 30 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Overloading: Function overloading is the ability to have multiple functions with the same name but with different signatures/implementations. Python does not support function overloading. When we define multiple functions with the same name, the new function always overrides the prior function. Example:- def add(a,b): p=a+b print(p) def add(a,b,c): p=a+b+c print(p) # add(2,3) this will not run, it gives error 14 add(1,2,3) PYTHON FOR COMPUTATIONAL PROBLEM SOLVING User - Defined Functions : Example Example 1: #program to display a greeting message def display(): print("hello") print("python") print("program") display() Output: hello python program 15 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function: Call Example 2: def display() : print("hello") ;print("python") display() display1=display #assigning the function entity another name #at this point the reference count of the function entity is up by 2 del display #ref count reduces by 1 display1() #still works Output: hello python 16 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Multiple Return statements Functions can have multiple return statements, but any statement after the 1st return statement becomes part of the unreachable code. The python interpreter is forgiving in terms of letting its programmers make these kind of errors. Example:- def example(): print(“an example function”) return #function ends here print(“after return”) #unreachable return ‘Hello’ #unreachable 17 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Returning multiple values Example 3-: When a collection of values is returned from called function, the def add(): interpreter puts it together into a tuple and returns it to the a = 12 calling program. b = 13 s = a+b return s,a,b # becomes an unnamed tuple sum = add() print(type(sum)) # (25, 12, 13) 18 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Value returning and Non-Value returning Functions Non - Value Returning Functions – Functions are not required to return a value back to the caller. By default, it returns None. Example 2:- def multiply_numbers(a,b): product=a*b print(product) Value Returning Functions – Functions that are required to return a value back to the caller. Example 2:- def multiply_numbers(a,b): n1=10 product=a*b n2=20 return product print(“Product=“,multiply_numbers(n1,n2)) 19 THANK YOU Dr. Chetana Srinivas and Prof.Sindhu R Pai Team Python - 2022 Department of CSE(AI & ML) and CSE Email-id :- [email protected] [email protected] 20 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dr. Chetana Srinivas and Prof. Sindhu R Pai, Department of CSE (AI&ML) and CSE 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Functions – Position and Keyword Arguments Dr. Chetana Srinivas and Prof. Sindhu R Pai, Department of CSE(AI & ML) and CSE 2 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Keyword and Positional Arguments When we call a function in Python, we can pass in two different types of arguments 1. Keyword arguments (named arguments) – Are arguments passed to a function or method which is preceded by a keyword (parameter_name)and an equals sign. Argument name must be same as the parameter name in the function definition. 2. Positional arguments – Are arguments that need to be included in the proper position or order. Note: If there are both keyword and positional arguments, Keyword arguments must follow positional arguments 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Keyword and Positional Arguments Differences Keyword arguments Positional arguments Parameter names are used to pass the Arguments are passed in the order of argument during the call parameters. The order defined in the order function declaration. Order of parameter Names can be Order of values cannot be changed to changed to avoid pass the argument(or values). the unexpected output. Syntax : – Syntax : – FunctionName(paramName=value,…) FunctionName(value1,value2,value3…) 4 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Keyword and Positional Arguments Keyword arguments (named arguments) Example 1: - def nameAge(name, age): print(“Hi, I am”,name) print(“My age is ”,age) nameAge(name=“Rajeev”, age=26) nameAge(age=26, name=“Rajeev”) 5 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Keyword and Positional Arguments in Python Positional arguments Example 2: - def minus(a,b): return a-b X=20;Y=10 print(“Difference between two numbers is=”,minus(X,Y)) 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Keyword and Positional Arguments in Python Combination of both Positional and keyword arguments Rule: All keyword arguments must follow positional arguments Example 3:- def f1(x, y, z, a, b): print(a, b, x, y, z) f1(3,5,z = {4,5},b = [12,7,8,4], a = 99.7) # 99.7 [12, 7, 8, 4] 3 5 {4, 5} #f1(3,5,x = {4,5},b = [12,7,8,4], a = 99.7) #TypeError: f1() got multiple values for argument 'x' #f1(x = 9, y = 99,2,3,b = 22) #SyntaxError: positional argument follows keyword argument 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Default Parameters Default parameters are always a part of the symbol table which is added during the leader processing phase. If the user did not send the argument, then this default parameter is used in the processing. Example 4:- Example 5:- def f1(a,b=5): x=12 print(a,b) def f1(a,b=x): f1(4) print(a,b) f1(4,13) f1(4) f1(4,13) 8 THANK YOU Dr. Chetana Srinivas and Prof.Sindhu R Pai Team Python - 2022 Department of CSE(AI & ML) and CSE Email-id :- [email protected] [email protected] 9 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Dr. Chetana Srinivas and Prof. Sindhu R Pai, Department of CSE (AI&ML) and CSE 1 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Functions – Variable number of Arguments Dr. Chetana Srinivas and Prof. Sindhu R Pai, Department of CSE(AI & ML) and CSE 2 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Arguments and Parameters In the function definition, variables are specified which receive the arguments when the function is called or invoked. These are called parameters. The parameters are always variables. When the function call is made, the control is transferred to the function definition. The arguments are evaluated and copied to the corresponding parameters. This is called parameter passing by value or call by value. The value of arguments are passed by value to the parameters. 3 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Arguments and Parameters When a function performs a specified task, it may require some values to operate on. These values have to be provided when calling a function as input. These values have to be put within the pair of round parentheses in the function call. They are called as arguments. 4 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function: Global and Local variables There are two types of variables Global Variables: Variables created outside all functions. Scope of Global variable is within the file and outside that file too. Local variables: Variables created inside the function and accessible only to that function. Scope of the local variable is within the function. Example 1: x=10 print("global first outside",x) def f1(): x=11 #local variable x. #Life and scope is only within this function print("inside",x) f1() print("global second outside",x) 5 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function: Global and Local variables Example 2: Global variable is read-only inside a function. We cannot modify the value of that variable inside the function directly. x=10 print(x) def f1(): x=x+1 #UnboundLocalError. print("inside",x) f1() print("outside",x) 6 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function: Global and Local variables Example 3: Usage of global keyword x=10 print("global first outside",x) def f1(): global x x=x+1 print("inside",x) f1() print("global second outside",x) #If you interchange the first two statements inside the function, it results in Error. 7 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Arguments and Parameters Example 4:- Calculate the sum of two numbers given and return the sum. def add_numbers(x,y): sum = x + y return sum output = add_Numbers(10,5) print(“The sum of two numbers is = ”,output) Output: The sum of two numbers is = 15 8 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Arguments and Parameters Example 5:- Calculate the area of triangle given the dimensions. def area_tri(b,h) : a=0.5*b*h return a Area=area_tri(5,6) print("area=",Area) The function definition has two parameters, which indicate that it requires two arguments to be passed when the function is called/invoked. The arguments are constants in this example, 5 and 6. These values are copied to the parameters b and h respectively. 9 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Arguments and Parameters When a function is called, it is imperative that the number of arguments passed MUST ALWAYS MATCH the number of parameters in the function definition Example 6:- def product(x,y,z) : a=x*y*z return a r=product(5,6,2) #r=product(5) #error : too few arguments #r=product(5,6,2,7) #error : too many arguments print(“product =",r) Output: product = 60 10 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Categories of Functions 1. No arguments : No return value 1. No arguments : with return value def add(): def add() a = 10 a=10 b = 20 b=20 print(a+b) return a+b add() sum = add() print(sum) Output: 30 Output: 30 11 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Function Call: Categories of Functions 3. With arguments : No return value 4. With arguments : With return value def add(a,b): def add(a,b): print(a+b) return a+b add(10,20) sum = add(10,20) print(sum) Output: 30 12 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Variable number of positional arguments: *arg [Any variable can be used with *] * handles the variable number of positional arguments in the function. arg is of type tuple inside the function. Example 7: def f1(*arg): print(arg, type(arg)) #arg is of type tuple for i in arg: print(i) f1(2,1,6,4,9,7) #All three function calls are valid f1() f1(2,4) 13 PYTHON FOR COMPUTATIONAL PROBLEM SOLVING Variable number of keyword arguments: **kwarg [Any variable can be used with **] ** handles the variable number of keyword arguments in the function. kwarg is of type dictionary inside the function. Example 8: def f1(**kwarg): print(kwarg, type(kwarg)) #kwarg is of type dict for i in kwarg: print(i,end="") print() for i in kwarg.keys(): print(i,end="") print() for i in kwarg.values(): print(i,end="") 14 f1(a=2,b=1,c=6) THANK YOU Dr. Chetana Srinivas and Prof.Sindhu R Pai Team Python - 2022 Department of CSE(AI & ML) and CSE Email-id :- [email protected] [email protected] 15