Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore AI ebook

AI ebook

Published by Priyanshu Sah, 2022-07-16 13:28:46

Description: AI ebook

Search

Read the Text Version

Step 8: Take the second paper and draw the le er ‘R’ again randomly as done in steps 3 and 4, as shown in the figure. (You can take any color to fill the cells or boxes.) 1 21 2 2 32 3 3 43 4 4 54 5 5 65 6 6 76 7 7 87 8 8 98 9 9 10 9 10 12 23 34 Step 9: Cut the strips as done previously in step 5. 45 56 67 78 89 9 10 Step 10: Arrange the strips as done in step 6. 3 1 22 3 44 5 5 66 7 7 88 9 9 10 PM Publishers Pvt. Ltd. 101

Step 11: Take values 1 or 0 as done in step 7. 1 22 3 0111110 0100010 3 44 5 0100010 0100110 5 66 7 0111100 0111100 7 88 9 0100110 0100011 9 10 0100001 Step 12: Now take both le ers’ values and add them in a sequence as shown. 1 R0 1 1 1 1 1 0 0100010 0100010 2ⁿ R 0 1 1 1 1 1 0 0100010 0100010 0Sum Value 2 2 2 2 2 0 0200020 0200020 0100010 0111100 0110000 0100110 0111100 0111100 0200120 0222200 0221100 0111000 0101100 0100111 0100110 0100011 0100001 0211110 0201111 0200112 Artificial Intelligence - 9 102

1 0222220 2 Step 13: Now take the sum value of the first and 2 0200020 3 second le er and place its value in table cells on 3 0200020 4 the third paper as shown in figure. 4 0200120 5 5 0222200 6 6 0221100 7 7 0211110 8 8 0201111 9 9 0 2 0 0 1 1 2 10 1 0222220 2 Step 14: Fill any color where the table cell values 2 0200020 3 have ‘1’ or ‘2’ value and leave those cells empty 3 0200020 4 whose value is ‘0’ as shown in figure. 4 0200120 5 5 0222200 6 Here, you can see that the output is similar to 6 0221100 7 the le er ‘R’. 7 0211110 8 8 0201111 9 9 0 2 0 0 1 1 2 10 Now, you have to make an intelligent model which can recognize whether an alphabet wri en by you is similar to the data trained or not. Also, train the model with the datasets of the same alphabet that you used in the above scenario but take different shapes of boxes. PM Publishers Pvt. Ltd. 103

3 NEURAL NETWORK Introduction In the previous unit, you have learnt an overview of deep learning and machine learning models. As you know, deep learning is a subfield of machine learning which is also a subfield of AI. In simple words, deep learning is a field of AI that is based on learning and improving on its own by examining computer algorithms. Neural Network is an instance of deep learning technology. Deep learning is a crucial technology behind the development of self-driving cars that requires innumerable images and thousands of hours of video footage. The concept of deep learning underwent first transforma on in the 1980s. In the present day and age, it has become popular due to two prime reasons: a) Data: Deep learning requires huge amounts of labelled data. b) Complex applica ons: Deep learning has solved increasingly complicated applica ons with increasing accuracy over me. Deep learning algorithms are commonly used for processing and classifying data without extrac ng features manually, on the basis of learning-based approach. As you know, systems based on learning approach are con nuously updated and more powerful with new user inputs and informa on whereas rule-based systems are sta c. One of the major advantages of learning-based approach is that if a model is trained with par cular type of datasets i.e. ABC and the machine designs the algorithm around it, in such a case, modifica ons in the model take place on their own. The modifica on depends upon the changes occurring in that par cular dataset. Let us understand with the help of a simple example. Suppose you have a dataset which contains 50 images of novels and children’s books. The cover page of each book and novel is different. Now, you can do the work of labelling i.e. keep all the images of novels in the Novel category and rest of them will be kept in the Children’s books category. A er labelling, you can train an AI model with this dataset and design an algorithm in such a way that it can easily find out the difference between a novel and a children’s book according to their quality or features and can predict the label of any image which is fed to it as a novel or a children’s book. A er dataset training, tes ng data plays an important role in these systems because some mes the dataset entered by the user does not match with the par cular dataset for which the model has to be trained. In such a case, the model adapts to the features on which it has been trained and makes appropriate predic ons. Thus, a learning-based system is also known as an adap ve intelligent system because it can learn on its own by adap ng to the new data which is flowing in. Artificial Intelligence - 9 104

Machine learning algorithms are o en categorized as: 1. Supervised Learning: This algorithm consists of a target/outcome variable (or dependent variable) which is to be predicted from a given set of predictors (independent variables). Using these sets of variables, we generate a func on that maps inputs to desired outputs. The training process con nues un l the model achieves the desired level of accuracy on the training data. Examples of Supervised Learning: Classifica on and Regression. 2. Unsupervised Learning: In this algorithm, we do not have any target or outcome variable to predict/es mate. It is used for clustering popula on in different groups, which is widely used for segmen ng customers in different groups for specific interven on. Example of Unsupervised Learning: Clustering. 3. Reinforcement Learning: Using this algorithm, the machine is trained to make specific decisions. It works this way: the machine is exposed to an environment where it trains itself con nually using trial and error. This machine learns from past experience and tries to capture the best possible knowledge to make accurate decisions. Example of Reinforcement Learning: Markov Decision Process (Discussion beyond the scope of chapter). The methods used for iden fying, processing and classifying data in deep learning systems are Classifica on, Regression and Clustering. Both techniques, Classifica on and Regression come under the category of Supervised Learning and Clustering comes under the category of Unsupervised Learning. Classifica on works with predefined datasets in which elements are assigned, Regression problems are based on con nuous data, while Clustering works on discrete datasets used to make clusters on the basis of similari es and differences between elements of datasets. Let’s know about them in detail: a) Classifica on: This is a type of Supervised Learning. In general, Classifica on refers to a process of classifying something according to their features. Similarly, in AI models, classifica on methods/algorithms are used to classify the given dataset on the basis of rules given to it. Let us understand with the help of a simple example. Suppose you have a dataset consis ng of 100 images of pears and pomegranates. Now, you want to train a model to recognize whether an image is of a pear or a pomegranate. To do this, you must train the model with discrete datasets along with their labels. A er training with a par cular dataset, your model will be ready to classify images on the basis of the labels and predict the correct label for test data. b) Regression: Like Classifica on, Regression also falls under the REGRESSION family of Supervised Learning that works with con nuous data. This algorithm predicts the output values based on input features from the data fed in the system. It builds a model on the features of training data and uses the model to predict the value for new data. For example, if we want to predict the result of a student’s final assessment, we can use marks of his/her past assessment as training data. PM Publishers Pvt. Ltd. 105

c) Clustering: In the previous unit, we have learnt about CLUSTERING iden fica on of trends and pa erns in the available data through visual representa on. In AI systems, clustering, a type of Unsupervised Learning, is used for this purpose. This method is a very simple method as it finds similari es and differences among the discrete dataset. One of the major advantages of this method is that the machine generates its own algorithms to differen ate amongst the dataset to achieve the pre-decided course of ac on. Using this method, a system is able to understand the dataset on its own and perform clustering on the basis of observed similari es and differences. Neural Network The term ‘neural network’ has been revolu onized a er the recogni on that the computa onal power of the human brain is completely different from the conven onal digital computer. In 1944, two researchers Warren McCulloch and Walter Pi s made a simple neural network on the basis of the func oning of neurons in the human nervous system. The first Ar ficial Neural Network (ANN), called Perceptron, was invented in 1958 by psychologist Frank Rosenbla on the basis of following aspects: • Knowledge is acquired by the human brain from its environment through a learning process. • Iden fica on of objects on the basis of acquired knowledge. The other researchers used similar ANNs to study human cogni on. A procedure of processing informa on to acquire and understand knowledge by thoughts, experiences, and senses is called human cogni on. In 1975, Allen Newell and Herbert A. Simon found that there are some similari es in the func onal structures and processing procedures of human beings and computers. According to them, both human beings and computers are special systems which contain systema c modules of input, output, processing, and storage, which process the input informa on and perform the tasks of feature extrac on and pa ern recogni on for different objects on the basis of acquired knowledge. An Ar ficial Neural Network (ANN) can be defined as a compu ng system made up of simple, highly interconnected processing elements which process informa on by their dynamic state response to external inputs. ANNs are made up of mul ple nodes which imitate biological neurons of the human brain. The neurons are connected by links to communicate or interact with each other. These nodes can take input and perform simple opera ons on the input data. The processing result of these opera ons is passed to other neurons. These networks are able to adapt dynamic changes of the input and predict the best possible output without any need to redesign the output criteria. In simple terms, a neural network is essen ally a way of organizing machine learning algorithms to perform a certain task. A neural network has great poten al to solve problems for which the dataset is very large, like images, pa erns, etc. In simple words, the larger neural networks are able to produce be er results with larger amounts of input data as compared to tradi onal machine learning algorithms. DO YOU KNOW ? Ar ficial Neural Networks (ANNs) have mul ple applica ons across various sectors and industries: 1. E-commerce companies use ANNs for personalized product recommenda ons for customers. 2. ANNs help in the development of chatbots which use NLP to interact with human users. Artificial Intelligence - 9 106

