0% found this document useful (0 votes)
2 views17 pages

Review Python 2

This document provides a comprehensive overview of Python data structures, specifically focusing on lists and tuples. It covers characteristics, operations, and built-in functions associated with these data types, emphasizing their mutability and immutability, respectively. Additionally, it includes examples and explanations of how to manipulate these structures effectively in Python programming.

Uploaded by

jenniferbeomgyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Review Python 2

This document provides a comprehensive overview of Python data structures, specifically focusing on lists and tuples. It covers characteristics, operations, and built-in functions associated with these data types, emphasizing their mutability and immutability, respectively. Additionally, it includes examples and explanations of how to manipulate these structures effectively in Python programming.

Uploaded by

jenniferbeomgyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Review Python II UG COTES S will be able to: 24 © revise the concept of lists, tuples, dictionaries, and modules. 2.2 in Python, 23 perform different operations an lists, tuples, dictionaries and 4 modules. In the previous chapter, you have revised the fundamentals of Python. This chapter covers some more features of Python, such as lists, tuples, dictionaries, and modules. Let us revise these concepts one-by-one separately. 2.1 Lists ‘The list datatype is a collection of data elements. These data elements can be ofthe same data type or they can be of different data types also, The items in the list are separated by the comma (,) and encloced within the square brackets [] 2.1.1 Characteristics of Lists An important feature of the list is that it is mutable. That means it can be modified even after its creation Lists in Python have some more useful characteristics that are discu. issed below: Lists are ordered, ‘They can contain any arbitrary objects. List elements can be accessed by index. Lists can be nested, ++ et + Lists are mutable and dynamic. 2.1.2 List Operations Lists are one ofthe most powerful features of Python. You can perform a number ; of ope: following table summarises some of these operations: Perations in a list. The Creating list Lists in Python can be created by just num = [6.5 Son Aa 87, placing the sequence of elements inside month = {-Ian", sare 5 the square bracket [ ]. "May 2 7Feb', “Mart, “Apes, Atem= [1 # empty rise Indexingin alist The elements of a list are indexed in a Won", ‘Tues* specife order. Ifthere ae n elements ina. prin (L{2}) list, then 0 will be the first index and n-1 the last. Output: wed EE > Wed] elements of Slicing a list Concatenating two lists Repeating elements in a list (Repetition) Using membership operators in a list ‘Traversing alist Accessing the To access the values in lists, you can use the square brackets with the index or indices to obtain the value available at that index. alist If you want to access a range of elements from a list, you need to slice it, A colon() is used to slice a list. With this operator, you can specify where to start the slicing, where to end, and specify the step. List slicing returns. a new lis from the existing lst. Concatenation means appending the elements ‘of one list to another. The repetition “operator is used to repeat elements in the sequence by a specified number of times, Items in the sequence are not copied but are referenced multiple times. The ‘in’ and ‘not in’ operators are the membership operators. They are used to check whether a value exists in the list oF sequence or not. If a value is found in the list, it returns True; otherwise, it returns False, Traversing a list means visiting every element of the list. This can be done by using loops. 2.1.3 Built-in Functions of lists You can use many built-in functions with a list. Some commonly used functions are discussed in the following table: lenQ) list) append) ‘The len() function returns the number of elements in a list. ‘The ist() function isalso called aconstructot. It is used to create alist with values and also ‘create an empty list. ‘The append{ ) function adds its arguments asasingle elementat the end of the lst. After ‘using the append() function, the length of thelist will be increased by one. text = ['I', ‘Love’, ‘my"] ‘text. append("India") print (text) supply = ["pen", “pencil”, harpener", "eraser", “ruler”, rayon" } print (supply[~-3:-1]) Output: ["eraser”, “euler"] >>> fruits = ["mouse", "keyboard", "joystick", “microphone”, “touch pen", trackball") >>> print (fruits[1:4]) Output: [*keyboard', ‘joystick’, “microphone’, ‘touch pen‘ ] marks1 = (1, 11, 22, 33] marks2 = (12, 14, 14, 15] marklist = marks1 + marks2 print(marklist) Output: [1, 11, 22, 33, 12, 14, 14, 15] marks = [5, 6, 7] print(marks * 3) Output: [5, 6, 7, 5, 6, 7,5, 6 7] ['summer*, ‘winter’, ‘autumn’, "monsoon" J ‘winter’ ina Output: True rainy’ not ina Output: True sandwich = [“bread", “butter, “jan"} for 4 in range(1en(sandwich)): print(sandwich{i]) Output: bread butter Jam item = ["India', ‘Japan’, 37, 63.6] 4 >>> print(len(item)) item = 1ist() print (item) a extend) insert() count() index() remove() pop() reverse() sort() sorted() min() max() sum() “The extenel( funetion iterates over is arguments and adds each element 10 the list at the he length of the list inereases by the rnomber of elements in the argumen end. ‘Vhe finction built-in insert() allows you to add an element at a specified position in the list The count() function retums the total number ‘of elements with the specified value provided in argument The index() function returns the index of the given clement in the list. Ifthe element is not present in the list, then it will give an error, The remove() function removes the first matching element that has been provided as the function argument from the lis. ‘The remove() function also removes the first occurrence of a duplicate item in the list. ‘The pop() function removes the element at the given index from the list and returns the removed item, It takes single index as an argument. "The reverse() function is used to reverse the elements of the list. This function does not retum any value. It reverses the sequence of the elements in the list and updates the original lst. ‘The sort() function arranges the elements of a given list either in an ascending or descending order. It changes the list and does not return any value, ‘The sorted() function sorts the elements of ‘given sequence in a specific order, either ascending or descending and returns the sorted list ‘The min() fanction returns the minimum value present in the list. ‘The max() function returns the maximum, value present in the list ‘The sum() function adds the elements of the sequence and returns the sum, stove’, ‘my’ els text = [ gaia’) text append print (text) + tgug', "sept" > month = [July's 248 oct", ‘dec"] month. insert (4, print(month) month = ['july’» ‘aus > ‘oct’, ‘aug’, ‘dec ] x = fruits. count ("aug' ) print(x) vowels = ['a"s rl index = [Link]('o") print( ‘The index of 0:', index) *nov') *sept's es num = [1 2, 3, 5, 6, 3, 2] [Link](3) print(num) food = ["icecream', ‘burger", “vegroll', "Gulab Jamun", ‘Ladoo"] food_drop = Food. pop(2) print( ‘Updated Food List:', food) Tum = (18, 28, 30, 48, 50, 60] ‘num. reverse() print (num) Vowels = ['er, * ay tuys to as vowels. sort() “I print(*Sorted list " Order): veagliSt (An ascending characters = ['e", +4: Teeter eh aes tue ge Prént(sorted(characters)) ti ['l, 'Love,, ‘my, ‘India’} (july, ‘aug, 'sepr, ‘oct’, nov, dec’) The index of 0:3 11, 2, 5, 6,3, 2] Updated List: (icecream’, "burger’, Gulab Jamun’, ‘Ladoo'] {60, 50, 40, 30, 20, 10] Sorted list (in ascending order) a i,'0, ul) fase, 04 0] Minimum list element: 12 Maximum list element : 75.5 75 grocery = (‘red sauce’, ‘salt’, ‘sugar'] grocery. append("Fruit Jam”) print(grocery) Output: [red sauce’, 'salt', ‘sugar’, ‘Fruit Jam'] GFEZBD write program to deletean element from alist, a Element saved at index will be removed.) sub = [‘English", ‘Hindi’, ‘French’, ‘Math’, 'Science'] sub_drop = [Link](-4) - print( ‘Deleted subject:', sub_drop) print( ‘Updated List:', sub) Output: Deleted subject: Hindi Updated List: [‘English’, ‘French’, ‘Math', ‘Science’ ] 2.1.4 Nested List A nested list is alist within a list. It is an ordered list that can contain any type of data. You can apply all the list functions to the nested list also, A nested list is created by placing a comma-separated sequence of sublists. You can access an individual item from a nested list using index Values as you do in the simple lis. Example: L= (1, 2, [11, 22, [33, 44]], 3, 4] 6 The list data type is a collection of data elements of the same or different data types © _Thelist() constructor or function is used to create an empty list Its called a constructor because it stores memory for lst objects. © The operator +'is used to concatenate two lists and the operator is used to replicate alist © The len() function retums the number of values or elements in a list, © The appendi) function adds its arguments as a single element to the end of the lst. © The extend) function iterates over its arguments and adds each element to the lst atthe end © The insert!) function allows you to add an element at the specified position in the list. © There are some other functions that can also be used with alist, lke sont), sorted), remove), pop(), sum(), min(), maxt), ete. © Apart ofa list can be extracted using the slice operation, © Allst within another list is called a nested list. 2.2 Tuples jects. It is a type of a sequence like strings and lits, clements of a tuple are enclosed within parentheses() It means that the elements t cannot be changed. They can be used to store values of different data types. —_ but it is immutable. The that are assigned to a tuple 2.2.1 Characteristics of Tuples The characte follo cs ofa tuple are + ‘Tuple items are stored in an order and this order cannot be changed ns afier the tuple ha + Tuples are unchangeable or immutable, You cannot change, add, or remove it been created. + Tuples can contain duplicate items. + ‘The tuples can contain items of different data types. 2.2.2 Tuple Operations Like list, you can perform many operations on a tuple as discussed below: FRieopatons nm Bam Creating a tuple Atuplecanbecreatedbyenclosingtheelements t = (35 335 434 53) inside parenthesis( ) and all the elements can gempty tuple be separated by commas. cup 2 0) #tuple with single element t= (56)) Accessing tuple Ina tuple, each itens is stored individually Tup = ("Monday’, "Tuesday", 2.5, 32, ‘w') elements and can be accessed through indexing. A >>> print(tup [1]) tuple can have positive or negative indexing. Qytput: Tuesday Slicing in atuple Tupleitemscanbeaccessed by using theslicing #2 = ("a", "b", ‘cy ‘d') operator colon '. Slicing uses indexing, either print (tup (1:21) positive or negative. Output: ('b",) Concatenating two Concatenation is the process of joining the tt = ("a', 2, 2.5) tuples elements of a tuple with another tuple. The t2= (2, "b', 5.5) ‘+ operator is used to concatenate two tuples. ¢3 = t14t2 print(t3) Output: ('a', 1, 2.5, 2, ‘b', 5.5) Repeating ‘The operator is used to repeat the elements t = (*Hel1o") * 3 clements ofa tuple of a tuple by a specified number of times. print(t) ‘The elements inthe tuple are not copied but Output; HelLokelLoHelio are referenced multiple times. Using membership The'in'and'notin'operatorsarethemembership t= (2, 2, 3, a", operators. They are used to check whether a 4 int value exists in the tuple or not. IF the valte #5 Qunut: Thue found in the tuple, it returns True, otherwise it returns False. operators. ‘Traversing a tuple means visiting the vehicles = [“car", "bus", “truck"] elements of the tuple at least once. This can for i in range(len(vehicies)): be done by using loops in Python. print(vehicles[i]) Output: ‘Traversing a tuple using loops car bus, ‘truck + 2.2.3 Built-in Functions of Tuples You can use various built-in functions to perform different operations on tuple. Some commonly used tuple functions are listed below: lent) ‘The len() function returns the length of a item=(‘pass’, ‘break’, 12, 2.5) 4 tuple, tuple() ‘The tuple( ) function is also called a constructor. item = tuple() oO It is used to create an empty tuple and also with print (item) values. count() ‘The count() function returns the total number item = (‘one’, 4, 1.5, 4, 4-5, 44, 3 of times an clement has appeared in a tuple. 4) You need to give the value of the element as an [Link](4) argument to the function. index() The index() function returns the index of item = the first occurrence of a given element in the 3) tuple. Ifthe element is not present in the tuple item. index('one") then it will give an error. tone’, 3, 1-5, 3-5, 4.5, 44, 8 max) ‘The max() function returns the maximum value @ = (6, 4, 2, 15) as from the tuple. max(a) min() ‘The min() function finds and displays the a= (6, 4, 2, 15) 2 ‘minimum value in a tuple. min(a) sum() The sum() function returns the total value of «= (1.1, 2, 2.5, 4.5, 9) 19.1 all the items in a tuple sum(x) sorted() ‘The sorted) function sorts the elements of a num = (9, 5, 23-5, 6.5, 1, 2.5) (2, 2.5, tuple. The sorting is done in ascending order sorted(num) 5, 6.5, by default. It returns a new sorted list and does 8, 23.5] not modify the original tuple. (EERIE) write program to ceatea tuple from alist, list1 = [1, 2, ‘a’, ‘two’, 4.5) print("\nTuple using List: ") print(tuple(1ist1)) Output: ———— = aad Observe the input and output. Tuple using List: |The tuple() function has converted (2, 2, ‘a', "two", 4.5) ——-_ thelist type into tuple type read ‘Tuplei = tuple(‘One') print("\nTuple with the use of functio print (Tuple1) Output: Observe the input and output. | ‘Tuple with the use of function: the tuple function has converted the (0','ni'e) — tring type into tuple type. t= (10, 9, 8.5, 5, 5, 2, 6) print("Original tuple is: ", t) tlist = list(t) tlist[-3] = 5.5 t = tuple(tlist) print (“updated tuple is," t) Output: Original tuple is: (10, 9, 8.5, 5, 5, 2, 6) Updated tuple is: (10, 9, 8.5, 5, 5.5, 2, 6) 2.2.4 Modifying Tuples As you know, tuples are immutable, they cannot be modified after they are explicit methods using which you can modify the tuples. created. However, there are Adding New Elements in the Tuples sw items at any You can add or modify an clement of a tuple by following an indirect approach. ‘To insert ne} position, first the tuple needs to be converted to a list using the list( ) function. Then, insert an clement at the desired location and again convert the list to a tuple. Consider following example: >>> tup = (1, ‘sweet’, 2, 4) Step 1: Convert tuple into list using the list() function. >>>temp=list (tup) >>>print (temp) [1, ‘sweet’, 2, 4] Step 2: Insert an element at the desired location, >>> temp[2] = 50 >>> print (temp) [1, ‘sweet’, 50, 4] Step 3: Convert the list to tuple using the tuple( ) function. >>> tup = tuple(temp) >>> print (tup) (2, ‘sweet’, 58, 4) By performing the above mentioned three steps, you can insert an item of the tuple atthe desired position. Packing and Unpacking Tuples You can modify the tuples using packing-unpacking method also. To create a tuple from a set of values is called packing and separating individual values from a tuple is called unpacki Syntax for unpacking: , , , . = tuple_name ‘The number of variables at leit side ofthe assignment must match with the number of elements in the tuple at right side, Bi acs : > Example: tl= (2, 4, 6, 8) a,b,c, d=t1 First element of the tuple will be assigned to the variable a, second element of the tuple will be assigned 10 the variable b, and so on. Example: >>> t1 = [2, 4, 6, 8] >>> a,b, cy d=th >>> print(a, b, c, d) 2,4, 6,8 2.2.5 Nested Tuples A tuple defined inside another tuple is a nested tuple. In a nested tuple, each sub-tuple is considered an clement of the main tuple. Consider the following example: » “two", "three", (4, 2, 3)) my_tuple = (“on © Atuple is a collection of objects. Elements of a tuple are enclosed in parentheses and are separated by the comma. Ifa sequence has comma separated elements without parentheses, it is also treated as a tuple. Tuples are ordered sequences as each element has a fixed position. Indexing is used to access the elements ofa tuple You can concatenate two tuples together using the plus (+) operator. The repetition operator (*) is used to repeat the elements ofa tuple by a specified number of times. Membership operator ‘in’ checks whether an element is present in the tuple or not, and ‘not in’ does the opposite. Tuple manipulation functions are: len(), tuple(), count(), index(), sorted(), min(), max(, and sum(). To create a tuple from a set of values is called packing and separating individual values from a tuple element is called unpacking. ooo 6 eo 2.3 Dictionaries Dictionary is a data type in Python. It is an unordered collection of items. Each item of a dictionary has a key-value pair, The elements of the dictionary data type are ordered and can be changed after defining, Dictionary is a mutable data type. So, the values can be added, removed, and changed at any time. However, the keys of the dictionaries are immutable. 2.3.1 Characteristics of Dictionaries + Dictionaries are unordered. Dictionary keys must be unique and immutable, onsidered to be mutable. ‘The elements in a dictionary are indexed by keys and not numbers. + + Values in the dictionary can be changed. Hence, it + 2.3.2 Creating a Dictionary A dictionary can be created by enclosing a comma-se A colon (:) separates each key from its associated value. arated list of key-value pairs iP curly braces {} P Example: mark_list = {'name': ‘Haritika’, ‘marks’: [26, 29, 30]} Creating a Dictionary using the dict() Function ‘The dict() function is used to create a dictionary with or without key-value P: Example: >>> name = dict() >>> print (name) Output: tt 2.3.3 Adding Elements to the Dictionary In Python dictionary, addition of the elements can be done in multiple ways. One value at a time can be added to a dictionary by defining the value along with the key, for example, dict{Key] = "Value. number = dict(I = ‘one’, II = ‘two’, III = 'three') print (number) Output: (°F: ‘one’, ‘EE': "two", ‘IIE': ‘three’} air passed as an argument, 2.3.4 Accessing Elements of a Dictionary Ina list and tuple, the elements can be accessed through indexing. However, in a dictionary, you can access the elements by referring to their keys, inside square brackets. Syntax: dictionary name[key] Example: day = {1: ‘Non', day(2] Output: ‘Tue’ "Tue', 3: "Wed"} 2.3.5 Traversing a Dictionary “Traversal refers to visiting each element in the collection at least o, mee. It because traversing uses loops to visit key-value pairs. Using the for loca: 2° alled iterating over loop makes traversing very easy. *'T90p with membership operator i! Example: Book = {'Book 1': ‘Alice’, ‘Book 2° for K in Book: print (K, ":", Book [K]) Output: Book 1: Alice Book 2: Granny "Granny" } 2.3.6 Mutability of a Dictionary The dictionary’ is considered as a mutable data type that allows you to perform insertion, updating, and deletion operations. Python dictionaries can handle complicated data types. For example, in library management, tasks such as sorting of books by subject and author name, as well as handling maintenance and return processes, can be efficiently accomplished. This can be achieved with the help of dictionary Kevivalue pairs, where data may be uniquely identified using unique keys and values can be inserted, moditied, and deleted as needed. Mutability in a dictionary can be implemented in two ways: + Adding a new item + Modifying an existing item B Adding a new item: To create a >>> map = {‘a":‘one', ‘b':'two"', {’a": ‘one’, ‘b': "two", "c": new item, you must create a new '¢":"three"} “three', four'} index key, which will be used to. >?? map['d"]="four’ re the value in your dictionary. ??? Print(map) Modifying an existing item: The >>> fruits = {'2":"apple', ‘apple’, 'b': "banana", value of a Key can be modified or ‘b": "banana", "c*:'cucumber*} cherry} changed by using an assignment operator, Ps >>> fruits 2.3.7 Built-in Functions of Dictionaries # changing value for ‘c’ key >>> fruits['c'] = ‘cherry ‘The Ien() function returns the number of elements in adictionary, ie. the total number of items o key:value pairs. len() keys() ‘The keys() function will return the keys of the dictionary items only. As a dictionary is an unordered collection of items, thus you ‘may observe a change in the sequence of the keys that you have saved. values() It will return only the values of keys of the dictionary items. It will eturnall the dictionary items including the key-value pairs items() It is used to access a value for a key in Python dictionary. Ifa key exists, the get() function returns the specific value, otherwise it return None; if the value at the parameter is specified, it return the specified value. ‘The fromkeys( ) function creates a new dictionary from the given sequence like string, list, set, or tuple as keys and with the specified values, It returns a new dictionary with the values. get() fromkeys() >>> Emp = {'Name": "Raman", ‘Dept: "Sai':250¢0} >>> Ien(Emp) Output: 3 >>> print([Link]()) Output: dict _keys({'Name', "Dept", 'Sal"]) >>> print ([Link]()) Output: dict_values({*Raman', ‘HR', 25000]) >>> print (Emp. itens()) Output: dict_items({(*Name", *Raman’), Coept*, HR), ('Sal", 25000)]) >>> print Emp. getName" )) Output: Raman x (key, *key2", *key3") y= "Hello" demo_dict = [Link](x, y) print(demo_dict) Output: {‘key1" “Hello'} ‘Hello’, 'key2': ‘Hello, setdefault() update() copy() sorted() pop() opitem() lear() ian, The setdefault() function returns the value of the specified key in the dictionary (if it is present in the dictionary). If the key is not found, then it adds the key with the specified default value given as a parameter. ‘The update() function updates the dictionary with the elements from another dictionary or from another sequence of key/value pais. ‘The copy( ) function returns a shallow copy of the dictionary, by default, ‘This function is used to sort the dictionary. The sorted() function returns a new sorted collection, keeping the original dictionary unchanged. ‘The pop() function is used to delete a key and its value that has been passed as the function argument. If the key does not exist in the dictionary, then it returns default value if ified in the function argument. “The popitem() function removes and retuens the last added key-value pair in the dictionary. Pairs are retuned in Last In First Out (LIFO) order. “The dlear() function removes all the key-value pairs from the dictionary, making it empty. *, 10000) value « Emp. setdefault(’ S22 the return value 4s alue is: 25000 » value) print(" ‘Output: The return ¥ ‘b's "boy" } data) {'a's'apple"» data . tionary print ("original 04 data2 = {'c':"cap"} datat update(data2) print("updated Dictionary:", datal) Output: oo original Dictionary: {'2": ‘apple’, *boy'} Updated Dictionary: {'a': ‘apple’, "oy', ‘c's ‘cap'} 1:3} un = newnum = [Link]() print(“original dictionary: “, num) print("Copied dictionary: ", newnum) Output: original dictionary: {'a': 1, Copied dictionary: ("a': 1, "b': >>> num= {'a'zd, 'c':3, 'b':2} >>> print (sorted([Link]())) Output: ['a', "b', *e"] aeH Ht, 'bes2, 4 x = [Link]("b') print("The dictionary after deleting", num) print (“item deleted is :", x) Output: The dictionary after deleting {'a': 1, '¢': 3) item deleted is : 2 51, *b!r2, *ets3y Print("Ttem popped: , num. popitem()) print("Items remaining in the dictionary:"» num) Output: Tem popped: (*c', 3) Items remaining i ict Den yamine in the dictionary: {‘a' t+ num = {'a':2, "b':2, tr 1» *!:3) Print("Dictionar nary before deletion:", nul [Link]() “iets na Output: Pint (“Dic Print("Dictionary after deletion:*, num) Dictionary be PEstign@ry before deletion: tain 1 ‘bY Dictlonary after deletion: {} =X min() ‘The min() function fetches the minimum key, num = {*2":1, 'D":2, v = min(num) print (‘minimum value: *, v) Output: minimum valu max() ‘The max() function fetches the maximum key, num = {‘a":1, "b’ v= max(num) print(‘maximum value: ", v) Output: maximum valu sum() Itadds al the keys in the dictionary and returns num = {1:'a", 2:'b', the sum, total = sum(num) print ("Sum of keys in the dictionary : ", total) Output: sum of keys in the dictionary: 6 ary ret} Consider the following programs to understand some of the operations on dictionaries. Write a program that copies one dictionary to another. # Python program to copy dictionaries # using the copy() method # creating the dictionary dict_a = {‘id' : 1e1, ‘name’ : ‘amit’, ‘age’: 21} # creating a copy dict_b = dict_a.copy() # printing the dictionaries print ("Dictionary \'dict_a\’ is... print(dict_a) print("Dictionary \'dict_b\' is print(dict_b) ‘Wit a program to concatenate two dictionaries to create new one. dict=(1:10, 2:20} dic3=(5:50, 6:60} dica = {} for din (dict, dic2, dic3): [Link](d) print(dic4) GxteTID- © Dictionary is a mutable data type. © Anentry ina dictionary consists of a key-value pair 6 ° Keys of a dictionary must be unique and of immutable data type. Values of dictionary can be list, integer, float, string, or any data type. They can be repeated ina dictionary. 7 ae @ _Anempty dictionary can be created using { } brackets. ey-value pair passed as an argument, © The dic() function i used to create a dictionary with or without Key" © Traversal means visting every element in the collection. © The len() function returns the total length of the dictionary. femerwaton very easy and qui © Python dictionary uses a set of builtin functions that makes is IMPS ionaries, Functions like len(), key(), value(), copy(),items(), get), et. are Jean), del), pop), and © Python allows deleting key-value pair from the dictionary using functions Cea ophera() perations based erform operations based on © The functions min), maxi), and count) work on the dictionary keys and perfow ope the key. 2.4 Modules In Python, a module refers to a Python file that contains statements and definitions (functions). A plenty ol modules are available in the standard library of Python that you can import and use in your programs. These modules are pre-defined in Python library ‘To add a module or a part of a module in your code, the import and from statements are used 2.4.1 The import Statement The import statement can be used to add a module in your code. You can access the definitions inside it by using the dot(.) operator. Example: import math print("The value of square root of 25 Output: [Link](25)) The value of square root of 25 = 5.0 2.4.2 The from Statement oe statement is used to add specific attributes or functions fom a module into the current Python Example: from math import * print("The value of square root of 25 = " Output: The value of square root of 25 =5.9 » sart(25)) 2.4.3 The math Module Ee furs the square oe = number. The square root ofa negative ttpecstleah fal se tember ie dees) of ese 1081 in floor() pow(base, exp) fabs() degrees(x) radians(x) sin() cos() tan) It rounds off a floating point number to the next, largest integer. This function takes a number and rounds it down to the nearest integer that is not greater than the input value. ‘This method evaluates the base raised to the power exp and returns the result. It returns the absolute value of the number x where xis a numeric expression. It always returns absolute value in float. It converts angle x from radians to degrees, where x must be a numeric value, It converts angle x from degrees to radians, where x must be a numeric value ‘This method returns the sine of a number x. ‘To find the sine of degrees, it must first be converted. into radians using the [Link]() function. It returns the cosine of value x given to function cos(x). The value passed in this function should be in radians. ‘This function returns the tangent of a number. The ‘value passed in this function should be in radians. 2.4.4 The random Module ‘The random module is a built-in module in Python to generate the pseudo-random numbers. Random numbers are used in various fields like in science, art, statistics, cryptography, gaming, and many other fields. Nowadays, Captcha, automatic password generator, etc,, are some of the popular uses of random numbers. >>> [Link](5.3) 6 >>> [Link](-2.4) 2 >>> math. floor(4.6) 4 >>> [Link](~28.3) 28 >>> math. pow(-2, 3) -8.0 >>» math. pow(4, 2) 16.0 >>> math. Fabs (53 + 2.9) 55.9 >>> [Link](~10) 10.0 >>> math. fabs(-5 + 2) 3.0 >>> [Link](3) 171887338539 >»> math. degrees(~3) ~171,887338539 >>omath. degrees(®) 0 >>> math. radians(3) 0.0523598775598 >>> [Link](-3) -0,0523598775598 >>> math. radians(@) 0.0 >>> [Link](32) ~0,9880316240928618 >>> print ([Link]([Link](38))) 0.4ga9s999999999908 >>> print([Link]([Link](32))) 0.8660254037644387 >>> print([Link]([Link](3@))) 0.5773502691896257 random() Therandom() method returnsa loatnumber 497256 D Seems 0090 i cn es 0k Oe randon() take any intial value as an argument. 37303700779782734 dint (1, 3) alee Jnteger value from 1 to 3. The >> [Link]( indor randint() The randint() function generates random >>> randon rank integer values between the specific integer This wil sve YOU UL values. lt works only om integer values. outputcanbels2007) >>> random. randint(1-5, 8. Valuetrror: non-integer randrange — This method generates the random numbers >>> random. randrange(ts on muraber betwen (tart, top, within the range specified by start and stop This example means that he Teneo Nene vee step) values. The step value is optional. The value to 10 will be generated while skipping. c Of start is 0, by default, Similarly, the value A possible output can be: 1, 3, 5, 7, 9. It will not produce of step is 1, by default. It also accepts integer 2, 4, 6, and 10. values only. ‘Write a program to generate alist of 100 random number using a for loop. import random mylist = [] for i in range(@, 100): x = [Link] (1, 18) mylist..append(x) print (mylist) ‘Write a program of a number guessing game in which the user selects a range. guess: print("You guessed too small!") elif x < guess: print ("You guessed too high!") # If guessing is more than the required guesses, # this output is shown. if count >= math. 1og(upper - lower +1, 2): print("\nThe number is %d." %x) print("\tBetter luck next time!") Output: Enter Lower bound: 2 Enter Upper bound: 1@ You've only 3 chances to guess the integer! Guess a number: 7 You guessed too small! Guess a number: 8 You guessed too small! Guess a number: 9 Congratulations you did it in 3 tries. 2.4.5 The statistics Module Python statistics module is used to calculate mathematical statistics of numeric data, ferioaiay Purpose ee | mean() Itcalculates the arithmetic mean of the >>> [Link]([3, 4, 4, 6]) numbers in a sequence or set, 4.25 median() It returns the middle value of numeric >>> [Link]([6, 8, 1, 4, 2]) 4 ance or set Gata ina seg >>> [Link]([1, 2, 3, 7, 8, 9]) 5.8 mode() ‘The mode() function returns the most >>> statistics. mode([2, 5, 3, 2, 8, 3, 9, 4, 2, in the sequence or set, 5, 6]) repeated value i a 7 >>> statistics. mode([6, 5, 3, 6, 1, 3, 2, 4, 6, 5, 6]) 6 i import statistics 77, 85> values = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, m m pr P) il = [Link](values) 12 = statistics .mode(values) i1 = [Link](values) rint The mean of the values is rint("The mode of the values is m1) m2) Print ("The median of the values is =", m3) {Ss Recap) ° Ce 10, eke ‘The import statement can be used to add a module in your code. You can access the definitions inside it Using the dot operator 86) Output: values is The mean of the = 89.76923076923077 The mode of the values $5 « 86 The median of the values is = gy The [Link](n) method returns the square root of a given number. The ceil) function rounds off a floating point number to the next largest integer The floor() function rounds off a number to the nearest integer, which is not greater than number (x), The pow(base, exp) method evaluates the base raised to the power exp and re The fabs(x) function returns the absolute The sin(x), cos(x), and tan(x) methods ret The mean(), program, value of the number x, where x is a nu fava Brain Developer in the blanks. The ‘The function append( ) adds its argument A tuple defined in another tuple is called a The The ‘The function adds the The function [Link]( ) feiches the The function removes, The _ a ______ means visiting every e| _ data type uses square br operator is used to replicate th operator returns fs ifn eleme asa single he list elements of th and returns the lement of a tuple ackets for comm; la — °PeTatos in Python are used to che tuple tis NOt present in the ——— of the stadded key. ister Separated values in Py clement to the Nee of an turns the result, ric expression turn te sine, cosine, and tangent of a numbe The random module is a built-in Python module 1X respectively, used to generate the pseudo-random numbers. median(), and mode( functions can be used by importing statistics module in Python thon ——___ of the list list “vence and returns the sum, dictionary. lue pair in the dictionary. fem in a tuple.

You might also like