For example, >>> name = “ARTIFICIAL INTELLIGENCE” >>> print(“length of variable name that holds a string is:”, len(name)) Output length of variable name that holds a string is: 23 b) lower(): This function is used to convert all the uppercase letters of a string into lowercase. For example, >>> name = “ARTIFICIAL INTELLIGENCE” >>> print(“String after conversion:”, name.lower()) Output String after conversion: artificial intelligence c) capitalize(): This function is used to capitalize first letter of the string. For example, >>> name = “artificial intelligence” >>> print(“String after conversion: ”, name.capitalize()) Output String after conversion: Artificial intelligence d) join(): This function is used to join the string representation of elements in a sequence. For example, >>> name1= “ARTIFICIAL” >>> name2= “INTELLIGENCE” >>> sequence= (name1, name2) >>> name= “ ”.join(sequence) >>> print(“string after joining name1 and name2 is:”, name) Output string after joining name1 and name2 is: ARTIFICIAL INTELLIGENCE e) split(): This function is used to split the string. For example, Output >>> name= “ARTIFICIAL INTELLIGENCE” >>> name1= name.split() [‘ARTIFICIAL’, ‘INTELLIGENCE’] >>> print(name1) PM Publishers Pvt. Ltd. 151
f) find(): This function is used to check whether the substring is available in the string or not. If it is available in the string, then you will get the lowest index of the substring. For example, >>> name1= “ARTIFICIAL INTELLIGENCE” >>> name2= “INTELLIGENCE” >>> print(”name2 is available at index:“, name1.find(name2)) Output name2 is available at index: 11 g) replace(): This function is used to replace the old string with the new string. For example, >>> name1=“ARTIFICIAL INTELLIGENCE” >>> name=name1.replace(“INTELLIGENCE”, “ROBOT”) >>> print(“The new name after replacement:”, name) Output The new name after replacement: ARTIFICIAL ROBOT Traversing a List As you know, lists are mutable or changeable and consist of a sequence of elements. Python offers a way to access each element of a list one-by-one using a traversing method. The method of traversing a list is the same as traversing a string. Let us understand the concept of list traversal with the help of a simple example given below: >>> name = [‘R’, ‘O’, ‘B’, ‘O’, ‘T’] >>> print(“All the traversing elements of a list:”) >>> for i in name: print(i) Here, the control variable ‘i’ will be assigned to each Output element of the list one-by-one. Therefore, loop variable ‘i’ will be assigned to the element R of the defined list All the traversing elements of a list: ‘name’ in the first iteration and so element R will be R printed. In the second iteration, this loop variable gets O the value of the next element ‘O’ which will get printed. B The process of assigning and printing elements will O continue until the last element of the list. T If you want to traverse a list using indexes of elements, in such a case you can use range() and len() functions. Let us understand the syntax of traversing a list using functions with the help of a simple example. Suppose you have defined a list named Li like: >>> Li = [‘C’, ‘A’, ‘T’] Output The basic syntax of using these functions to traverse a list are as follows: C >>> for i in range(len(Li)): A print(Li[i]) T Artificial Intelligence - 9 152
Now, if you want to print all the elements of a list with their index positions, you must write the following lines of code: Output >>> Li = [‘V’, ‘I’, ‘D’, ‘Y’, ‘A’] >>> length = len(Li) # Determine length 0V >>> for i in range(length): 1I print(i, Li[i]) 2D 3Y 4A Comparing Lists Python offers a wide variety of comparison operators. Using these operators, you can easily compare values, strings or lists. In Python, the lists are compared element-by-element. If the corresponding elements are of the same type, ordinary comparison rules are used. If the corresponding elements are of different types, the type names are compared, since there is no other rational basis for comparison. Let us understand with the help of examples given below: >>> List_1 = [10,11,12,13] >>> List_2 = [10,11,12,13] >>> List_3 = [10,11,[12,13]] >>> List_1 == List_2 #Statement1 >>> List_1 == List_3 #Statement2 Here, statement 1 evaluates to True whereas statement 2 evaluates to False. While using comparison operators in case of lists, you should remember that the corresponding elements of two lists must be of comparable type. Operations on Lists Like string, you can perform various operations on lists like joining two lists, replicating a list and slicing a list. In this section, you will learn how to perform various operations on a list. a) Joining Lists: You have learnt about string concatenation operator. Similarly, two lists can be added using concatenation operator(+). While using + operator, you should remember that both operands must be of list types. For example, both Lists:”, List_join) >>> List_1 = [10,11,12,13] >>> List_2 = [14,15,16,17] >>> List_join = List_1 + List_2 >>> print(“The new list after joining Output The new list after joining both Lists: [10, 11, 12, 13, 14, 15, 16, 17] PM Publishers Pvt. Ltd. 153
b) Replicating Lists: Like string replication, you can replicate a list as many times as you need. To do this, you can use a replication operator (*). For example, >>> List_1 = [10,11,12,13] >>> print(“List after replication is:”, List_1*3) Output List after replication is: [10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13] c) Slicing Lists: As you read earlier, string slicing refers to the process of extracting a substring from a string. Similarly, lists slicing refers to a process of extracting the sub part of a list. For example, >>> List_1 = [10,11,12,13] >>> List_2 = List_1[2:4] >>> print(“The slicing list is:”, List_2) Output The slicing list is: [12, 13] Sometimes, you want to extract elements from a list in a non-consecutive manner. In such a situation, you can use slice steps. For example, >>> List_1 = [10,11,12,13] >>> List_2 = List_1[0:4:2] >>> print(List_2) Start Stop Steps Output 042 [10, 12] If you want to print a list in reverse order, then you can use the following expression: >>> List_name[::-1] Let us understand the concept of reversing lists with the help of an example given below: >>> List_1 = [10,11,12,13] >>> List_2 = [20,30,40,50] >>> List_1_rev = List_1[::-1] >>> List_2_rev = List_2[::-1] >>> print(“List 1 after reversing:”, List_1_rev) >>> print(“List 2 after reversing:”, List_2_rev) Output List 1 after reversing: [13, 12, 11, 10] List 2 after reversing: [50, 40, 30, 20] Artificial Intelligence - 9 154
List Built-in Functions/Methods Python offers a wide variety of built-in functions to perform various operations on a list. In this section, we will learn some of the most commonly used functions of lists manipulation. Inserting Elements in List You can use insertion and deletion methods to manipulate an existing list. As you read earlier, insert(), append() and extend() functions are used to add new elements in a list. a) append(): This function is used to add a new item to the end of the list. The basic syntax of append() function is as follows: Listname.append(new_item) Let us understand the concept of append() function with the help of an example given below: >>> List_1 = [10,11,12,13] >>> List_1.append(14) >>> print(“List after adding new element:”, List_1) Output List after adding new element: [10, 11, 12, 13, 14] You should remember that only one item can be added at a time using append() function. If you want to add more elements, you can use extend() method. extend() method is also used to add elements of another list to the existing list. b) extend(): As you read earlier, this function is used to add multiple elements in an existing list. The basic syntax of extend() function is as follows: Listname.extend([Set of new items]) Let us understand the concept of extend() function with the help of an example given below: >>> List_1 = [10,11,12,13] >>> List_1.extend([14,15,16]) >>> print(“List after adding new set of elements:”, List_1) Output List after adding new set of elements: [10, 11, 12, 13, 14, 15, 16] c) insert(): This function is used to insert an element in the existing list at a specified location. Two arguments are used in this function: index value where you want to insert a new element and the new element itself. The basic syntax of insert() function is as follows: Listname.insert(index_value, new_item) Let us understand the concept of insert() function with the help of an example given below: >>> List_1 = [10,11,12,13] >>> List_1.insert(2,15) >>> print(“list after inserting new element at 2nd index:”, List_1) Output list after inserting new element at 2nd index: [10, 11, 15, 12, 13] PM Publishers Pvt. Ltd. 155
Deleting Elements from List In this section, we will learn how to delete an element from the list using built-in-functions: a) pop(): This function is used to remove the desired element from the list using index value as a parameter. The basic syntax of pop() function is as follows: Listname.pop(index_value) Let us understand the concept of pop() function with the help of an example given below: >>> List_1 = [40,20,19,13,14,13] >>> List_1.pop(3) >>> print(“list after popping element from the specified index:”, List_1) Output list after popping element from the specified index: [40, 20, 19, 14, 13] While using the pop() function, you should remember that if you do not specify any index value as a parameter, then this function removes the last element from the list. b) remove(): This function is mostly used to remove the first occurrence of the specified item from the list when you have no idea about the index value. The basic syntax of remove() function is as follows: Listname.remove(list_item) Let us understand the concept of remove() function with the help of an example given below: >>> List_1 = [40,20,19,13,14,13] >>> List_1.remove(13) #it will remove the first occurrence of 13 >>> print(“list after removing element 13 from the list:”, List_1) Output list after removing element 13 from the list: [40, 20, 19, 14, 13] c) del(): This function is used to remove the individual element, the sublist of elements or delete the list completely. The basic syntax of del() function is as follows: del Listname[index_value] del Listname[start:stop:step] del Listname #it will be used to delete list completely Let us understand the concept of del() function with the help of examples given below: Example 1: >>> List_1 = [40,20,19,13,14,13] >>> del List_1[2] >>> print(“list after deleting element from the desired index:”, List_1) Output list after deleting element from the desired index: [40, 20, 13, 14, 13] Artificial Intelligence - 9 156
Example 2: >>> List_1 = [40,20,19,13,14,13] >>> del List_1[0:4:2] >>> print(“list after deleting elements in the slice steps:”, List_1) Output list after deleting elements in the slice steps: [20, 13, 14, 13] Some other List Functions a) count(): You can use count() function to count the number of duplicated items available in the defined list. The basic syntax of count() function is as follows: Listname.count(list_item) Let us understand the concept of count() function with the help of an example given below: >>> List_1 = [10,11,12,13,13,13] >>> List_2 = List_1.count(13) >>> print(”The result is: ”, List_2) Output The result is: 3 b) reverse(): This function is used to reverse the order of the elements of the list. The basic syntax of reverse() function is as follows: Listname.reverse() Let us understand the concept of reverse() function with the help of an example given below: >>> List_1 = [10,11,12,13] >>> List_1.reverse() >>> print(“list after using reverse() function:”, List_1) Output list after using reverse() function: [13, 12, 11, 10] c) sort(): In general, sorting refers to a process of arranging elements either in the ascending order or descending order. While programming in Python, you can use sort() function to arrange the elements in a specific order. The basic syntax of sort() function is as follows: Listname.sort() Let us understand the concept of sort() function with the help of an example given below: >>> List_1 = [40,20,19,13,29] >>> List_1.sort() # To arrange the items in ascending order >>> print(“list after using sort() function:”, List_1) Output list after using sort() function: [13, 19, 20, 29, 40] PM Publishers Pvt. Ltd. 157
If you want to sort the elements of a list in descending order, then you can use a reverse parameter in the sort() function. You should remember that the default value of the reverse parameter is False. To print the elements of a list in descending order, you can keep the value of the reverse parameter True. For example, >>> List_1 = [10,20,19,43,58,60] >>> List_1.sort(reverse=True) >>> #To arrange the items in descending order >>> print(“list after using sort() with reverse parameter:”, List_1) Output list after using sort() with reverse parameter: [60, 58, 43, 20, 19, 10] d) index(): Using this method, you can search the location or the index value of the element in the defined list. The basic syntax of index() function is as follows: Listname.index(list_item) Let us understand the concept of index() function with the help of an example given below: >>> List_1 = [40,20,19,13,13,13] >>> print(“The index value of element 19 in the list is:”, List_1.index(19)) Output The index value of element 19 in the list is: 2 e) clear(): This method is used to clear all the items from the defined list. The basic syntax of clear() function is as follows: Listname.clear() Let us understand the concept of clear() function with the help of an example given below: >>> List_1 = [10,11,12,13,13,13] >>> List_1.clear() >>> print(“The list after using clear function:”, List_1) Output The list after using clear function: [ ] DO YOU KNOW ? Python has a great collec on of libraries which makes it the most popular programming language used for AI. Artificial Intelligence - 9 158
In a Nutshell 1. The set of instruc ons wri en in a language which a computer can understand is called a program. 2. An algorithm is a step-by-step procedure to solve any par cular task whereas a flowchart is a diagramma c representa on of problem solving process. 3. The last step in solving a problem is to convert the flowchart into a program. 4. Python is a high level, structured, open source programming language that supports the development of wide range of applica ons from simple text processing to worldwide web browser to games. 5. The online game portal ‘CodeCombat’ is a good pla orm to learn and improve coding skills. 6. An Integrated Development and Learning Environment (IDLE) is the most popular graphics-based development environment for Python used to create, edit and debug a program. 7. The interac ve mode is best for small programs but for saving the program for future use, the script mode is used. 8. Python uses indenta on to express the block structure of a program. 9. Character set is a set of valid characters that a language can recognize. 10. A token is the smallest element of a program that is meaningful to the interpreter such as keywords, delimiters, operators and many more. 11. Operators are the special symbols that carry out arithme c and logical computa ons such as Arithme c, Rela onal, Logical and Assignment. 12. Comments are very important while wri ng any language. Python supports Single line and Mul -line comments in Python. 13. Data types are used to define the type of value a data can contain. Python has built-in data types such as numbers, strings, tuples, list, sets, etc. 14. A sequence is an ordered collec on of items. The three types of sequence data are Strings, Lists and Tuples. 15. Variables are used to store data in the memory. The data can be numbers, text and objects. 16. The input() and print() func ons are used for standard input and output opera ons in Python. 17. Control statements are used to control or change the flow of execu on. Three basic control structures are: Sequen al, Condi onal and Loop. 18. Condi onal control structure tells the program which ac on to take, based on certain condi on such as if, if-else, nested if, elif, etc. 19. The loop control structure enables a program to perform one or more ac ons repeatedly as long as certain condi ons are met such as for and while. 20. There are various string manipula on techniques such as traversing a string, string opera ons and string slicing. 21. There are various list manipula on techniques such as traversing a list, comparing lists, and opera ons on lists. PM Publishers Pvt. Ltd. 159
Multiple Choice Questions 1. The direc on of flow in any flowchart should be from ...................... . a) top to bo om b) le to right c) both (a) and (b) d) None of these 2. The symbol used to connect the different shapes in a flowchart is ...................... . a) b) c) d) 3. ……………………….. is a set of valid characters that a language can recognize. a) Token b) Character set c) Variable d) Keywords 4. The values operated by the operator are called ........................... . a) Keywords b) Operands c) Delimiters d) Literals 5. A ...................... control structure shows one or more ac ons following each other in order. a) sequen al b) procedure c) branching d) looping 6. ..................... statement is used to execute one or more statements depending on whether a condi on is True or not. a) Loop b) If c) Break d) Con nue 7. ...............……... causes a sec on of your program to be repeated a certain number of mes. a) Break b) If c) Con nue d) Loop 8. ...............……... can be used to uncondi onally jump out of the loop. a) Con nue b) Loop c) Break d) While 9. Which of the following func ons is used to remove the desired element from the exis ng list using index value as a parameter? a) remove() b) pop() c) append() d) push() 10. Which of the following func ons is used to arrange the list elements in a specific order? a) append() b) index() c) sort() d) reverse() 11. You can use …………………….. if you want to add more than one element in an exis ng list. a) append() b) insert() c) extend() d) push() 12. A technical term …………. refers to a process of itera ng through the elements of a string. a) sequen al b) searching c) traversing d) processing Answers 1. c 2. a 3. b 4. b 5. a 6. b 7. d 8. c 9. b 10. c 11. c 12. c Artificial Intelligence - 9 160
Fill in the Blanks 1. The rhombus-shaped symbol in a flowchart is known as ........................... . 2. Rectangle is used to show the ................................ part of the flowchart. 3 Python uses ........................... to express the block structure of a program. 4. ........................... are the reserved words in Python and cannot be used as constant, variable or any other identifier names. 5. ....................... are the data items which never change their value throughout program run. 6. A ........................... is an ordered collection of items, indexed by positive integers. 7. When .......................... decisions are involved, we can put ifs together. 8. .......................... is the process of placing the if or if-else or elif statement. 9. .......................... statement is used to skip the rest of the statements of the current loop block and to move to next iteration of the loop. 10. By default, indexing always starts with ……………………... which means that the index of the first element of the sequence is ……….......… . 11. The ………………………………. operators in Python are used to test whether a specified value is available within a sequence or not. 12. The ‘not in’ operator evaluates to …………………………. if a character or a substring does not exist in the specified string. Answers 1. Decision Box 2. Processing 3. Indenta on 4. Keywords 5. Literals 6. Sequence 7. Mul path 8. Nes ng 9. Con nue 10. 0, 0 11. Membership 12. True Evaluate Yourself State T for True or F for False for the following statements. 1 Input/Output box is a rectangle-shaped symbol used for doing calcula ons. 2. A flowchart helps in the development of a program. 3. Python doesn’t support mul ple structure approach. 4. The text wri en in the comments are ignored by Python. 5. Operator precedence determines the order in which the expression are evaluated. 6. Logical error occurs when the rules and regula ons of computer language are violated. 7. The if...elif...else executes only one block of code among several blocks. 8. Con nue and Break statements have the same effect. 9. Condi onal and looping statements are structured using indenta on rather than using curly braces. PM Publishers Pvt. Ltd. 161
10. The join() func on is used to join the string representa on of elements in a sequence. 11. List slicing refers to a process of extrac ng the sub part of a list. 12. del() func on is used to remove the first occurrence of the specified item from the list. Answers 1. F 2. T 3. F 4. T 5. T 6. F 7. T 8. F 9. T 10. T 11. T 12. F Writing Subjective Responses 1. Write a short note on data types in Python. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 2. What do you understand by the term ‘Operators’? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. What is the difference between single line and mul -line comments? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 4. Write a short note on control structures. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. What do you understand by the following: a) append() ............................................................................................................................................... b) clear() ............................................................................................................................................... c) extend() ............................................................................................................................................... d) ............................................................................................................................................... Artificial Intelligence - 9 162
e) ............................................................................................................................................... f) ............................................................................................................................................... 6. What do you understand by the term ‘slicing a string’? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... Short Answer Questions 1. Write any three advantages and disadvantages of a flowchart. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 2. What is operator precedence? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. What do you mean by a variable? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 4. Write any 3 features of Python programming language. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. Write a short note on the following: a) Rela onal Operators ................................................................................................................................................ ................................................................................................................................................ b) Iden fiers ................................................................................................................................................ ................................................................................................................................................ c) Logical Operators ................................................................................................................................................ ................................................................................................................................................ d) Sequence ................................................................................................................................................ ................................................................................................................................................ PM Publishers Pvt. Ltd. 163
Long Answer Questions 1. Differen ate between the following: a) For loop and While loop ................................................................................................................................................ ................................................................................................................................................ ................................................................................................................................................ b) Break statement and Con nue statement ................................................................................................................................................ ................................................................................................................................................ ................................................................................................................................................ c) Membership operator and Comparison operator ................................................................................................................................................ ................................................................................................................................................ ................................................................................................................................................ d) Syntax errors and Logical errors ................................................................................................................................................ ................................................................................................................................................ ................................................................................................................................................ 2. Explain the importance of Indenta on in Python. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. “Loop causes a sec on of your program to be repeated certain number of mes”. Explain. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 4. Name and explain string built-in func on. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. List and explain various opera ons that can be performed on a list. ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... Artificial Intelligence - 9 164
Application Based Questions 1. Rahul wants to make a program in Python using mul ple condi ons like finding the smallest number among three numbers entered by him. But, he doesn’t know how to do it. Can you help him by sugges ng which type of statement would he use to do so? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 2. Meenal has wri en a Python code in which two ac ons are performed on the basis of condi onal expression outcome. According to you, which type of condi onal statement could she use while wri ng a code? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. Meenakshi wants to write a program in Python IDLE to check whether the number entered by the user is a palindrome or not. Can you help her by sugges ng the appropriate type of statement she should use to do so? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 4. Raghav has taken two variables in Python IDLE for performing mathema cal opera ons on them. Now, he wants to assign a value to them. Which type of operator should he use to do so? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. Geeta wants to insert a long comment in a Python program but she does not know which character to use. Can you help her to iden fy the character and how to use it? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 6. Rohan wants to manipulate the value of a variable each me when he runs the program. But while crea ng a variable, he was making a mistake in the naming conven on of the created variable. Can you help him by sugges ng appropriate rules while naming variables? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 7. Sohan is a li le bit confused about Rela onal and Logical operators. Can you help him by explaining the concept of these operators in brief? ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... PM Publishers Pvt. Ltd. 165
Find the Errors in the Following Codes Here, some codes are given. You have to iden fy errors in each block of code and rewrite the code a er correc on in the given boxes. a. #Assigning values a==4 b=6 c=8 sum=a+b+c Print (“The value of sum is:”) b. # Enter values using input() func on a= input(int(Enter the value of a:”)) b= input(int(Enter the value of b:”)) diff = a-b print(“The difference value of variable a and variable b is:” diff) c. # Two different data type a = “478” b = 456 print(\"Data type of variable a:\",type(a)) print(\"Data type of variable b:”, type(b)) #Perform Type Cas ng b = int(b) print(\"Data type of variable b a er Type Cas ng:\",type(b)) sum = a + b print(\"Value of variable sum:\", sum) print(\"Data type of the variable sum:\",type(sum)) d. number = int(input(\"Enter any number:\")) if number/2 = 0: print(\" Entered number is even\") else: print(\"Entered number is odd\") e. first_num = int(\"Enter first number:\") second_num = int(\"Enter second number:\") if(first_num // second_num=0): print(first_num,\"is divisible by\", second_num) else: print(first_num,\"is not divisible by\", second_num) Artificial Intelligence - 9 166
Lab Activity Operator Based Problems 1. Write a program to print remainder and quo ent a er dividing one integer with another. 2. Write a program to print conversion of weight from kilogram to grams. 3. Write a program to calculate and print the Simple and Compound Interest. 4. Write a program to evaluate (a+b)², where value of a=5 and b=3. 5. Write a program to find the perimeter of the following objects: a. Square b. Rectangle c. Triangle 6. Write a program to convert the temperature from Fahrenheit to Celsius. C= (F− 32) × 5/9 Selection Based Problems 1. Write a program to check whether the given number is posi ve or not. 2. Write a program to check whether the given number is fully divisible by 5 or not. 3. Write a program to check whether the given number is odd or even. 4. Write a program to input 5 numbers from the user and check whether their sum is greater than 480 or not. 5. Write a program to print ranks as per the condi on below: if Marks >=90, print “Rank 1” if 90< Marks >=80, print “Rank 2” if 80< Marks >=70, print “Rank 3” if 70< Marks >=60, print “Rank 4” if below 60, print “Work Hard” 6. Write a program to print the names of days of week based on given number (i.e. 1 for Sunday, 2 for Monday...). 7. Write a program to input 2 numbers from the user and print the smaller one. 8. Write a program to check that if a person’s age is greater than or equal to 18, then print “You are eligible for vote”, otherwise print “You are not eligible for vote”. Iteration Based Problems 1. Write a program to print the coun ng from 1 to 20. 2. Write a program to print the sum of all natural ll the N number (N is an integer number) 1+2+3+4…….N 3. Write a program to print the table of any given number. 4. Write a program to print the sum of all digits of given number. For example, if the user inputs 158, then the sum will be (1+5+8)=14. 5. Write a program to print the Fibonacci series given below: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 PM Publishers Pvt. Ltd. 167
String and List Based Problems 1. Write a program to print all the elements of any list. 2. Write a program to add any value to a given list by specific index posi on. 3. Write a program to remove any element of a list by entering index. 4. Write a program to print the number of elements which exist in a list. 5. Write a program to print the sum of all elements of any list. 6. Write a program to perform the following opera ons on the given string: “Python is an interpreted, high-level and general-purpose programming language.” a) Find the length of the string. b) Find the word “and” and replace it with symbol “&”. c) Join the string with the text “It has a simple syntax similar to the English language.” 7. Write a program to perform the following opera ons on the given list: [‘Orange’, ‘Mango’, ‘Papaya’, ‘Apple’, ‘Grapes’] a) Remove “Papaya” and add “Guava” at the same posi on. b) Sort the list in ascending order. d) Add the “Cherry, Banana, Coconut” to the list. Project Work 1. Create a simple calculator that can perform opera ons like addi on, subtraction, mul plica on and division between two values depending upon the user choice. 2. Create a program that can perform opera ons like lowercase, capitalize, length, spli ng, joining and replace on a string upon the user choice. 3. 50 students appear in an examina on consis ng of a total of 5 subjects, with each subject having maximum marks of 100. Convert an algorithm into a flowchart and create a program in Python to calculate and print the percentage marks obtained by each student, along with his/her roll number and name. Algorithm Flowchart Step 1: Start NO YES Step 2: Add a variable Count and initialize it to zero Step 3: Read the input data like roll number, name, and Step 4: marks obtained by the student Add the marks obtained by the student in various subjects Step 5: Calculate the percentage by dividing Total marks by 5 Step 6: Write the output data like roll number, name and percentage of marks obtained on the printer Step 7: Count is incremented by one after processing the data for each student. Step 8: At the decision step, the value of Count is compared with 50. If the value is less than 50, the steps within the process loop are repeated. If the value of Count becomes equal to 50, the process will stop. Step 9: Stop Artificial Intelligence - 9 168
AI RELATED FIELDS The Blockchain Technology The blockchain is a decentralized ledger of all the transac ons across a P2P (peer-to-peer) network. Using this technology, par cipants can confirm transac ons without the need of a central cer fying authority like banks. Its applica ons include fund transfer, se ng trades, vo ng and many other uses. Blockchain Technology Uses Benefits TRANSPARENCY AND TRACKING DIGITAL CURRENCY FINANCE IoT DATA STORAGE SIMPLER AND FASTER REDUCED COSTS INCREASED TRUST ONLINE VOTING GOVERNANCE HEALTHCARE INSURANCE Working of Blockchain Technology Someone The requested The network of VALIDATION requests a transac on is nodes validates the MAY INCLUDE transac on broadcasted to a P2P transac on and the CONTRACTS network consis ng of user’s status using CRYPTOCURRENCY computers, known as known algorithm OTHER RECORDS nodes The transac on The new block is then Once verified, the transac on is complete added to the exis ng is combined with other blockchain, in a way that is transac ons to create a new permanent and unalterable block of data for the ledger Cryptocurrency Cryptocurrency is a medium of exchange, created and stored electronically in blockchain, using encryp on techniques to control the crea on of monetary units and to verify the transfer of funds. The best example of cryptocurrency is Bitcoin. PM Publishers Pvt. Ltd. 169
Internet of Things (IoT) Imagine that your car can talk to your house. Your car might tell your house that you are coming back from school and instruct it to turn on the lights and switch on the AC; it might also tell your refrigerator to cool up your juice. We've read and seen such things in science fiction but now all this is possible by the concept called Internet of Things or IoT. Internet of things (IoT) is the network of things that are connected together and pass useful information to each other with the help of the Internet. The Internet of Things (IoT) connects sensors/devices such as refrigerators and ACs to the Internet and uses software to connect them to our daily lives. All that you need to make this network of things is a Wi-Fi connection, things such as refrigerator, car, washing machine, and AC with Internet connecting facility and the software which enables this network connection. Users can access the data or control individual objects using web or mobile apps. Working of IoT Sensors Sensors connected to the objects may gather, receive, transmit, and share data about the objects with other devices online. Sometimes we use sensors/devices because multiple sensors can be bundled together, or sensors can be part of a device that does more than just sense things. For example, your phone is a device that has multiple sensors (camera, accelerometer, GPS, etc.), but your phone is not just a sensor. Connectivity The sensors or devices can be connected to the cloud for processing. The connectivity is done through a variety of methods, including cellular, satellite, Wi-Fi, Bluetooth, or connecting directly to the Internet. Artificial Intelligence - 9 170
Data Processing Once the data gets to the cloud, software performs some kind of processing on it. This could be very simple, such as checking that the temperature reading is within an acceptable range. Or it could also be very complex, such as using computer vision on video to identify objects (such as intruders in your house). User Interface The information is made useful to the end-user in some way. This could be via an alert to the user (email, text, notification, etc). For example, a text alert when the temperature is too high in the children's room. Also, users might have an interface that allows them to proactively check in on the system. For example, a user might want to check the video feeds in his/her house via a phone app or a web browser. However, the user may also be able to remotely adjust the temperature of the room AC via an app on his/her phone. Some actions are performed automatically. Rather than waiting for you to adjust the temperature, the system could do it automatically via predefined rules. And rather than just call you to alert you of an intruder, the IoT system could also automatically notify the relevant authorities. Real World Usage of IoT Smart Home New home builders and existing homeowners are integrating features that automate a wide variety of tasks and enhance the overall at-home environment. Wouldn't you love if you could switch on air conditioning before reaching home or switch off lights even after you have left home or unlock the doors to friends for temporary access even when you are not at home? Don't be surprised, companies are building products to make your life simpler and convenient by using IoT. Smart home has become the revolutionary ladder of success in the residential spaces, and it is predicted that smart homes will become as common as smartphones. PM Publishers Pvt. Ltd. 171
Connected Cars A connected car is a car that is equipped with Internet access. This allows the car to share Internet access with other devices both inside as well as outside the vehicle. A connected car is able to optimize its own operation, maintenance as well as comfort of passengers using onboard sensors and Internet connectivity. Most large auto makers are working on connected car solutions. Major brands such as Tesla, BMW, Apple, and Google are working on bringing the next revolution in automobiles to improve your safety, security, and performance in today’s vehicles. Smart Cities Smart city is another powerful application of IoT, generating curiosity among world's population. Smart surveillance, automated transportation, smarter energy management systems, water distribution, urban security and environmental monitoring are all examples of Internet of things application for smart cities. IoT will solve major problems faced by the people living in cities such as pollution, traffic congestion, and shortage of energy supplies. For example, by installing sensors and using web applications, citizens can find free available parking slots across the city. Healthcare Research shows application of IoT in healthcare will be massive in coming years. IoT in healthcare is aimed at empowering people to live healthier lives by wearing connected devices. When someone in the family gets sick, you want to give them the highest level of care. With the smart thermometer, you can do just that. This super smart heat sensor can be interfaced with your phone through the sensor and synced up with the mobile app. With the app, you can log in and keep track of their temperature, and even their symptoms. So, IoT can also be referred as a revolutionary technology which can make our life easier, more comfortable and more interesting. Artificial Intelligence - 9 172
Know About Robotics We have always been taught that computer works on instruc ons, aids in doing complex calcula ons and serves many other purposes by performing various other tasks. The idea of inven on of technology came into existence with the inten on to make people's lives more easier and comfortable. One such inven on that has revolu onized the en re world is Robo cs. Robotics The word robo cs was derived from the word robot. Robotics is the combination of engineering and science that includes mechanical engineering, electrical engineering, computer science and others. Robotics deals with the design, construction, operation, and use of computer systems for their control and information processing. What image comes to your mind when you hear the word ‘robot’? A metallic body which mimics human behaviour. Precisely, “Robot is an electro-mechanical device, which senses its environment, processes it and decides what actions must be performed under the given conditions. It takes the decision by itself and reacts to its environment without manual interactions.” Difference Between a Computer and a Robot Computer is a simple general-purpose device that performs arithme c or logical opera ons. On the other hand, Robot is a mechanical or virtual ar ficial agent that carries out physical ac vi es like household chores, which may include making your bed, folding laundry, washing dishes or sweeping the floor. Not only this, but robot is being used in businesses, healthcare and many other fields. Need of Robotics Robotics is the branch of science focused on learning and creating robots or machines that make our lives easier. It is being used in different fields for different purposes: $ In healthcare, doctors use robotics to perform surgeries to save lives. $ Automobiles industry uses it to build cars, it is also being used in many aspects of manufacturing to help increase productivity and efficiency. $ Even in the military, robotics is applied in many of its areas. Military drones can be used for surveillance, to support operations on the battlefield and to assess danger level with real-time information. $ When applied in education and incorporated in curriculum, it encourages students to design and build their own robots. PM Publishers Pvt. Ltd. 173
Robotics for School Robotics has now become as integrated into everyday life as computers. Many schools have been incorporating subjects such as Technology, Computer Science and Programming/Coding in their school curriculum, demanding attention of the teachers and students at all levels from primary level education to upper secondary school and beyond. In fact after computer labs, robotics labs are becoming an integral part of many schools. What will Students Learn in Robotics? 1. Students will learn how to apply scientific principles to real-life situations. 2. Students will build confidence and practice teamwork through participation in games. 3. Students will have the opportunity to design and build their own robots in class. Their knowledge in science and mathematics will develop through hands-on experience and problem-solving skills. Are Robots Posing Threat to Future Employment? After learning so much about Robotics, the first thing that comes to our mind is the impact of robots on future employment. Yes, robots will do much of the work humans do today, impacting the human workforce and the type of work humans do. But that doesn't mean that there won't be any work left for humans. Jobs that require creativity, emotional intelligence and social skills are unlikely to be filled by robots any time soon. As we rely more and more on mechanized systems and automation, we will require more people with technical skills to maintain, replace, update and fix these systems and hardware. Useful Online Links You can get more information about Robotics from the links given below: $ education.lego.com Mindstorms EV3 $ roboticsinschool.com EDBOT $ jayrobotix.co.in ROBOX $ robotshop.com Robot Construction Kits $ indiastemfoundation.org STEM education initiative $ www.rs-india.org Robotics Society of India $ www.indiafirstrobotics.com IndiaFIRST Robotics Academy $ www.robogenius.in RoboGenius Academy Artificial Intelligence - 9 174
Raspberry Pi What image comes to your mind when you hear the word 'Raspberry Pi'? A red color sweet flavored delicious fruit used in salads, puddings, cakes, tarts, and other desserts. Raspberry Pi is a series of small single board computers developed in the United Kingdom by Raspberry Pi foundation in 2012. Its main motive was to promote the basics of programming and software development to school children especially in developing countries. The Raspberry Pi follows the tradition of denominating IT companies after fruit’s name i.e. Apple, Blackberry, etc. whereas Pi is an abbreviation for 'Python Interpreter', as Python is considered to be Raspberry Pi's main programming language. However, those with little or no Python experience can opt for Scratch, which is a block based programming language. It is a low cost, credit card sized full-fledged minicomputer which possesses the same capability of doing work as of computer that enables people of all ages to explore computing. How Do I Get Started With the Raspberry Pi? Raspberry Pi itself is just a small board. You'll also need a power supply, a monitor or TV, an HDMI cable to connect the monitor, a mouse and a keyboard. Once you've plugged in all the cables, the easiest way for new users to run the Pi is to download the NOOBS (New Out of Box Software) installer. Once the download is complete, follow the instructions to install an Operating System (Raspbian) on the Pi. The look and feel of Raspbian is like any desktop computer. The OS, which is constantly being improved, recently had a graphical overhaul and includes an optimized web browser, an office suite, programming tools, educational games, and other software. The official website of Raspberry Pi (www.raspberrypi.org) contains lot of resources, books, magazines and projects for educators and students to aid in enhancing teachers’ skills and unleashing creativity among students. Some of these are:- For Teachers and Educators: Code Club and Teach Computing provide resources, lesson plans and training programmes for teachers and educators to teach computer to students. For Competitions and Events: Astro Pi and Coolest projects are platforms where people create experiments that run on Raspberry Pi computers. Volunteer-led Club and Raspberry Jams: Through these free creative clubs, students can interact with others at meet ups around the world and can also join and learn together on the Raspberry Pi. Besides these, there is also fun project site with step-by-step project guide for many projects like Blender, HTML/CSS, Python, Scratch and many more. PM Publishers Pvt. Ltd. 175
PROJECT WORK A. Tic-Tac-Toe (Based on Data Domain) In your leisure me, you must have played ‘Noughts and Crosses’ game in your notebook many mes. This game can engage the a en on of learners of any age. Now, you can play and enjoy this game online. Game Introduc on: Tic-Tac-Toe is a two-player game that is played on a 3x3 grid. Tradi onally, it was played with paper and pencil. In this game, each player takes turns to mark X and O on the available spaces in the grid. To win the game, a player must place three of their marks in a horizontal, ver cal, or diagonal row as shown in the figures. If all 9 squares are filled and neither player has 3 in a row, it is considered a e. 12345678 How to Play Tic-Tac-Toe Online? To play this game online, go to the web browser and type the following URL in the address bar: h ps://gametable.org/games/ c-tac-toe/ and press Enter. You will get the following screen: By playing this game online, you will learn how an expert Ar ficial Intelligence (AI) system will play a perfect game. Choose either One or Two Player op on and select the difficulty level. Enjoy your game and share your experience. ..................................................................................................................................................... ..................................................................................................................................................... ..................................................................................................................................................... ..................................................................................................................................................... ..................................................................................................................................................... Artificial Intelligence - 9 176
B. What will be the most difficult challenge for autonomous vehicles? Prepare a project report with pictures in 200 words. C. You have learnt a lot about how smart devices are helpful in achieving Sustainable Development Goals. Now, write an ar cle in 200 words about what kind of efforts should you make to achieve at least 5 Sustainable Development Goals. D. Prepare a presenta on on the topic: Innova ons of Ar ficial Intelligence ll 2020. E. Prepare a presenta on of at least 10 slides on the topic: Smart Devices used in Smart Hospitals and Smart Schools. F. Colab, offered by Google, is a free environment to implement AI algorithms using Python without any virtual setup. Using Google Chrome, you can code online and run the program to see the output. To do so, you will need to have a Gmail account. Try this applica on to run your Python codes and share your experience in 200 words. G. AutoDraw is an AI-enabled tool based on the domain of Computer Vision in which a machine can recognise the pa ern of your drawing object and map it with a matching image with the most visual resemblance. This tool shows various op ons to make a predic on about the drawing objects. To use this applica on, enter the following URL in the address bar of your web browser: h ps://autodraw.com Now, you should select AutoDraw icon from the toolbar on the le . This icon ac vates the AI element of the tool. Now, ask the students to draw any shape and let the AI algorithm detect and predict the possible drawings similar to it. The predic ons will appear in the topmost row labelled Do you mean as shown in the figure. Drawn by the user Predicted by AutoDraw A er looking at the predic ons and analysing how accurate the machine is, visualize an image in your mind (for example: a monument, vehicle, thing, etc.) and then start drawing it roughly. No ce the step at which the machine is able to predict the image. Once the correct image comes on the screen, observe the lines of symmetry in it. Now, prepare a presenta on in which all slides contain different figures that show symmetrical pa erns and lines of symmetry. H. Prepare a presenta on on the topic: Ethical Issues which Exist in AI Systems. PM Publishers Pvt. Ltd. 177
ADDITIONAL KNOWLEDGE Viva Voce Q1: Define Artificial Intelligence. Ans: Artificial Intelligence is a branch of Computer Science which is a study of how the human brain thinks, learns, decides and works, when it tries to solve problems. In simple terms, Artificial Intelligence refers to the ability of machines or computer programs to carry out certain tasks that require human beings to use their intelligence. Q2: What do you understand by Linguistic Intelligence? Ans: Linguistic Intelligence refers to one’s ability to use, comprehend, speak and write verbal and written language. It is important in interpersonal communication. Q3: How will you differentiate human intelligence from Artificial Intelligence? Ans: Human intelligence is based on cognitive behavior whereas Artificial Intelligence uses models to mimic human behavior. Q4: What do you understand by the term Artificial General Intelligence? Ans: Artificial General Intelligence can be defined as the ability of systems to perform any intellectual task with efficiency like a human. These systems are hard to develop because replication of the human brain is theoretically possible but not practicable as of now. Q5: “In the present scenario, all AI systems are weak.” Comment. Ans: Yes, all AI systems which are available today are weak because they pretend to be intelligent but are not intelligent in reality. Q6: What is the role of AI systems in business? Ans: Nowadays, most of the companies use a biometric system for managing attendance of employees effectively and efficiently. Biometric system is an Artificial Intelligence application that collects data on facial and demographic characteristics. Q7: What is the role of sensors in smart devices? Ans: All the smart devices installed in a smart building are connected wirelessly to the Internet. These devices have sensors and software that allow them to communicate with other devices. With the help of sensors, the devices collect data about the way they are used and about the environment around them. Q8: What do you understand by the term ‘Sustainable Development’? Ans: Sustainable Development is the development that satisfies the needs of the present without compromising the capacity of future generations, guaranteeing the balance between economic growth, care for the environment and social well-being. Artificial Intelligence - 9 178
Q9: What do you understand by the third wave of AI? Ans: The third wave of AI is also known as Perception AI. Today, Artificial Intelligence (AI) Q10: helps us in shopping, provides suggestions on e-commerce websites, connects us with Ans: our friends on social media and much more. In simple words, we can say that we have Q11: begun to witness the third wave of AI or we are living in the era of the third wave. Ans: Q12: Name the first computer-controlled autonomous vehicle which was built in 1979. Ans: Q13: Stanford Cart. Ans: Q14: What do you understand by the term ‘AI ethics’? Ans: The term ‘AI ethics’ refers to a set of rules and principles related to AI systems. Q15: Name the loop which is considered as an extension of the recommendation and Ans: automation loops. Q16: Prediction loop Ans: Name the organization which is responsible for the development of the first intelligent Q17: personal assistant in 2003. Ans: Q18: Defense Advanced Research Projects Agency (DARPA) Ans: Q19: Write any two adoption concerns related to AI systems. Ans: a) Job loss is the major concern across the world due to adoption of automation systems in various sectors. b) The adoption of AI systems could increase income inequality across the world. Define the following terms: a) Data Acquisition b) Data Exploration a) Data Acquisition: Data Acquisition or Data Gathering refers to a process of identifying and gathering all data required for an AI project. b) Data Exploration: Data Exploration refers to a process of understanding the nature of data in terms of quality, characteristics, etc. that we have to work with. What do you understand by the term ‘Problem Scoping’? Problem Scoping is the initial stage of the AI project life cycle. The term ‘Problem Scoping’ refers to a process of framing a problem in such a way that you will have a vision to solve it. In general, it involves a series of steps to narrow down to a problem statement from a broad theme. Define System Map. What is the role of System Maps while solving a problem? A system map is basically a tool that helps us in making decisions and actions in complex situations. It helps us in formulating the solution for achieving the goal of our project. Define the term ‘Data Visualisation.’ Data visualisation refers to a process of representing data in graphical format using various visualisation tools. Name the two major approaches that are used in Artificial intelligent systems. The two major approaches that are used in Artificial intelligent systems are: a) Rule-based Approach b) Learning-based Approach PM Publishers Pvt. Ltd. 179
Q20: What is the role of an Inference engine in an expert system? Ans: The inference engine seeks the desired information and relationships from the knowledge base to provide the desired course of action in the way a human expert would. Q21: What is the major drawback of learning-based approach systems? Ans: The major drawback of learning based approach systems is the frequent training which is required with new data and data-driven insights. Q22: Explain decision tree in short. Ans: A decision tree is a graph in which the flow begins from the root node and ends with an appropriate decision/output made on the leaf nodes. In order to solve decision problems, data gathering and analysis is one of the necessary stages of decision support systems development with the use of artificial intelligence. Q23: “The capability of machine learning systems to process large chunks of data is considered as a big disadvantage.” Why? Ans: Because larger the amount of data, larger will be the processing time. Q24: Define the term ‘Deep learning.’ Ans: Deep learning or deep neural learning is a subset of machine learning techniques which is inspired by the structure and function of a brain and is capable of learning by example. Q25: What do you understand by classification and clustering methods in the context of AI systems? Ans: In AI models, classification methods/algorithms are used to classify the given datasets on the basis of rules given to it whereas clustering method is used to find the similarities and differences among the discrete datasets. Q26: Define fault tolerance capacity of neural networks in your own words. Ans: Fault tolerance is the capacity of any network to continue its operation even if a significant part of the network is lost or missing. It is superior in neural network because it is able to distribute the encoded information throughout the network. Q27: What is the difference between a program and a programming? Ans: A set of instructions is called a program whereas programming is an art of writing instructions to tell a computer what to do. Q28: What do you understand by the term ‘Object Oriented Programming’? Ans: Object-oriented programming technique is a style or technique of programming which is used to encapsulate code within objects. The concept of OOPs is a major feature of Python. Q29: What is the full form of IDLE? Ans: IDLE is an acronym of Integrated Development and Learning Environment. Q30: What do you understand by the word ‘variable’ in context of Python programming language? Ans: Variables are the building blocks of a program. A memory location of is used to store Artificial Intelligence - 9 180
data created in the main memory of a computer is called a variable. These locations are created and identified by the given name while executing a program. Using variables, values are stored and manipulated to produce the desired results. Q31: What is data type? Ans: A data type is an attribute that tells the computer what kind of data a variable can have. The concept of data type is mostly used in those programming languages where the type of variable is known at compile time. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Q32: What is the main difference between a list and a tuple? Ans: List contains a list of elements separated by comma and enclosed within square brackets [ ]. We can change or modify the values of a list, i.e. it is mutable or changeable. On the other hand, tuple contains a group of elements separated by comma and enclosed in parentheses ( ). We cannot change or modify the values of a tuple, i.e. it is immutable. Q33: Define Relational Operators in short. Ans: Relational operator refers to those operators which determine the relationship between two operands. These operators are also known as Comparison Operators because they compare the value of variables and determine the relationship based on comparison. If the comparison is true, the relational expression results into the Boolean value True and in case of false, the relational expression results into the Boolean value False. Q34: What do you understand by Selection Statements? Ans: The selection statement refers to those statements whose execution depends on the specified condition. These statements transfer the flow of the program to the specific location on the basis of conditional expression outcome. These statements are mainly used for decision making as each decision involves the choice between two alternatives i.e., Yes or No. Q35: Define Flowchart. Ans: A flowchart is the pictorial representation of the flow of steps or a procedure to solve a problem. Q36: Define membership operator in Python. Ans: The in operator is a membership operator which is used to check whether the given value lies in sequence or not. The result of this operator is true if it is found in the specified sequence, otherwise it returns false as a result. PM Publishers Pvt. Ltd. 181
Popular Python IDEs IDE stands for Integrated Development Environment. It is a development environment for writing Python programs and testing them. There are several Online and System based Python IDEs which are available to us. You can choose the best IDE as per your need. Let’s know about some popular IDEs. Online IDE Platforms IDLE: This is a cross-platform, open-source, lightweight and simple-to-use IDE, so you can build simple projects such as web browser game automation, basic web scraping applications, and office automation. Link: https://www.python.org/shell/ PROGRAMIZ: It is another online platform used to create, debug and compile Python programs. Link: https://www.programiz.com/python-programming/online-compiler/ TUTORIALSPOINT: It is also one of the most popular online IDE platforms. Link: https://www.tutorialspoint.com/execute_python_online.php Artificial Intelligence - 9 182
System IDE Platform PyCharm: It is an IDE for professional developers created by JetBrains company. PyCharm provides all major features that a good IDE should provide: code completion, code inspections, error highlighting and fixes, and debugging. Link: https://www.jetbrains.com/pycharm/ Spyder: It is an open-source IDE usually used for scientific development. It has some great features such as autocompletion, debugging and iPython shell. Link: https://www.spyder-ide.org/ Sublime Text 3: It is a popular code editor that supports many languages including Python. It's fast, highly customizable, has a huge community and has basic built-in support for Python when you install it. Link: https://www.sublimetext.com/3 Visual Studio Code: Visual Studio Code (VS Code) is a free and open- source IDE created by Microsoft that can be used for Python development. It is lightweight and packed with powerful features. Link: https://code.visualstudio.com/ Atom: Atom is an open-source code editor developed by GitHub that can be used for Python development. Like Sublime Text, Atom is highly customizable. Link: https://atom.io/ Jupyter Notebook: It has a lightweight interface. It is a web- based application that allows a user to create open source document that combine live-code with narrative text, equations and visualizations. Link: https://jupyter.org/install.html Pydev: PyDev IDE is a Python IDE for Eclipse. This is also one of the best IDE for creating Python applications. Link: https://www.pydev.org/ Thonny: It is a Python dedicated IDE that comes with Python 3 built-in. Once you install it, you can start writing Python code. Thonny is intended for beginners. Link: https://thonny.org/ PM Publishers Pvt. Ltd. 183
Applications of Python Business Web Applications Applications Education Game Development Software Scientific and Development Numeric Calculations 1. Web Applica ons: Python has a lot of frameworks such as Django, Flask and a number of libraries that can aid in developing secure and scalable web applica ons. 2. Game Development: Python is also used in the development of interac ve games. It has some amazing libraries such as Pygame and PyOpenGL which help you in building wonderful games. 3. Scien fic and Numeric Calcula ons: Python’s popularity has also reached scien sts and researchers who use it for doing complex and scien fic calcula ons. There are many libraries available for scien fic and numeric calcula ons. Some of these are SciPy, Pandas, Ipython and NumPy. 4. So ware Development: Python is mostly used as a support language for building control and management in so ware development. It also facilitates mul ple stages of so ware development like management, control, and tes ng. 5. Educa on: Python is also used in the field of educa on due to its simplicity and demand. Python programming has a huge scope of applica ons in educa on as it is a great language to teach in schools or even learn on your own. 6. Business Applica ons: Even the business world is not le behind to u lize the benefits of Python. A key role is played by Python in the building of e-commerce websites, which is very relevant in the current market demand. Artificial Intelligence - 9 184
Python in Linux Python comes pre-installed on most Linux distributions like Ubuntu. If Python does not come pre-installed in some old version of Ubuntu, you can easily install it. Installing Python Python comes in three versions: Version 1.0, Version 2.0 and Version 3.0. In this example, we are using Ubuntu 18.04, in which Python version 3.6 is pre-installed. Let us check. Updating your System You can update the system so that you can download the updated software packages. 1. Open Ubuntu and press Ctrl + Alt + T keys simultaneously on the keyboard to open the Terminal. 2. Type sudo apt-get update after the $ sign. 2 3. Press the Enter key. You will be prompted for your password. 4 4. Type the password and press Enter key again. The updating process will begin. It may take some time. After updating, the prompt will appear again to accept the next command. Installing Python 1. Type sudo apt-get install python3.6 1 after the $ sign. 2. Press the Enter key. You will be prompted for your password. 3. Type the password and press Enter key again. As you can see in the screenshot above, Python 3.6 is already installed in Ubuntu 18.04 as mentioned above. Running Python 1. Type python3 after the $ sign. 1 2. Press the Enter key. You will get a python prompt (>>>). Let’s enter a command “Welcome to Python” at the prompt. 1. Type print (“Welcome to Python”) after the python prompt. Make sure to include the brackets and 1 double quotes (\" \"). 2. Press the Enter key. PM Publishers Pvt. Ltd. 185
If you have entered the command correctly, you should see this: Welcome to Python >>> The prompt (>>>) should reappear to tell you that it is ready to accept more commands. In the above program the word print is a type of Python command called a function, and it displays whatever is inside the quotes on the screen. Great! You’ve just created your first Python program in Linux. Exiting from Python After working in Python, you can exit from Python and return to Ubuntu prompt. 1. Type exit() after the python prompt. 1 2. Press the Enter key. Ubuntu prompts appears. Integrated Development and Learning Environment (IDLE) Python IDLE is a graphical program for writing Python programs and testing them. It is very easy and user-friendly. You can start writing Python code with IDLE. It is simple and has nice syntax highlighting ability. Installing Python IDLE 1. Type sudo apt-get install idle-python3.6 1 after the $ sign. 2. Press the Enter key. You will be prompted for your password. 3. Type the password and press Enter key. The downloading and installation process of the software package begins. After installation, the prompt will appear again to accept the next command. Running Python IDLE After installing, you can open Python IDLE in Ubuntu 18.04. 1. Click on Show Applications icon. 2 Apps List screen will appear. 3 2. Type idle in the Search bar. 3. Click on IDLE icon. The Python shell will appear. Prompt Now, you can use IDLE to enter a Python command at the prompt. Artificial Intelligence - 9 186
Python Practice Code Now, you are fully aware of Python’s syntax and control structures. Let’s practice some more to strengthen your concepts and enhance your programming skills. 1. # swap values using third variable x=10 y=20 print(\"value of x before swapping: \",x) print(\"value of y before swapping: \",y) z=x x=y y=z print(\"value of x after swapping: \",x) print(\"value of y after swapping: \",y) Output value of x before swapping: 10 value of y before swapping: 20 value of x after swapping: 20 value of y after swapping: 10 2. # Calculate the Average Speed TD=float(input(\"Enter the Total Distance in KM : \")) TT=int(input(\"Enter the Total Time in Hour : \")) AS=float(TD/TT) print(\"Average speed is : \",AS,\"KM/Hour\") Output Enter the Total Distance in KM : 120 Enter the Total Time in Hour : 2 Average speed is : 60.0 KM/Hour 3. # Calculate the Kinetic Energy ( 1 mv2 ) 2 m=float(input(\"Enter the Mass Value : \")) v=int(input(\"Enter the velocity : \")) Ke=(m*(v**2))/2 print(\"Kinetic Energy is : \",Ke) Output Enter the Mass Value : 120 Enter the velocity : 2 Kinetic Energy is : 240.0 PM Publishers Pvt. Ltd. 187
4. # Program to check whether the given Alphabet is a Vowel or a Consonant alpha=input(\"Enter any Alphabet: \") if(alpha==\"a\" or alpha==\"e\" or alpha==\"i\" or alpha==\"o\" or alpha==\"u\"): print(\"it is a Vowel: \",alpha) else: print(\"it is a Consonant: \",alpha) Output Enter any Alphabet: e it is a Vowel: e 5. # Calculate Profit and Loss CP=float(input(\"Enter the Cost price: \")) SP=float(input(\"Enter the Selling price: \")) PL=float(SP-CP) if(PL>0): print(\"Gross Profit: \",PL) else: Output print(\"Gross Loss: \",abs(PL)) Enter the Cost price: 120 Enter the Selling price: 150 Gross Profit: 30.0 6. # Program to print table of any given Number num=int(input(\"Enter number for print table \")) i=1 while i<=10: Output Enter number for print table 5 res=num*i 5x1=5 print(num,\" x \",i,\" = \",res) 5 x 2 = 10 i+=1 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50 Artificial Intelligence - 9 188
7. #Print the pattern. Output ******* i=j=k=1 * while i <= 6: * * print(\"*\", end = \" \") * i+=1 * print()# for new line * while j <= 6: ******* print(\"*\") j+=1 while k <= 6: print(\"*\", end = \" \") k+=1 8. # Program to print string into pattern. name=“AKASH” Output x = “” A for i in name: AK AKA x+=i AKAS print(x) AKASH 9. # Program to check whether the Number is Prime or not num=int(input(“Enter any integer Number: ”)) count=0 i=1 while num>=i: if(num%i==0): count=count+1 i+=1 if(count<=2): print(“Number is Prime”) else: print(“Number is not Prime”) Output Enter any integer Number: 13 Number is Prime PM Publishers Pvt. Ltd. 189
10. # Print sum and average of given list list1=[10,20.5,30,40,50] length=len(list1) # Total no. of elements sum=0 for i in list1: sum+=i avg=float(sum/length) print(\"Sum of all elements= \", sum) print(\"Average of all elements= \",avg) Output Sum of all elements= 150.5 Average of all elements= 30.1 11. # Code for find and replace in string txt=input(\"Enter your text : \") find=input(\"Replacing text : \") replace=input(\"Replaced with : \") New_txt=txt.replace(find, replace) print(New_txt) Output Enter your text : My Name is Akash Replacing text : My Replaced with : Your Your Name is Akash 12. # Code to reverse the elements of list. OS= ['Windows', 'macOS', 'Linux'] print('Given sequence:', OS) OS.reverse() print('Reversed sequence:', OS) Output Given sequence: ['Windows', 'macOS', 'Linux'] Reversed sequence: ['Linux', 'macOS', 'Windows'] Artificial Intelligence - 9 190
AI EXPERIMENTS Game-1: Akinator: (Domain - Data) This game is based on guessing theme. It will ask you some series of ques ons and will try to guess what fic onal or real-life character, object, or animal you are thinking of. Click on the link given below to play and enjoy this magical game: h ps://en.akinator.com/ Game-2: Teachable Machine: (Domain - Computer Vision) Teachable Machine is a web tool that makes it fast and easy to create machine learning models for your projects which require no coding. Using this tool, you can train a model to recognize your images, sounds, and poses, then instantly test it out and export your model. Let’s click on the link given below to play and enjoy this game: h ps://teachablemachine.withgoogle.com/v1/ Game-3: A.I. Duet (Domain - Data) This game is an example of how machine learning can inspire people to be crea ve in new ways. Play some notes and the computer will respond to your melody. Let’s click on the link given below to play and enjoy this game: h ps://experiments.withgoogle.com/ai/ai- duet/view/ PM Publishers Pvt. Ltd. 191
Game-4: Semi-Conductor (Domain - Computer Vision) This AI-based experiment lets you conduct your own orchestra through your browser. It uses machine learning library that works in the browser to map out your movements through your webcam. You can move your arms to change the tempo, volume, and instrumenta on of a piece of music. Let’s click on the link given below to play and enjoy this game: h ps://semiconductor.withgoogle.com/ Game-5: Quick Draw (Neural Network) This game is built with machine learning. It lets you draw a shape or an object, and uses a neural network Ar ficial Intelligence to guess what the drawing represents. The more you play with it, the more it will learn. Let’s click on the link given below to play and enjoy this game: h ps://quickdraw.withgoogle.com/ Game-6: Thing Translator (Domain - Computer Artificial Intelligence - 9 Vision) This game lets you take a picture of something to hear how to say it in a different language. It’s just one example of what you can make using Google’s machine learning API (Applica on Programming Interface), without needing to dive into the details of machine learning. Let’s click on the link given below to play and enjoy this game: h ps://thing-translator.appspot.com/ 192
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192