Architecture of Neural Networks In general, a neural network is a technique to build an intelligent applica on that simulates the way a human brain processes, learns and remembers informa on. Before understanding the basic architecture of neural networks, it is important to learn about the func oning of neurons in the human nervous system. As you know, the brain is the most complex organ in the human body which works on the basis of neurons. A typical neuron is made up of four parts which are as follows: a) Dendrites: They are tree-like projec ons of the cell which make connec on to other cells and are responsible for receiving the informa on from other neurons they are connected to. b) Axon: Axon is the tail-like projec on of the cell soma through which neurons are able to send informa on. c) Soma: Soma, also known as the cell body, is the main part of the cell. It is responsible to process informa on which is sent by the dendrites. d) Synapses: Synapses refer to the connec on between the axon of one neuron to other neuron dendrites. The axon of a neuron sends an impulse to the synapse of another neuron. The received impulse is then sent to the nucleus through dendrites. The cell body or soma performs an ac va on func on on the impulse received and then gives it to the output axon which passes the same to the next neuron in the system. Similarly, a neural network is the complex structure in AI systems which is made up of ar ficial neurons. This network is able to take mul ple inputs to produce a single and meaningful output. In general, a neural network consists of an input and output layer with one or mul ple hidden layers within. The basic architecture of a neural network is shown in the figure given below: Input Hidden Output layer layer layer Input #1 Output Input #2 Input #3 Input #4 Here, input layer nodes receive only one value or input at one me and send it to all the nodes available in the hidden layer. The hidden layer nodes perform specific func ons on the incoming data and pass the processed informa on to the output layer node. You should remember that no processing would take place at the input layer due to its passive nature. DO YOU KNOW ? The Chinese Internet service provider Baidu has developed an AI-based text-to-speech system ‘Deep Voice’ which can imitate a person’s voice and create synthe c human voices using deep neural networks. PM Publishers Pvt. Ltd. 107

The similari es between the components of biological neural network and Ar ficial Neural Network are as follows: S. No Biological Neural Network Ar ficial Neural Network 1. Dendrites Input 2. Soma Node 3. Synapse Interconnec on link between two nodes 4. Axon Output Have you thought about how processing takes place in a hidden layer? Let us discuss. Each node available in the hidden layer has its own machine learning algorithm. The execu on of the algorithm starts when it receives data from the input layer. A er that, processed informa on is then passed to the subsequent hidden layer if available. It is important to note that a neural network may contain one or more than one hidden layer. The number of hidden layers depends upon the complexity of a func on for which it was configured. In the last stage, the last hidden layer passes the processed informa on to the node of the output layer. Similar to input layer, the output layer also cannot make any modifica on in the acquired informa on. The concept of neural network has been widely used in pa ern recogni on and classifica on tasks due to the following features: a) ANNs are capable of learning complex non-linear input-output rela onships. b) The training procedures of ANNs are sequen al. c) ANNs can easily adjust to a new environment without using any preset instruc ons. d) ANNs can easily work with large amounts of datasets. e) The learning capacity will keep enhancing/con nuing throughout the life of the system. Advantages of Artificial Neural Network Ar ficial Neural Networks play an important role while developing AI systems using deep learning techniques. The main advantages of Ar ficial Neural Network are as follows: a) Fault tolerance: Fault tolerance is the capacity of any network to con nue its opera on even when a significant part of the network is lost or missing. It is superior in neural network because it is able to distribute the encoded informa on throughout the network. b) Parallel opera ons: Ar ficial Neural Networks have great poten al to perform mul ple jobs at one me due to parallel architecture. The parallel architecture also allows ANNs to process large chunks of data in a very organized way. c) Faster processing: ANNs are made up of a large number of compu ng elements, each of which can process informa on on its own. Thus, ANNs are able to process large amounts of informa on simultaneously. d) Can work with inadequate knowledge: A er ANN training, the informa on may produce output even with inadequate data. The loss of performance here depends upon the importance of missing data. Artificial Intelligence - 9 108

e) Power of interconnec ons: Ar ficial Neural Networks are able to add new informa on without destroying the old informa on, using the power of interconnec ons. Disadvantages of Artificial Neural Network Some disadvantages of Ar ficial Neural Network are as follows: a) Hardware dependence: Ar ficial Neural Networks require processors with parallel processing power, in accordance with their structure. For this reason, the realiza on of the equipment is dependent. b) Unexplained behavior of the network: This is the most important problem of ANN. When ANN produces a probing solu on, it does not give a clue as to why and how. This reduces trust in the network. c) No assurance of proper network structure: In ANNs, no specific rules are men oned to determine the structure of Ar ficial Neural Networks. The appropriate network structure is achieved through experience, and trial and error. d) Difficulty of showing the problem to the network: ANNs work with numerical informa on. Problems have to be translated into numerical values before being introduced to ANN. The display mechanism to be determined here will directly influence the performance of the network. This depends on the user's ability. e) Computa onal expensive: As you know, a neural network is made up of a large number of compu ng elements. Thus, it is an expensive approach. Worksheet 1: Based on Neural Network and Human Nervous System In this session, you have learnt few similari es between neural networks and the human nervous system. Now, write at least three differences between them. ...................................................................................................................................................... ...................................................................................................................................................... ...................................................................................................................................................... Attributes of Artificial Neural Networks Neural networks are capable of applying various skills to large sets of data in the same way as humans do. The powerful a ributes of an Ar ficial Neural Network are as follows: a) Adap ve learning: Like humans, the basic founda on of neural networks is based on previous knowledge. For example, various so ware use adap ve learning to teach maths, language and arts. b) Self-organiza on: The term ‘Self-organiza on’ in ANNs refers to the ability of clustering and classifying large amounts of data which makes it capable of organizing the complicated visual problems posed by medical image analysis. PM Publishers Pvt. Ltd. 109

c) Real- me opera on: Ar ficial Neural Networks are able to provide answers in real me. Self-driving cars and drone naviga on are few examples of real me opera ons performed by ANNs. d) Ability to predict: The ability of predic ng outcomes on the basis of models is one of the most powerful characteris cs of ANNs. Due to this feature, ANNs are widely used in various fields like medical, meteorological department, etc. e) Fault tolerance: Neural network exhibits fault tolerance capacity. When significant parts of a network are lost or missing, the en re network would not fail. This ability is especially useful in space explora on, where the failure of electronic devices is always a possibility. Applications of Artificial Neural Network The Ar ficial Neural Network has great poten al to perform complex opera ons. Due to this reason, ANNs are widely used in various applica ons as: a) Signature verifica on: Neural networks are widely used to iden fy signatures which is one of the most useful ways to authorize and authen cate a person in legal and financial transac ons. In signature verifica on applica ons, neural networks are used to extract features or the geometrical feature set represen ng the signature. With these extracted features, we have to train the neural networks using an efficient and appropriate algorithm of neural networks. This trained neural network will recognize the genuine or forged signature in the verifica on stage. b) Route detec on: Neural networks are widely used for detec ng naviga on routes from the source point to the des na on point. Google Maps, a global posi oning system provides useful direc ons and real- me traffic informa on to millions of users. This informa on is updated constantly to mirror the changes in an ever-changing world. c) Market segmenta on: Target marke ng involves breaking a market into segments on the basis of customer taste and preferences. It is one of the biggest applica ons of neural networks because these networks are able to perform segmenta on among the customers on the basis of factors like economic status, loca on, purchasing pa erns and a tudes towards a product. d) Speech recogni on: You must have seen Google voice assistant, a speech recogni on system in your smartphones. This system makes you capable of working with apps in a user-friendly way because it takes less me to speak rather than type. Ar ficial Neural Network plays an important role in the field of smart voice systems because these systems consider individual words spoken by different people as an input speech signal and features extracted by the model are then used to train the ANN to recognize human speech. e) Monitoring robo c factories: Nowadays, automated and robo c factories are being monitored by ANNs in the form of controlling machinery, making adjustments in temperature se ng, etc. f) Forecas ng: Forecas ng is the main necessity of every business but it is not a simple approach. It involves various types of complexi es and risks. For example, predic ng stock prices is a complex problem with a lot of underlying factors. For this work, ANNs are be er than tradi onal forecas ng models because of their ability to model and extract unseen features and rela onships without any restric ons on input data. Artificial Intelligence - 9 110

Ar ficial Neural Networks are currently being used to solve many complex problems and their demand is increasing with me due to their ability of learning from faults. Thus, neural networks are being preferred more for complex problem-solving. Worksheet 2: Based on Information Processing With the help of the Internet or your teacher, describe at least four main differences between the human brain and today’s computers in terms of informa on processing. For your help, a clue box is also given below: a. Parallel fashion or sequen al fashion b. Slow or fast c. Distributed or single d. Connec vity changes Activity Section Human Neural Network Let’s understand the process of neural network through an ac vity of crea ng ‘Human Neural Network’. The main purpose of organizing this ac vity is to make the students understand how neural network processes and classifies data without extrac ng features manually, on the basis of learning-based approach. Here, we take 20 students from a class and divide them in groups of four layers i.e. 7 in Input Layer, 6 in Hidden Layer 1, 6 in Hidden Layer 2 and 1 in Output Layer. Output Layer Input Hidden Hidden Layer Layer 1 Layer 2 Rules and Instruc ons of the Game: 1. No discussion would be allowed and each layer must be at a distance from the other layers. 2. Each student of Input Layer would be allo ed 6 chits, 4 chits would be allo ed to each student of Hidden Layer 1 and 2 chits would be allo ed to each student of Hidden Layer 2. 3. An image (or input) would be shown to every student of Input Layer only and based upon it, each of them has to instantly write 6 different words that describe the image on 6 different chits. PM Publishers Pvt. Ltd. 111

4. A er this, they need to pass on one chit to each of the nodes of Hidden Layer 1 i.e. 1 chit will be given from each student of Input Layer to each student of Hidden Layer 1. 5. Therefore, each student of Hidden Layer 1 will receive 7 chits from 7 different input students (nodes). They have to take a good look at the chits and write down 4 different words on 4 different chits allo ed to them. They can either use the same words as the Input Layer students did, or they can make their own interpreta on. 6. Now, these 4 chits are to be given randomly to any 4 nodes of Hidden Layer 2 i.e. each student (node) of Hidden Layer 1 can choose any 4 students (nodes) out of the 6 nodes of Hidden Layer 2, and give one’s chits. 7. Now, students of Hidden Layer 2 would follow the same procedure as students of Hidden Layer 1 and write down 2 different words on 2 different chits (as per the allotment) and pass it on to the Output Layer. 8. The student of Output Layer node will get 12 chits in total and he/she has to interpret all the words, summarize them and guess which image was shown to the Input Layer. 9. Finally, the Output Layer will present the summary to everyone. If it matches the image given to the Input Layer, then they win, else they lose. For instance, the Input Layer sees this image, now the 7 students would write different words in the chits allo ed to them such as hut, sun, tree, river, etc. and by following the instruc ons of the game men oned above, finally the Output Layer would be able to figure out that it’s a scenery. The crux of this game is to deduce the conclusion that Neural Network is based on learning and improving on its own. In a Nutshell 1. Deep learning is a field of AI that is based on learning and improving on its own by examining computer algorithms. Neural Network is an instance of deep learning technology. 2. Deep learning algorithms are commonly used for processing and classifying data without extrac ng features manually, on the basis of learning-based approach. 3. Machine Learning Algorithms are o en categorized as: Supervised, Unsupervised and Reinforcement Learning. 4. The three methods or techniques used for iden fying, processing and classifying data in deep learning systems are Classifica on, Regression and Clustering. 5. In AI models, Classifica on methods/algorithms are used to classify the given datasets on the basis of rules given to it. 6. Regression works with con nuous data. This algorithm predicts the output values based on input features from the data fed in the system. 7. Clustering method is a very simple method as it finds similari es and differences among the discrete dataset. One of the major advantages of this method is that the machine generates its own algorithms to differen ate amongst the dataset to achieve the pre-decided course of ac on. Artificial Intelligence - 9 112

8. In 1944, two researchers Warren McCulloch and Walter Pi s made a simple neural network on the basis of the func oning of neurons in the human nervous system. 9. An Ar ficial Neural Network (ANN) can be defined as a compu ng system made up of simple, highly interconnected processing elements which process informa on by their dynamic state response to external inputs. 10. The larger neural networks are able to produce be er results with larger amounts of input data as compared to tradi onal machine learning algorithms. 11. The fault tolerance capacity of Ar ficial Neural Networks is superior because neural networks are able to distribute the encoded informa on throughout the network. 12. Ar ficial Neural Networks are able to add new informa on without destroying the old informa on, using the power of interconnec ons. 13. The ability of predic ng outcomes on the basis of models is one of the most powerful characteris cs of ANNs. Due to this feature, ANNs are widely used in various fields like medical, meteorological department, etc. Multiple Choice Questions 1. Which of the following algorithms are commonly used for processing and classifying data without extrac ng features manually, on the basis of a learning-based approach? a) Deep Learning b) Knowledge-based c) Both of these d) None of these 2. Which of the following statements is not true about systems based on learning approach? a) These systems are updated con nuously. b) These systems are more powerful than rule-based systems. c) These systems are dynamic in nature. d) These systems are sta c in nature. 3. The first Ar ficial Neural Network (ANN) called ................................ was invented in 1958 by psychologist Frank Rosenbla . a) Percep on b) Perspec ve c) Perceptron d) Perceive 4. A ................................ is a technique to build an intelligent applica on that simulates the way a human brain processes, learns and remembers informa on. a) Neural Network b) Natural Language Genera on c) Natural Language Processing d) Computer Vision 5. A neural network is the complex structure in AI systems which is made up of ar ficial ...................................... . a) brain b) neurons c) nucleus d) axon Answers 1. a 2. d 3. c 4. a 5. b PM Publishers Pvt. Ltd. 113

Fill in the Blanks 1. .............................. requires huge amounts of labelled data. 2. .............................. -based system is also known as an adap ve intelligent system because it can learn on its own by adap ng to the new data which is flowing in. 3. One of the major advantages of .............................. method is that the machine generates its own algorithms to differen ate amongst the dataset to achieve the pre-decided course of ac on. 4. ANNs are made up of .............................. nodes which imitate biological neurons of the human brain. 5. In general, a neural network consists of an input and output layer with one or mul ple .............................. layers within. Answers 2. Learning 3. clustering 5. hidden 1. Deep learning 4. mul ple Evaluate Yourself State T for True or F for False statements. 1. Machine learning is a subfield of deep learning which is also a subfield of AI. 2. Neural Network is an instance of deep learning technology. 3. The first Ar ficial Neural Network (ANN) called Perceptron was invented in 1979 by psychologist Frank Rosenbla . 4. A neural network has no poten al to solve problems for which the dataset is very large like images, pa erns, etc. 5. The output layer of a neural network can make modifica ons in the acquired informa on. 6. In ANNs, no specific rules are men oned to determine the structure of Ar ficial Neural Networks. 7. The ability of predic ng outcomes on the basis of models is one of the most powerful characteris cs of ANNs. 8. In AI models, classifica on methods/algorithms are used to classify the given dataset on the basis of rules given to it. Answers 1. F 2. T 3. F 4. F 5. F 6. T 7. T 8. T Artificial Intelligence - 9 114

Writing Subjective Responses 1. What is the main difference between Classifica on, Regression and Clustering techniques? ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 2. Write any two similari es between Biological Neural Networks and Ar ficial Neural Networks. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. Describe the basic architecture of a Neural Network in brief. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 4. Write a short note on ‘Perceptron’. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. “Nowadays, systems based on neural networks are being widely used in the healthcare industry.” Comment. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... Short Answer Questions 1. Define the term ‘Neural Network’. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... PM Publishers Pvt. Ltd. 115

2. What do you understand by the term ‘Classifica on’? ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. “The concept of neural network has been widely used in pa ern recogni on and classifica on”. Explain. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 4. Write any two advantages of Ar ficial Neural Networks. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. “Neural network plays an important role in AI systems.” Comment. Also, write any two applica ons of neural networks. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... Long Answer Questions 1. “Deep learning algorithms are commonly used for processing and classifying images without extrac ng features manually, on the basis of a learning-based approach.” How? ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 2. Explain the characteris cs of ANNs in brief. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. List some disadvantages of Ar ficial Neural Network. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... Artificial Intelligence - 9 116

4. Describe the working procedure of a neural network in brief. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 5. “Neural networks are being preferred more for complex problem-solving.” Comment. ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... Application Based Questions 1. Rahul’s teacher gave him an assignment to prepare a presenta on on the topic: “Learning- based approach is more powerful than rule-based approach”. While preparing the assignment, he needs to add some points explaining the statement. Can you help him in preparing the assignment by sugges ng some points? ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 2. Rishabh has heard a statement in his class that “The fault tolerance capacity of Ar ficial Neural Networks is great.” Now, he is very curious to know about the term ‘fault tolerance’. Can you help him by sugges ng an appropriate defini on of fault tolerance in terms of compu ng? ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... 3. Vaibhav wants to know about the difference between Supervised and Unsupervised Learning. Can you help him by sugges ng at least two differences between these two? ...................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... ....................................................................................................................................................... PM Publishers Pvt. Ltd. 117

4 CODING IN PYTHON Introduction to Programming You know that being a machine, a computer understands the instructions given to it in its language, that is, Machine Language. Let us understand it in the following manner: If someone asks you to add 8 + 5, you will quickly give the answer 13, but if the same question is asked to the computer, it will not be able to answer it. This is because your instruction is not understood by the computer. It can only understand the instructions given in computer language. The set of instructions written in a language which a computer can understand is called a program. In computing, a program is implemented by a computer to solve any problem and get the results. Basically, a computer program involves three steps: 1. Algorithm : Creating an algorithm 2. Flowchart : Making a flowchart 3. Program : Converting a flowchart into a program Algorithm Dear children, in your day-to-day life, whenever you have to solve any problem or do any work, you have to follow a step-by-step procedure so that you can get the best results for it. Let us understand it by an example. What steps would you follow to buy a new shirt? The possible steps are as follows: 1. Take your money and go to the garments shop in the market. 2. Tell the shopkeeper which color and style of shirt you want. 3. Choose and finalize the desired shirt. 4. Pay money to the shopkeeper. 5. Take the balance amount (if any) from the shopkeeper. Finally, you get the desired result, i.e., purchase of a new shirt. In the same way, a computer also solves its problems in a step-by-step procedure to give you accurate results. All the software programs are written in special languages called computer languages. They follow a specific pattern of steps to achieve specific objectives. Before writing a program, we have to determine the objective and then we start developing a pattern of steps. An Algorithm is a step-by-step procedure to solve any particular task, such as a mathematical or a logical problem. It is defined as a sequence of instructions that when executed in a specified sequence, leads to desirable results. DO YOU KNOW ? Python has become the first choice of tech giants such as Google, Instagram and Spo fy. Artificial Intelligence - 9 118

Characteristics of a Good Algorithm If your teacher asked you to solve a Math problem and you are not familiar with the steps involved in solving the problem, you will not be able to solve it. You need to know the sequence of steps for solving the Math problem. The same principle also applies to writing computer programs. To write an effective computer program, it is necessary to write every instruction in the correct sequence. In order to qualify as an algorithm, a sequence of instructions must possess the following characteristics: 1. Each instruction should be precise and clear. 2. It should have 0 or more well-defined input steps. 3. It should have 1 or more well-defined output steps. 4. Each step of an algorithm should be well-defined and stated. 5. An algorithm must terminate after a finite number of times. 6. After executing the instructions, the desired results are obtained. Uses of an Algorithm An algorithm tells exactly how to do something step-by-step to reach our goal, to achieve the required output or to accomplish our task. So, an algorithm is used to provide a method of doing things, from our daily life to every other complex problem in the world. Even a simple program of adding, subtracting, and multiplying uses an algorithm. Calculating the speed, path, fuel of a space shuttle is also done by using algorithms. Algorithm is used: ! for finding the shortest or the best path to travel from one location to another. ! for weather forecasting. ! for finding structural patterns in curing diseases. ! for making games like chess that can defeat the best chess players. ! for building smart robots. We sometimes don’t even notice, but knowingly or unknowingly, we execute a lot of programs in our daily life written using algorithms. For example, have you ever noticed the processing done at the server: ! when you check your mail? ! when you post your picture on social media and get likes? ! when you buy some products online and pay for them from home? Advantages of a Good Algorithm 1. Independent of any computer language, so it is very easy to understand. 2. Easy to write and modify. 3. Easy technique to understand the logic. 4. Easy identification of mistakes since every step has its own logical sequence. 5. Can be easily converted into flowcharts and then into computer programs. Disadvantages of an Algorithm 1. It is very time-consuming. 2. Big tasks like branching and looping are difficult to put in algorithm. PM Publishers Pvt. Ltd. 119

EXAMPLES AN ALGORITHM TO ADD ANY TWO NUMBERS: Step 1 : Start Step 2 : Take two numbers Step 3 : Add the two numbers Step 4 : Print the result Step 5 : Stop This is an algorithm to add two numbers. AN ALGORITHM TO FIND THE GREATER NUMBER OF THE TWO: Step 1 : Start Step 2 : Take two numbers Step 3 : Compare these two numbers; if A > B, then go to step 4 or else go to step 6 Step 4 : Print A is greater Step 5 : Stop Step 6 : Print B is greater Step 7 : Go to step 5 This is an algorithm to find the greater number of the two. Flowchart A flowchart is a diagrammatic representation of a problem-solving process, also known as an algorithm. It is called a flowchart as it charts the flow of a program. Herman Goldstine and John von Neumann developed a flowchart (originally a diagram) to plan computer programs. The direction of flow in a flowchart is always from top to bottom or left to right. The process of drawing a flowchart for an algorithm is known as flowcharting. In a flowchart, each operation is represented using specific geometrical symbols. These symbols are connected to each other by arrows to show the operations. Some basic symbols that are used while making a flowchart are as follows: START/STOP BOX It is an oval-shaped symbol that is used at the beginning and at the end of the flowchart. It shows the starting and ending of a flowchart. INPUT/OUTPUT BOX It is a parallelogram-shaped box that is used to indicate the input and output of a program, i.e., the instructions related to the input and getting the result. PROCESSING BOX It is a rectangle-shaped box that is used to show the processing part of the flowchart, like calculation. Artificial Intelligence - 9 120

DECISION BOX It is a rhombus-shaped box that is used to check the conditions, display comparisons, and take the decisions to solve the problems. FLOW LINES These are the arrow lines used to connect the different shapes and show the flow of logic in a flowchart. CONNECTORS It is a circle-shaped symbol that is used to join the parts of a flowchart. Rules for Making a Flowchart There are some rules that should be followed while making a flowchart: 1. While drawing a proper flowchart, all necessary requirements should be listed out in a logical order. 2. The flowchart should be clear, neat, and easy to follow. 3. Only one flow line should be used in conjunction with terminal symbol. 4. The direction of flow, in a flowchart, should be from top to bottom or from left to right. 5. Avoid the intersection of flow lines if you want to make it more effective. 6. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Uses of a Flowchart Flowcharts are used in many industries including entertainment, engineering, physical sciences and computer programming. The purpose of all flowcharts is to communicate how a process works or should work without any technical jargon. Programmers use data flowcharts to identify where the data originated, where it is being altered and where it is stored. These charts are often linear and read left to right. Advantages of a Flowchart 1. A flowchart helps in analyzing the problem in a more effective way. 2. It is a better way of communicating the logic of a system. 3. It acts as a guide during the program development phase. 4. It helps in finding out errors. Disadvantages of a Flowchart 1. A flowchart can be complex when the logic of a program is quite complicated. 2. Drawing a flowchart is a time-consuming task. 3. It is difficult to alter the flowchart. Sometimes, the designer needs to redraw the complete flowchart to change the logic of the flowchart or to alter the flowchart. PM Publishers Pvt. Ltd. 121

EXAMPLES FLOWCHART 1. CONVERTING AN ALGORITHM INTO A FLOWCHART Start Wake up in the morning ALGORITHM Go to washroom Step 1: Start Brush your teeth Step 2: Wake up in the morning Step 3: Go to washroom Take a bath Step 4: Brush your teeth Wear your school uniform Step 5: Take a bath Step 6: Wear your school uniform Have your breakfast Step 7: Have your breakfast Take your tiffin Step 8: Take your tiffin Step 9: Go to your school Go to your school Step 10: Stop Stop 2. CONVERTING AN ALGORITHM INTO A FLOWCHART FOR ADDING TWO NUMBERS ALGORITHM FLOWCHART Start: The beginning Start of a flowchart. Step 1: Start Step 2: Take two numbers Input N1, N2 Input: Give 2 numbers to the computer. Step 3: Add the two numbers Sum = N1 + N2 Processing: Give instruction to calculate. Step 4: Print the result Print Sum Output: The result is displayed. Step 5: Stop Stop Stop: The end of a flowchart. Artificial Intelligence - 9 122

3. CONVERTING AN ALGORITHM INTO A FLOWCHART TO FIND THE AREA OF A RECTANGLE ALGORITHM FLOWCHART Step 1: Start Start Step 2: Take two sides Input A, B Step 3: Calculate the area by multiplying Area = A x B the two sides Step 4: Print the area Print Area Step 5: Stop Stop 4. A STUDENT APPEARS IN AN EXAMINATION CONSISTING OF A TOTAL OF 5 SUBJECTS, WITH EACH SUBJECT HAVING MAXIMUM MARKS OF 100. CONVERT AN ALGORITHM INTO A FLOWCHART TO CALCULATE THE PERCENTAGE OF MARKS AND PRINT IT. ALGORITHM FLOWCHART Step 1: Start Start Step 2: Read the input data like roll Read input data number, name, and marks obtained by the student Add marks of all subjects for Step 3: Add the marks obtained by the giving total marks student in various subjects Step 4: Calculate the percentage by Percentage = dividing the Total marks by 5 Total marks / 5 Step 5: Write the output data like roll Print output data number, name and percentage of marks obtained on the printer Step 6: Stop Stop In this flowchart, it will start, then read the student's record, calculate the percentage of marks obtained by him/her, print one line of output, and finally stop. Program The last step in solving a problem is to convert the flowchart into a program. This can be written in the computer language to get the desired result. There are many computer languages like C++, Java, Python, etc. Now, we are going to learn about Python programming language. PM Publishers Pvt. Ltd. 123

Introduction to Python Python is a high level, structured, open source programming language that supports the development of wide range of applications from simple text processing to world wide web browsers to games. Python was founded by Guido van Rossum in early 1990s. It is named after ‘Monty Python's Flying Circus’, a comedy television show. Python enables you to create programs through coding. Coding (or computer program) helps you to organize your thoughts and express your ideas to create something new in the computer. It empowers you to not only use technology but to create it. Using CodeCombat for Learning Programming Coding has become a buzzword today. It is arguably the most important skill to learn in the 21 Century and needs be to inculcated among students at an early stage. However, there are many challenges in teaching computer programming such as the diversity in students’ ability and aptitude levels, and most importantly the difficulty in motivating students to learn computer programming. To overcome all these obstacles, Gamification has stepped in, which helps the teachers to teach difficult concepts of programming fundamentals to novice students, in order to keep their interest and motivation. Gamification allows you to play and study. Today, we have plenty of online game portals which motivate and capture the interest of students to learn coding. Here, we are using CodeCombat which is a good platform to learn and improve coding skills. For using CodeCombat, click on https://codecombat.com/ and press Enter. The following window will appear. 1 1. Click on Sign Up button. 2 2. Click on Sign up as 124 an Individual. Artificial Intelligence - 9

3 3. Enter your date of 4 birth. 5 4. Click on Continue. 6 5. Enter your email 7 address, username and password. 6. Click on Create Account. You can now play the game. 7. Click on PLAY button to begin your game. 8. Click on the red flag below the hopping yellow arrow. 8 125 PM Publishers Pvt. Ltd.

After clicking on the flag, a pop-up window will appear, consisting of a description of the game, instructions to be followed and the learning outcomes related to programming which will be achieved through this level. 9. Click on PLAY button to proceed. 9 10. Select your character or hero from the list. 10 11. Click on NEXT button. 11 Now, you will get an Inventory screen where you can select the equipment for your hero that would aid in completing the task efficiently for achieving the goal. 12. Click on Equip. 13. Click on Play. 13 12 A window with a set of instructions and procedure to achieve the goal would appear. 14. Click on START LEVEL. 14 Artificial Intelligence - 9 126

A game window will open. The screen would be split in two parts: the code will be typed on the right side of the screen and on the left side, the character or hero selected by you would move according to your instructions. 15. Type your code here. The codes are based 15 on given methods. 16. Click on RUN after typing the codes. 16 Your selected hero or character will perform according to your given codes or instructions on the left side of the screen. 17. Click on DONE. You will get the Victory screen. Congrats!!! You have completed the first level. Now, you can click on 17 Continue if you want to play more... Features of Python Programming The growth and usage of Python are increasing day-by-day due to the following features: 1. Python is easy to use and learn. 2. Python is an open source language and available free of cost at https://www.python.org/downloads/. 3. Python can run equally well on different platforms such as Windows, Linux, Unix and Macintosh. So, it is a portable language. 4. Python can be used for Graphical User Interface (GUI) programming. 5. It is a high level programming language and user-friendly in nature for developers. 6. Programming in Python is fun. It's easier to understand and write coding in Python than any other high-level language. The syntax feels natural. For example: a=2 b=3 sum = a + b print(sum) Even if you have never programmed before, you can easily guess that this program adds two numbers and prints it. 7. Python is an interpreted language that executes the code line-by-line at a time. This makes the debugging process easier. PM Publishers Pvt. Ltd. 127

8. Python supports both procedure-oriented and object-oriented programming. 9. Python is an extensible language, it means that it can be extended to other languages. 10. Programs written in Python are typed dynamically which means that the type of the value is decided at run time. It's not necessary to add semicolon at the end of the statement. Python enforces you to apply proper indentation. These small things can make learning much easier for beginners. Due to these features and variety of applications of Python, many people and organizations prefer this language over other languages. Python Programming Styles Python is a general purpose programming language and supports multiple structure approach. Following paradigms are supported by Python: ! Object-oriented Approach: Python allows the programmer to create classes and objects. ! Procedure-oriented Approach: The code can be grouped into functions in Python as done in procedure-oriented approach. Stepwise execution of tasks is done using functions. ! Imperative: This style is useful for manipulating data structures and producing simple codes. Combination of the above programming paradigms makes the Python language more flexible and easy to use. Therefore, organizations are moving towards this language due to its multiple programming paradigms approach. Installing Python Python comes in three versions: Version 1.0, Version 2.0 and Version 3.0. Many series are available in these versions. In this chapter, we are using version 3.8. Open a browser and go to the official website https://www.python.org/downloads/ and press Enter. The following page will appear in your browser. 1. Click on Download Python. After downloading, install Python. 1 After installing, when you open Python, you will get this window: Prompt This is the Python shell, which is part of Python’s integrated development environment. An Integrated Development and Learning Environment (IDLE) is the most popular graphics-based development environment for Python. It is easy to create, edit and debug a program in this environment. Artificial Intelligence - 9 128

This window is called Interactive mode. The interactive mode screen shows the welcome message with version details and the three greater-than signs (>>>) called the prompt. This is a primary prompt which indicates that interpreter is executing the Python command. There is also a secondary prompt (…) which indicates that interpreter is waiting for the input to complete the statement. All the statements, expressions or commands are written after the primary prompt in the Interactive mode window. Let’s enter a command “Welcome to Python” at the prompt. >>> print(“Welcome to Python”) Make sure to include the double quotes (\" \"). Press Enter key on your keyboard when you have finished typing the line. If you have entered the command correctly, you should see something like this: >>> print(“Welcome to Python”) Welcome to Python >>> The prompt (>>>) should reappear to tell you that the Python shell is ready to accept more commands. In the above program, the word print is a type of Python command called a function, and it prints out whatever is inside the quotes to the screen. Great! You’ve just created your first Python program. Saving Your Program You don’t need to rewrite the same program every time you want to use it. It might be fine to just rewrite short programs, but a large program could contain millions of lines of code. For this reason, we can save our program for future use. The interactive mode is best for small programs and for beginners. But we can't save the commands in interactive mode for future use. For saving a program, you need to open and write a program in another Python shell, called Script mode. 2 1. Open IDLE (Python GUI). 3 2. Click on File menu. 3. Click on New File. PM Publishers Pvt. Ltd. 129

An empty window will appear, with Untitled displayed in the Menu bar. This is another Python shell, which is called Script Mode. Creating, Saving and Running a Program in Script Mode Let’s enter a command “Welcome to Python” in Script mode. 1 1. Type print(“Welcome to Python”) 2. Click on File menu. 2 3. Click on Save. 3 Save As dialog box appears. By default, the file will be saved in Python folder in C: drive, but you can change the location. 4. Type the File name (MyFirstProgram). The file extension of Python is .py. 5. Click on Save. 4 Python will save the program in the specified location. 5 6 The new File name will appear on 7 the Title bar. 6. Click on Run menu. You can also press F5 key to run the program. 7. Click on Run Module. If you’ve entered the command correctly, your saved file should run like this in Interactive mode. Now, if you close the shell window but leave the MyFirstProgram.py window open and then choose Run > Run Module, the Python shell reappears, and your program will run again. Artificial Intelligence - 9 130

Lines and Indentation Python is very particular about program layout, especially regarding lines and indentation. A Python program is made up of one or more physical lines. Each physical line may end with a comment. The text written in the comments are ignored by Python. In Python, the end of a physical line marks the end of most statements. Unlike other languages, you don’t need to terminate Python statements with a semicolon (;). Python uses indentation to express the block structure of a program. An indentation is an empty space at the beginning of a line to signal the start of a new paragraph. Unlike other languages, Python does not use braces or other beginning/end symbols around blocks of statements; indentation is the only way to denote blocks. Character Set Character set is a set of valid characters that a language can recognize. Python uses the traditional ASCII character set. Python version 3 source file can use any Unicode character. A version 2 source file is usually made up of characters from the ASCII set (character codes between 0 and 127). The ASCII character set is a subset of the Unicode character set. Python version 2.7 also recognizes the Unicode character set. Tokens A token is the smallest element of a program that is meaningful to the interpreter. Tokens supported in Python include identifiers, keywords, delimiters, operators and many more. Identifiers A random name made out of letters, digits and underscore (_) to identify a function name, a program name or a memory location (variable or constant) is known as identifier. Python is a case sensitive language as it treats lower and upper case letters differently. Following rules must be followed for creating identifiers: ! Must start with a letter A to Z or a to z or an underscore (_). ! Can be followed by any number of letters, digits (0-9), or underscores. ! Cannot be a reserved word. ! Python does not allow punctuation characters such as @, $ and % within identifiers. ! Class names start with uppercase letter. Valid identifiers: shapeclass shape_1 shape_to_db _var Invalid identifiers: 1shape my var *varnew my@var Keywords Keywords are the reserved words in Python and cannot be used as constant, variable or any other identifier names. All the Python keywords contain lowercase letters only except True, False and None. PM Publishers Pvt. Ltd. 131

Following is the list of Python keywords: True False None and as assert def class continue break else finally elif del except global for if from import raise try or return pass nonlocal in not is lambda Delimiters The following characters and combinations are used by Python as delimiters in expressions, list, dictionary, and various statements: ()[]{} , : . ` =; @ += -= *= /= //= %= &= |= ^= >>= <<= **= The last two rows are the augmented assignment operators, which are delimiters but also perform operations. The following ASCII characters have special meanings as part of other tokens. ' \"#\\ The following ASCII characters are not used in Python. $? Literals The data items that never change their value throughout the program run are called literals. Theoretically, Literal means any number, text or other information that represents a value. Python supports the following literals: Literals Examples String literals :: \"hello\" , '12345' Integer literals :: 0, 1, 2, -1, -2 Long literals :: 89675L Floating-point literals :: 3.14 Complex literals :: 12j Boolean literals :: True or False Special literals :: None Unicode literals :: u\"hello\" List literals :: [5, 6, 7] Artificial Intelligence - 9 132

Operators Operators are the special symbols that carry out arithmetic and logical computations. The values operated by the operator are called operands. Following are the operators used in Python: 1. Arithmetic Operators: Arithmetic operators are used to perform mathematical operations. The various arithmetic operators are given in table below: Operator Meaning Example '+' Addition and concatenation in strings >>> 200+45 245 >>> \"Good\" + \" \"+ \"Morning\" ‘Good Morning’ '-' Subtraction >>> 100-20 80 >>> 80-160 -80 '*' Multiplication and Replication in Strings >>> 4*5 20 >>> ‘python’ *3 ‘pythonpythonpython’ '/' Divide >>> 28/4 7.0 >>> 50/6 8.333333333333334 '%' Modulus/Remainder >>> 67%9 4 '**' Exponentiation >>> 8**2 64 2. Relational Operators or Comparison Operators: These operators are used to compare the values. Following is the list of comparison operators: Operator Meaning Example '>’ Greater than >>> 6>1 True '<’ Less than >>> 90>100 False PM Publishers Pvt. Ltd. >>> 8<9 True >>> 70<54 False 133

>=’ Greater than or equal to >>> 9>=5 '<=’ Less than or equal to True '==’ Equal to >>> 5>=9 '!=’ Not equal to False >>> 1<=2 True >>> 20<=10 False >>> 6==7 False >>> 7==7 True >>> 7!=4 True 3. Logical Operators: Logical operators perform Logical AND, Logical OR and Logical NOT operations. Operator Meaning Example >>> x=False or If any of the operands is true then >>> x=True >>> y=False condition becomes true >>> y=False >>> x or y >>> x or y False and If both the operands are true True >>> x=True then condition becomes true >>> x=True >>> y=False >>> y=True >>>x and y not Reverse the state of operand >>> x and y False True >>> a=True >>> a=False >>> not a >>> not a False True 4. Assignment Operators: These operators are used to assign value to the variables. Following are the list of assignment operators: Operator Meaning Example #Assign the value 30 to x '=' Assign the value from right >>> x=30 #print the value of x side to variable >>> print (x) 30 Artificial Intelligence - 9 134

'+=' Add and assign the value >>> a=12 to the variable >>> a+=2 # a=a+2 >>> print (a) '-=' Subtract and assign the value 14 to the variable >>> a=12 >>> a-=2 # a=a-2 '*=’ Multiply and assign the >>> print (a) value to the variable 10 >>> a=12 '/=' Divide and assign the value >>> a*=2 # a=a*2 to the variable >>> print (a) 24 >>> a=12 >>> a/=2 # a=a/2 >>> print (a) 6.0 Operator Precedence Operator precedence determines the order in which expressions are evaluated, so you can predict the outcome of an expression. It can also determine the overall value of the expression. For example, take the following expression: a = 8 + 6/2. Depending on whether the 8 + 6 expression or the 6/2 expression is evaluated first, the value can end up being 7 or 11. Python follows operator precedence rules for solving the expression as shown in the table. While solving the expression, operators follow Priority Operators Description the table and evaluate according to the priority 1st () parentheses level. Operators on the same line have the same 2nd */% multiplication, division, precedence and are evaluated left to right based modulus on how they appear in the expression itself. 3rd +- addition, subtraction 4th = assignment Now, for the same expression a = 8 + 6 / 2, according to this table, the division is evaluated before addition, so the value will be 11. Comments Comments are very important while writing a program in any language. Python interpreter ignores the text written in the comment. Python supports the following ways to use comments in a program: Single Line Comments Python uses hash (#) symbol for writing a comment for a single line. Example: #This is the start of program This is a single line comment #print hello in python This is a single line comment print (“Hello”) This is a statement PM Publishers Pvt. Ltd. 135

Multi-line Comments Python uses triple quotes ' ' ' or “ “ “ for multi-line comments. Example: “ “ “ This Is An Example Of Multi-line Comments” ” ” # Multi-line Comments Statements Simple and compound are two types of statements in Python source file. Unlike some other languages, Python has no ‘declarations’. It just contains statements. Simple Statement A simple statement lies entirely within a logical line. You do not need to place more than one statement on a single logical line, with a semicolon (;) as the separator. Python recommends one statement per line and makes programs more readable. Some of simple statements are break, continue, etc. Compound Statement A compound statement contains one or more statements and controls their execution. A compound statement has one or more clauses, aligned at the same indentation. Each clause has a header starting with a keyword and ending with a colon (:), followed by a body, which is a sequence of one or more statements. When the body contains multiple statements, also known as a block, these statements are on separate logical lines after the header line, indented four spaces rightward. The block ends when the indentation returns to that of the clause header. Some of compound statements are if, for, while, etc. Data Types Data types are used to define the type of value a data can contain. Data values in Python are known as objects and each object has a type. A type of object determines which operations the object supports. Data types define the way to store the values in memory. Python has built-in data types such as numbers, strings, tuples, lists, dictionaries, and sets. Some of them are discussed in the following section. You can also create user-defined types, known as classes. Numbers The built-in numeric types in Python include integer numbers, floating-point numbers, and complex numbers. Integer/Long Integer Integers are the whole numbers consisting of + or – sign without decimal digits such as 1000, -88, etc. Range of an integer in Python can be from -2147483648 to 2147483647. Long integer has unlimited range subject to available memory. The long integer value is handled by Python automatically. The long integer value can be appended L with value. Example: >>> a=12 # This is an integer value >>> b=4324L # This is a long integer value Artificial Intelligence - 9 136

Float Float data type represents floating point numbers which contain decimal point. For example, 0.5, -4.567, 0.001, etc. are called floating point numbers. These numbers can also be written in scientific notation by using 'e' or 'E' to represent the power of 10. Here 'e' or 'E' represents exponentiation. Example: 4.6×10⁵ is written as 4.6E5. # This is a floating point value Complex A complex number is a number that is written in the form of a+bj or a+bJ. Here, 'a' represents the real part of the number and 'b' represents imaginary part of the number. The suffix 'j' or 'J' indicates square value of -1. The real and imaginary part may contain integers or floats. Example: >>> c=4+5j # This is a complex value Sequence A sequence is an ordered collection of items, indexed by positive integers. The three types of sequence data type available in Python are: Strings, Lists and Tuples. String String is a sequence of characters used to store and represent text-based information. Single and double quotes are used to represent strings in Python. Example: >>> name=”reema” # name stores a string value Lists List contains the list of elements separated by comma and enclosed within square brackets [ ]. Example: >>> list= [10,20,”abc”] >>> #creates list with different types of elements Tuple Tuple is similar to the list. It contains a group of elements that can be of different types. The elements in the tuple are separated by comma and enclosed in parentheses (). Example: >>> tuple1=(10,20,”abc”) >>> #creates tuple with different types of elements Variables Variables are used to store data in the memory. The data can be numbers, text and objects. The data is given a name, so that it can be re-called whenever it is needed. Another way of looking at a variable is that it is like a label for something. For example, to create a variable named rose, we use an equal to sign (=) and then tell Python what information the variable should be the label for. PM Publishers Pvt. Ltd. 137

Here, we create the variable rose and tell Python that it labels the number 100: >>> rose = 100 # here we say that rose labels the number 100 To find out what value a variable labels, enter print in the shell, followed by the variable name in parentheses, like this: >>> print(rose) # here we ask what rose is labeling 100 # here Python prints the result We can also use more than one variable for the same item: >>> rose = 100 >>> flower = rose >>> print(flower) 100 In this example, we’re telling Python that we want the variable flower to label the same thing as rose by using the equal sign between flower and rose. You can also write variables like total_marks: >>> total_marks = 500 >>> print(total_marks) 500 This example shows that we’re talking about 500 marks. Variable names can be made up of letters, numbers, and the underscore character (_), but they cannot start with a number. It also cannot use reserved keywords. Defining Input and Output in Python A program needs to interact with user to complete a desired task which is done through Input- Output facility. Input refers to the data entered by the user of program. Python provides built-in functions for defining input and output. Some of the functions like input() and print() are used for standard input and output operations in Python. The syntax of these functions are as follows: Input in Python Using Input( ) Function The syntax and example of input() function are: Syntax: input([prompt]), where prompt is the string you want to display. Example: >>> num=input(\"enter a number:\") enter a number:23 >>> num '23' #entered value 23 is a string, not a number To convert this into a number we can use int() or float() functions. Example: >>> int('23') 23 #entered value 23 is a number, not a string >>> float('23') 23.0 #entered value 23.0 is a float Artificial Intelligence - 9 138

Output in Python Using Print( ) Function The syntax and example of print() function is as follows: Syntax: print(expression/constant/variable) Print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete) line and then goes to next line for subsequent output(s). To print more than one item on a single line, comma (,) may be used. Example 1: >>> print(\"hello\") hello Example 2: >>> print(3+5) 8 Example 3: >>> print(6*7) 42 Example 4: >>> print(\"class 8 student\") class 8 student Types of Errors Python is an interpreted language which executes the code line-by-line at a time after checking the errors. An error is a bug that prevents a program from executing in correct manner. This makes the debugging process easier. A Python program mainly contains following types of errors: Syntax Errors Every programming language in computer has certain rules and regulations. Syntax error will occur when these rules and regulations of computer language are violated. Example: >>> Print(\"hello\") Syntax Error: invalid syntax # type print in lower case for correct result >>> print(\"hello\") hello Logical Errors These cause the program to behave incorrectly, but they do not usually crash the program. These errors are caused by a mistake in the program’s logic. Example: >>> x = 5.0 >>> y = 7.0 >>> print(x+y/2) # It will give 8.5 as answer Logical Error: invalid logic # put x+y in braces as (x+y) for correct result >>> print((x+y)/2) # It will give 6.0 as answer PM Publishers Pvt. Ltd. 139

Programs in Python Let's go through some simple Python programs to understand this interesting and powerful language properly. Write the program in Script mode (Python shell). Program 1: To take two integers as input and find their sum. Source Code in Script Mode Output in Interactive Mode Program 2: To take length and width of a rectangle as input, and find its perimeter and area. Source Code in Script Mode Output in Interactive Mode Artificial Intelligence - 9 140

Control Structures A program is the set of instructions which are executed in sequential manner. In some situations, we have to change the order of execution of the program based on conditions or repetition of statements until conditions are met. Therefore, control statements are used to control or change the flow of execution. Three basic control structures are: 1. Sequential 2. Conditional 3. Loop Sequential Control Structure: A sequential control structure shows one or more actions following each other in order. Actions include input, process, and output. All actions must be executed, that is, none can be skipped. For example, getting two numbers from the user, calculate their sum and printing them. Conditional Control Structure: A conditional control structure tells the program which action to take, based on a certain condition. Loop Control Structure: The loop control structure enables a program to perform one or more actions repeatedly as long as a certain condition is met. Indentation in Python Python programs get structured through indentation, i.e. code blocks are defined by their indentation. All the statements in conditional and looping statements are structured using indentation rather than using curly braces ({}). This principle makes it easier to read and understand other people's Python code. Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. Conditional Control Structures We have a number of situations, where we may have to change the order of execution of statements based on certain conditions. This involves a kind of decision-making to see whether a particular condition has occurred or not, and then direct the computer to execute certain statements accordingly. When a program breaks the sequential flow and jumps to another part of the code, it is called branching. When the branching is based on a particular condition, it is known as conditional branching. If branching takes place without any decision, it is known as unconditional branching. Python language possesses such decision-making capabilities and supports the following statements known as control or decision-making statements to implement branching. For example: if, if-else, nested if, elif, etc. PM Publishers Pvt. Ltd. 141

The If Statement The if statement is a powerful decision-making statement and is used to control the flow of execution of statements. This statement is used to execute one or more statements depending on whether a condition is True or not. Syntax: condition False if condition: True Body of if Body of if First the condition is tested, if the condition is true then body of if after colon (:) will be executed. Example 1: “Are you older than 50?” and if the answer is yes, respond with “You are too old!” >>> age = 53 Output >>> if age > 50: You are too old! print(”You are too old!”) An if statement is made up of the if keyword, followed by a condition and a colon (:), as in if age > 50:. The lines following the colon must be in a block, and if the answer to the question is yes, the commands in the block will run. Print Group of Programming Statements If the answer to the question is yes, then you can print a group of programming statements under if block. Example 2: The If-else Statement condition False The if...else statement is an extension of the simple if statement. True Body of else Syntax: Body of if if condition: Body of if Artificial Intelligence - 9 else: Body of else The if..else statement evaluates condition and will execute body of if only when condition is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks. 142

Example: Output num = int(input(\"enter any number: \")) enter any number: 8 if num >= 0: Positive or Zero print(\"Positive or Zero\") else: print(\"Negative number\") In the above example, if value of num is greater than or equal to zero, then statement in if block will be executed; otherwise, if the value of num is less than zero, then statement in else block will be executed. If-elif-else Statement When multipath decisions are involved, we can put ifs Test False False together. A multipath decision is a chain of ifs in which Expression the statement associated with each else is an if or elif. Test of if Expression Syntax: if test expression: True of elif Body of if Body of if True elif test expression: Body of elif Body of else Body of elif else: Body of else If the test expression of if statement is False, it checks the test expression of the next elif block and so on. If all the test expressions are False, body of else is executed. Only one block among the several if...elif...else blocks is executed according to the test expression. The if block can have only one else block but it can have multiple elif blocks. Example: marks = int(input(\"Enter your marks: \")) if marks > 90: print(\"Excellent\") elif marks > 75: # first elif print(\"Very Good\") # second elif Output elif marks > 60: # third elif Enter your marks: 78 Very Good print(\"Good\") elif marks > 50: print(\"Need to work harder\") else: print(\"Poor, work very hard to score good marks\") In the above example, if the marks are greater than 90, then the statement following if will get executed; if the marks are greater than 75 but lesser than 90, then statement following first elif will be executed; if the marks are greater than 60 but lesser than 75, then statement following second elif will be executed; if the marks are greater than 50 but lesser than 60, then statement following third elif will be executed; otherwise, if the value of marks is less than 50, statement in else will be executed. PM Publishers Pvt. Ltd. 143

Nested If Statement condition-1 True Nesting is the process of placing the if or if-else or False condition-2 elif statement in another statement. It enables us to make complex decisions based on different inputs. False True Syntax: Statement-3 Statement-2 Statement-1 if condition-1: if condition-2: Statement-n statement-1 else: statement-2 else: statement-3 The logic of execution is, if the condition-1 is false, the statement-3 will be executed; otherwise, it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise, the statement-2 will be evaluated, and then the control is transferred to the statement-n. Example: Output num1 = int(input(\"Enter First Number: \")) Enter First Number: 6 num2 = int(input(\"Enter Second Number: \")) Enter Second Number: 64 num3 = int(input(\"Enter Third Number: \")) Enter Third Number: 33 if num1 > num2: Num2 is greatest: 64 if num1 > num3: print(“Num1 is greatest:”, num1) else: print(“Num3 is greatest:”, num3) else: if num2 > num3: print(“Num2 is greatest:”, num2) else: print(“Num3 is greatest:”, num3) Loop Control Structures Nothing is boring than having to do the same thing again and again. In programming, programmers do not particularly like repeating the same commands. Thankfully, most programming languages have loop option for that problem. Loops cause a section of your program to be repeated a certain number of times. The repetition continues while a condition is true. When the condition becomes false, the loop ends, and the control passes to the statements following the loop. In looping, a sequence of statements is executed until some conditions for the termination of the loop are satisfied. A program loop therefore consists of two segments, one known as body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Artificial Intelligence - 9 144

Python provides two types of looping constructs - For loop and While loop For Loop The for loop is used to repeat a block of statements until there is no item in Object (String, List, Tuple or any other object) in Python. Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation. For each item Syntax: in sequence for variable in Object: Last item Yes Statement 1 reached Statement 2 Body of for loop No ........... Body of for loop Statement n Exit loop Here, 'for' represents the keyword which indicates the beginning of for statement. 'variable' specifies the name of variable that will hold a single element of sequence. 'in' indicates the sequence which comes next. 'object' is the sequence that will be stepped through and 'statement 1', 'statement 2'….so on are the statements that will be executed in each iteration. In Python, if you want to print PM Publishers five times, you could do the following: >>> print(“PM Publishers”) Output: PM Publishers >>> print(“PM Publishers”) Output: PM Publishers >>> print(“PM Publishers”) Output: PM Publishers >>> print(“PM Publishers”) Output: PM Publishers >>> print(“PM Publishers”) Output: PM Publishers But, this is rather time-taking and boring. So, you can use a for loop to reduce the amount of typing and repetition, like this: # Python For Loop - Range Example >>> for x in range(0, 5): print(“PM Publishers”) Output: PM Publishers PM Publishers PM Publishers PM Publishers PM Publishers The range function can be used to create a list of numbers ranging from a starting number up to the number just before the ending number. PM Publishers Pvt. Ltd. 145

Example: Output # Python For Loop - String Example >>> Str_1 = \"PM_PUBLISHERS” Letter is: P >>> for word in Str_1: Letter is: M Letter is: _ print(\"Letter is: \", word) Letter is: P In the above example, we have first assigned “PM_PUBLISHERS” Letter is: U into a variable Str_1. Then we used the for loop to iterate Letter is: B through the string and display individual letters. Letter is: L Letter is: I While Loop Letter is: S Letter is: H Letter is: E Letter is: R Letter is: S The while loop in Python is used to repeat a block of statements for given number of times, until the given condition is False. It starts with the condition, if the condition is True then statements inside the while loop will be executed, otherwise if the given condition is False then it will not be executed. It means, while loop may execute zero or more time. The syntax of while loop is: Syntax: while test_expression: Start Body of while increment/decrement False In Python, the body of the while loop is determined through indentation. Test Expression True In while loop, test expression is checked first. The body of the loop is Body of while entered only if the test_expression evaluates to True. After each iteration Stop the value of loop control variable will increment/decrement and the test expression is checked again. This process continues until the test_expression evaluates to False. Example: # Print PM Publishers 5 times using while loop i=0 Output while i<5: print(\"PM Publishers\") PM Publishers i=i+1 PM Publishers # increments the value of i at each iteration PM Publishers PM Publishers PM Publishers In this example, the while loop will be executed 5 times and prints PM Publishers in a vertical line. While working with while loop, we need to increment the loop control variable we used in test condition; that control variable should be incremented in the body of the loop, otherwise the loop would turn into an indefinite loop. Artificial Intelligence - 9 146

Example: while loop Output #Print the values of a & b using 26 51 a = 25 27 52 b = 50 28 53 while (a < 30) and (b < 70): 29 54 30 55 a=a+1 b=b+1 print(a, b) In the above example, we initialized a variable a with the value 25, and a variable b with the value 50. The loop checks for two conditions using AND operator whether a is less than 30 and whether b is less than 70. As both conditions are True, the complete expression evaluates to True and statements following the loop will get executed. Break Statement Enter Loop Break can be used to unconditionally jump out of the loop. It Test Condition False terminates the execution of the loop. It can be used in while loop and for loop. Break is mostly required, when due to some True external condition, we need to exit from a loop. Syntax: break break Yes Example: No Exit Loop # Break Statement for l in 'Python': Output Remaining Body P of Loop if l == 'h': y break t print(l) The example above prints all letters in string 'Python' before the letter 'h'. This is so because when ‘l’ becomes equal to 'h', the break statement will force the program to exit from the loop. Continue Statement Enter Loop Continue statement is used to tell program to skip the rest of the Test Condition False statements of the current loop block and to move to next iteration of the loop. Loop does not terminate but continues on with the next True iteration. This can also be used with both while and for loop. Yes continue Syntax: continue Output Exit Loop Example: No Remaining Body # Continue Statement P for le in 'Python': y of Loop t if le=='h': o continue n print(le) The example above prints all letters in string 'Python' except the letter 'h'. This is so because when ‘le’ becomes equal to 'h', the if statement will be executed and the continue statement inside it will force the program to skip the following print statement and moves the control back to the top of the loop. PM Publishers Pvt. Ltd. 147

Strings and Lists in Python You have already learnt a short description of strings and lists. As you know, a consecutive sequence of characters which is enclosed in single quotation marks or double quotation marks is known as string. You should always remember that Python strings are immutable i.e., you cannot overwrite the values of string. A list is a standard data type of Python that can store a sequence of values belonging to any data type. Python lists are changeable, i.e, you can overwrite the elements anytime whenever required. Now, you will learn various string and list manipulation techniques. Traversing a String As you know, a string is made up of characters. While programming, sometimes there is a requirement to access only one character at a time from the whole string. In such a situation, you can use a traversing technique. In general, traversing refers to a process of iterating through the elements of a string. In Python, you can traverse a string through the unique index of each character. A unique index refers to the memory location of an element from a Python sequence by its position in that sequence. By default, indexing always starts with zero which means that the index of the first element of the sequence is zero. The index must be an integer because other data types will result in Type Error. Let us understand the concept of indexing with the help of a simple example. >>> name=“Azaryah” # Statement 1 #fetch ‘A’ from the name Azaryah >>> ch=name[0] # Statement 2 >>> ch2=name[-1] # Statement 3 Posi ve Indexing 0 1 23 4 5 6 A z ar y a h -7 -6 -5 -4 -3 -2 -1 Nega ve Indexing The statement 2 fetches the character available at index position 0 i.e. ‘A’ from the variable name which holds a string Azaryah. Python also allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. Here, statement 3 fetches the character ‘h’ from the user defined string “Azaryah.” The concept of traversing is commonly used in loops. Let us understand how to traverse a string in a loop with the help of an example given below: Output >>> str = “PYTHON” P Y >>> for i in str: T print(i) H O N Artificial Intelligence - 9 148

String Operators Concatenation and Replication operators are the basic operators used for concatenating a string or replicating a string in Python. Now, let us learn about membership operators and comparison operators for a string. a) Membership Operators: The membership operators in Python are used to test whether a specified value is available within a sequence or not. The two membership operators used for strings are: In Operator: The in operator evaluates to true if a character or a substring exists in the specified string, otherwise, it evaluates to false. For example, >>> “A” in “Azaryah” # Statement 1 >>> “H” in “Azaryah” # Statement 2 Here, statement 1 evaluates to true because character ‘A’ is available in the string “Azaryah” whereas statement 2 evaluates to false because the letter case of character ‘H’ is different in the defined string. Not in Operator: The working procedure of not in operator is just opposite to the ‘in’ operator. The ‘not in’ operator evaluates to true if a character or a substring does not exist in the specified string, otherwise, it evaluates to false. For example, >>> “H” not in “Azaryah” # Statement 3 Here, statement 3 evaluates to true because character ‘H’ is not available in the string “Azaryah”. b) Comparison Operators: In general, comparison operators are used to draw comparison between two values. In case of strings, comparison operators are used to compare two strings in terms of character by character as per their ASCII values. For example, >>> “a” == “a” # Statement 1 >>> “ABC” == “abc” # Statement 2 Here, statement 1 evaluates to true because both strings are equal whereas statement 2 evaluates to false because the letter case of LHS string is different from the letter case of RHS string. Note: ASCII (American Standard Code for Information Interchange) is a numeric value given to different characters and symbols. Now, let us learn how to compare two strings on the basis of relational operators with the help of an example given below: >>> “ABC” < “ABCD” # Statement 1 >>> “seema” > “seemA” # Statement 2 Here, statement 1 evaluates to true because LHS string is obviously less than RHS string whereas the output of statement 2 is true because both strings are the same upto the character ‘m’. The last character of string ‘seemA’ has lower ASCII value than the last character of string “seema.” PM Publishers Pvt. Ltd. 149

String Slicing Many times, there is a requirement to access a range of items from a string. In such situations, you can use a slicing operator. While using slicing operator, we define the following things: a) A starting point b) An end point c) Step size You should remember that step size is 1 by default, if you do not mention explicitly. The basic syntax of string slicing is as follows: str[start:end:step_size] Let us understand the concept of string slices with the help of an example. Suppose you have to define a variable “name” which holds a string value i.e. ARTIFICIAL. Now, if you write the following statement: >>> name= “ARTIFICIAL” [2:9] 0 1 23 4 5 6 7 8 9 A RT I F I C I AL -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 [-9:-5] >>> print(name[2:9]) # Statement 1 >>> print(name[-9:-5]) # Statement 2 Here, statement 1 will return all the characters starting from the 2ⁿ index to the 8 index (excluding the character of 9 index), i.e. TIFICIA whereas statement 2 will return all the characters starting from -9 index to -6 index (excluding the character of -5 index), i.e. RTIF While string slicing, you should remember that if you do not mention any index before slicing operators, then the index will be taken as zero by default and if you do not mention index after slicing operator, in such a case Python will consider the last index. You can understand the concept of missing index with the help of examples given below: >>> print(name[:10]) # Statement 3 >>> print(name[3:]) # Statement 4 On executing statement 3, you will get whole string i.e., ARTIFICIAL whereas you will get sliced string IFICIAL on the execution of statement 4. String Built-in Functions/Methods As you know, built-in functions are readymade functions. Python offers a wide variety of built-in functions for manipulating strings. Some of the commonly used string built-in functions are as follows: a) len(): This function is used to calculate the length of the string including whitespaces. Artificial Intelligence - 9 150


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook