INTRODUCTION TO CODING

Transcription

INTRODUCTIONTO CODINGGRADE VIIIStudent HandbookVersion 1.0

INTRODUCTIONTO CODINGGRADE VIIIStudent Handbook

ACKNOWLEDGEMENTPatrons Sh. Ramesh Pokhriyal 'Nishank', Minister of Human Resource Development,Government of IndiaSh. Dhotre Sanjay Shamrao, Minister of State for Human ResourceDevelopment, Government of IndiaMs. Anita Karwal, IAS, Secretary, Department of School Education and Literacy,Ministry Human Resource Development, Government of India AdvisoryEditorial and Creative Inputs Mr. Manuj Ahuja, IAS, Chairperson, Central Board of Secondary EducationGuidance and Support Dr. Biswajit Saha, Director (Skill Education & Training), Central Board ofSecondary EducationDr. Joseph Emmanuel, Director (Academics), Central Board of SecondaryEducationSh. Navtez Bal, Executive Director, Public Sector, Microsoft Corporation IndiaPvt. Ltd.Sh. Omjiwan Gupta, Director Education, Microsoft Corporation India Pvt. Ltd.Dr. Vinnie Jauhari, Director Education Advocacy, Microsoft Corporation IndiaPvt. Ltd.Ms. Navdeep Kaur Kular, Education Program Manager, Allegis Services IndiaValue adder, Curator and Co-Ordinator Sh. Ravinder Pal Singh, Joint Secretary, Department of Skill Education, CentralBoard of Secondary Education

ABOUT THE HANDBOOKCoding is a creative activity that students from any discipline can engage in. It helps tobuild computational thinking, develop problem solving skills, improve critical thinkingand exposure to real life situations to solve problems in various realms.Therefore, CBSE is introducing ‘Coding’ as a skill module of 12 hours duration in classesVI-VIII from the Session 2021-2022 onwards. The idea is also to simplify the codinglearning experience by nurturing design thinking, logical flow of ideas and apply thisacross the disciplines. The foundations laid in the early years will help the students tobuild the competencies in the area of AI, data sciences and other disciplines.CBSE acknowledges the initiative by Microsoft India in developing this coding handbookfor class VIII students. This handbook uses block coding to explain advanced conceptsof coding using python in MakeCode platform. It uses gamified learning approach tomake learning experience more engaging. The book is intuitive with practical examplesof theoretical concepts and applied exercises. There are mini projects that students canwork on. Additionally, the handbook also focuses on creating exposure to ethics ofcoding and application of coding in other subjects like mathematics.The purpose of the book is to enable the future workforce to acquire coding skills earlyin their educational phase and build a solid foundation to be industry ready.

RESOURCES FOR STUDENTSMinecraft education editionMinecraft education edition is a game-based learning platform that promotes creativity,collaboration, and problem-solving in an immersive digital environment. This platformprovides a fun way of learning coding and design thinking concepts.Visit https://education.minecraft.net/ for more details.MakeCodeMicrosoft MakeCode is a free, open source platform for creating engaging computerscience learning experiences that support a progression path into real-worldprogramming. It brings programming to life for all students with fun projects, immediateresults, and includes both block and text editors for learners at different levels.Visit https://www.microsoft.com/en-us/makecode for more details.GitHubGitHub is a storehouse where you can manage and collaborate on your code. It helps tomaintain different versions of the code easily. GitHub Student Developer Pack givesstudents free access to the best developer, web development, gaming and many othertools at no cost enabling practical learning.Sign up for the GitHub Student developer pack herehttps://education.github.com/discount requests/student application?utm source 2021-06-11-cbse

TABLE OF CONTENTSTable of Contents . IEthical practices in coding .1CONDITIONALS IN DETAILS .21.1What will you learn in this chapter? .21.2Types of Control Structures .21.3Understanding IF-ELSE and ELSE-IF statements.21.4Logical Operators .31.5Precedence of Logical Operators.51.6Activity: Display if a number is odd or even.61.7Nested Conditional statement . 111.8Activity: The nested division problem . 121.9Quiz time. 131.10What you have learned in this chapter . 15GET CREATIVE WITH LOOPS. 162.1What will you learn in this chapter? . 162.2What are Loops? . 162.3Exit Criteria . 172.4Activity: Cat Rain . 182.5Activity: Create a staircase using for loop . 212.6Activity: Create a staircase using while loop . 232.7Activity: Raining pigs and pandas. 252.8Quiz time. 272.9What have you learnt in this chapter?. 28FUNCTIONS IN DEPTH . 293.1What will you learn in this chapter? . 293.2Recap of functions. 293.3Function Parameters . 293.4Activity: Calculating Volume of Cuboid. 303.5Returning value from a function . 34I

3.6Quiz time. 353.7What have you learnt in this chapter?. 36PROGRAMMING WITH ARRAYS . 374.1What will you learn in this chapter? . 374.2What are Arrays? . 374.3Activity: Playing with colors. 374.4Sorting an Array . 384.5Searching in an Array . 384.6 Using Python to arrange an array in ascending order using bubble sort inMakeCode. 394.7Activity: Fun in Minecraft using arrays. 444.8Activity: Building stairs . 474.9Quiz time. 494.10What have you learnt in this chapter? . 55ADVANCED SEQUENCING . 565.1What will you learn in this chapter? . 565.2What is a Sequence? . 565.3Sequencing with Loops and Conditions . 575.4Activity: Print number divisible by 3 from 1 to 100 . 575.5Quiz time. 595.6What have you learnt in this chapter?. 60References . 61II

ETHICAL PRACTICES IN CODINGAs you build capabilities around coding, you will be equipped to build software on yourown which will have an impact on society in general. So, it is very important to adhereto ethical practices while building your own code. Below are some practices you mustremember as you keep learning to code.Respect other’s privacyAs you keep building software of your own you might need to access other’s personalinformation. Make sure you do not misuse the data and you understand your rights andresponsibilities associated with that dataHonor ConfidentialityYou might be given access to confidential information like trade secrets, client data,financial information etc. Ensure you do not disclose this information without properauthorizations.Page 1

CONDITIONALS IN DETAILS1.1 What will you learn in thischapter?In this chapter you will understandconditionals in detail and how to useconditionals in your code.Here you will learn: Understanding IF ELSE and ELSEIF statementsUsing logical operatorsUsing nested conditionsSelection / Conditional - A selection(conditional) control structure is used totest a condition in a program. Thiscontrol structure takes a decision toexecute one statement/operation overanother statement/operation dependingon the condition.Iteration – This control structureexecutes a set of statements for a certainnumber of times till the mentionedcondition is true. Loops are examples ofiterative statements.1.2 Types of mming has derived many types ofcontrol statements to suit differentneeds. We will study them in upcomingtopics.In programming, control structure is ablock of program that accepts andanalyses different variables and choosesthe direction in which to go based on thegiven parameters. To put simply, it is abasic decision-making process incomputing. It is like a prediction thatprogram makes by accessing the givenparameters.1.3 Understanding IF-ELSE andELSE-IF statementsThere are three basic types of controlstructures in programming:1. Sequential2. Selection / Conditional3. IterationSequential - In a sequential controlstructure, the statements in a programare executed sequentially, i.e. step-bystep in an order that they are written.Every day, we take many decisionsdepending on our situation. Forexample, we decide whether a number iseven or odd by dividing the number with2. If the remainder is 1, we can say thenumber is odd.IF-ELSE StatementIf we want to implement the logic in ourprogram, we need to use if-elsestatement.Page 2

The if-else statement requires threethings.1. Evaluation statement: conditionor expression that is beingchecked2. Executionstatement:theoperations that will be performedif the condition appears to be true3. Elseexecutionblock:theoperation that will be performedonly if the evaluation statement isfalseexpression used in false. The last line ofcode will be executed always because weare back using the origin indentation.If we implement the scenario usingproper syntax it will look like thefollowing lines of code.If we need to determine, a number iseven or odd using a flowchart, itbecomes like the following diagram.Point to note over here is that “ ” is anassignment operator, i.e. it is used toassign a value to a variable. And “ ” isa relational(comparison) operator, i.e. itis used to compare the value of twovariables.ELSE-IF StatementIf we implement the flowchart usingcoding syntax, it will be like the followingFig 1.1 Understanding if-elselines of code.In above example a %2 0 is theexpression that we are using forevaluation, and in the next line we areusing indentation to indicate theexecution statement. In the next lines weare using else keyword to indicate whatstatements will be executed in case theLet’s consider a situation where we needto compare two numbers a, b anddetermine if a is greater than b or theyare equal. To implement this one, weneed to perform checks at two steps. Thekeyword we need to use is elif. Thekeywork elif is used for checking anotherstatement in case previous statement isfalse.1.4 Logical OperatorsLogical operators are fundamentalblocks that can be used to build adecision-making capability in your code.When we need to make our decisionbased on two or more checks, it isnecessary to have a combination oflogical operators.Page 3

We can do things conditionally in ourprograms using if statements or if/elsestatements combined with logicaloperators. Logical operators work likeBoolean variables and return eitherTRUE or FALSE.In python programming, we use notkeyword to denote not operator. Someother programming languages use “!” asNOT operator.The three most important logicaloperators are AND, OR and NOT.Let us now look at the full list ofrelational operators.AND OperatorThe AND operator is used to see if two ormore conditions are true. If all theconditions are true, the AND operatorreturns TRUE. If any one of theconditions fail, the AND operator returnsFALSE. In python AND operator isdenoted by and keyword. Some otherprogramming languages use “&&” asAND operator.OR OperatorThe OR operator is used to see if eitherone of two or more conditions is TRUE.If any of the condition is true, the ORoperator returns TRUE. If all theconditions fail, the OR operator simplyreturns FALSE. In python syntax ORoperator is denoted by or keyword. Someother programming languages use “ ”as OR operator.Relational ual to x y x yLessthanGreaterthan orequal to x y x yLessthan orequal to x yNotequal to! x! yx greaterthan yx is equalto yx is lessthan yx is eithergreaterthan orequal to yx is eitherless thanor equal toyx not equalto yPoint to note over here is that “ ” is anassignment operator, i.e. it is used toassign a value to a variable. And “ ” isa relational(comparison) operator, i.e. itis used to compare the value of twovariables.NOT OperatorWe use the NOT operator to reverse ornegate a condition. If the condition istrue, NOT will return false and viceversa.Page 4

Activity: Can you create a triangle?Take this example of following figure oftriangle with sides A, B and C. We knowdetermines how the operations aregrouped in the absence of parentheses.Parentheses can be used to group theoperands with their correct operator,just like how we do it in arithmetic.In an expression, the operator withhighest precedence is grouped with itsoperands first, then the next highestoperator will be grouped with itsoperands, and so on. In a situationwhere there are many logical operatorsFig 1.2 Can you create a triangle.the sum of two sides must be greaterthan remaining side.Unless all sides are compared, wecannot say values for A, B and C arevalid or not. Therefore, we need tocombine all three logical expressions tosay whether they can truly make atriangle.Now, if we want to solve the problem oftriangle in python coding it becomes asfollowing.Fig 1.3 Conditions to create a triangle.1.5 Precedence of LogicalOperatorsof the same precedence, they will alwaysbe examined from left to the right.Have a look at the below table to checkthe precedence of logical operators:OperatorPrecedenceNOT (!)HighAND (&&)MediumOR ( )LowIn the below example, A1, A2, A3 and A4stand for the relational expressions.They have a mix of “&&”, “ ” and “!”operators. The expression in the firstcolumncanbeinterpretedbyparentheses as shown in the thirdcolumn.Just like arithmetic operators, logicaloperators also have precedence thatPage 5

It is a common practice to useparenthesis to group operands togetherrather than relying on logical operatorprecedence rules.A1 && A2&& A3 A4can beinterpreted as((A1 && A2)&& A3) A4A1 A2 &&A3can beinterpreted asA1 (A2&& A3)! A1 && A2 A3can beinterpreted as((!A1) &&A2) A3A1 && A2 A3 && A4can beinterpreted as(A1 && A2) (A3 &&A4)1.6 Activity: Display if a number is odd or evenLet us now run through a practice exercise to understand logical operations. You shouldtry this exercise on the Minecraft Education Edition. You may set up the Minecrafteducation edition from https://education.minecraft.net/get-startedNote: Minecraft is just one of the platforms to achieve this output. You can use manysimilar platforms available online to achieve similar output like – Scratch(https://scratch.mit.edu/) and Code.Org (https://code.org/)At the end of this activity, you can expect following output on screen:Page 6

Let us now follow below steps to replicate this output on screen:Page 7

Page 8

Page 9

Now we will implement the example of odd-even to display some messages on the screen.The program that you have written assigns 34 to a variable named as a. Then, in thenext lines of code, it checks whether variable a is now divisible by 2. If it is divisible, weare displaying a message on the screen. At line 3, 5 and 6 the statement player.say isused for displaying the message in the screen.When you are done with typing the necessary lines of code, click on the green Startbutton to execute the program. You will see the below result displaying number is even.Page 10

Activity 1.1Create a program in Minecraft whichwill check two numbers and display amessage saying if one is greater thanthe other, or they are same.1.7 Nested ConditionalstatementIn some cases, for checking complexscenarios we might find that using asingle if-else loop is not enough. We canalso use a combination of if, elseifstatement inside another if block.if condition 1:if condition 2:statement 1elsestatement 2elif condition 3:if condition 4:statement 3elsestatement 4else:statement 3Suppose we want to check if a numberis divisible by 4 or 5 or both 4 and 5. Weneed to check in multiple steps. First, weneed to check if its divisible by 4, if thiscondition is true, then we further needto check if it is divisible by 5. In anotherIF block we again need to checkdivisibility by 5, and check if it isdivisible by 4.Syntax of nested conditional statementsis like belowPage 11

1.8 Activity: The nested division problemWe will now create the program to check if a number is divisible by 4 or 5 or both 4 and5. To do that, open Minecraft Code Editor again. You can get the instructions fromprevious sections for doing that.Now that you have Minecraft Code Editor opened, type down the program as given below.Make sure the indentations are correct.After you are done with typing the code, click on the green Start button to execute theprogram.Result:You will now see that message is displayed according to the logic we have written in ourprogram. It assigns 44 in a variable called number. Then it goes through our nested ifelseif blocks toPage 12

display the result. If you have typed the lines of code properly, clicking onStart button will display a message like below.Now press C key to go back in the code editor. You can change the value of the variableand run it again. By doing that, you can verify if the program is behaving as you haveexpected.Activity 1.2Create another program which assigns total marks of a student to variable, anddisplay grade using the logic below. Total marks 70, then grade A Total marks 49 and Total marks 70, then grade B Total marks 49, then grade C1.9 Quiz timeObjective Type QuestionsQuestion 1Which one of the following options is not a logical operator?Option 1Option 2Option 3Option 4ORWHATANDNOTPage 13

Question 2Which of the following can create conditional statements?Option 1Option 2Option 3Option 4IFIF-ELSENested IF-ELSEAll the aboveQuestion 3Which operator negates a condition?Option 1Option 2Option 3Option 4ORNOTANDNone of the aboveStandard Questions1.2.3.4.5.WhatWhatWhatWhatWhatare different types of control structures? Define each type.are the different types of relational operators?are logical operators? Name different types of logical operators.are the differences between “AND” and “OR” operators? Give examples.is a nested conditional statement and where is it used?Higher Order Thinking Skills(HOTS)1. Create a program in Minecraft which assigns a number to a variable. Then checksif the number is divisible by 7 or 9 or both 7 and 9.2. Create a program in Minecraft which assigns a number to a variable. Then displayif the number is even or odd.3. Create a program in Minecraft which assigns a number to a variable. Find out if thenumber is divisible by 3. If divisible by 3, multiply it by 10 and display the output.Applied ProjectProblem Statement: There are three children named Rohit, Priya and Pooja. Height ofRohit, Priya and Pooja are 4.8 ft 5.2 ft and 5.1 ft respectively. Create a program inMinecraft using block coding to find who is the tallest of three.Sample solution:Page 14

1.10 What you have learned in this chapter AND, OR NOT are the different logical operatorsWe can combine multiple operators in a single expressionIF-ELIF is used to write logical operators in pythonWhen we have an IF within another IF, we call it a nested conditional statementWe learnt how to use operators in Minecraft code editorHow to apply logical operators in python coding?Page 15

GET CREATIVE WITH LOOPS2.1 What will you learn in thischapter?Now that we already understand logicaloperators in coding, let us dive deeperinto the details of how to solve a codingproblem. By the end of this chapter, youwill learn: What are the different types ofloops?Definition of different types ofloopsBreak and Continue loopsGet introduced to pseudocodeLoops make our code more manageableand organized. Let us now see what thedifferent types of loops are:1. While Loop2. For Loop3. Nested LoopThe While LoopThe While loop can execute a set ofcommands till the condition is trueWhile Loops are also called conditionalloops.Once the condition is met then the loopis finishedFor example - Print from 1 to 102.2 What are Loops?Everyday there are some tasks whichneedtobedonerepeatedly.Loops are programming elements whichrepeat a portion of the code for a setnumber of times till the desired processis complete. Repetitive tasks arecommon in programming and loops areimportant to save time and minimizeerrors.Here, if we want to derive the loop fromthis scenario, we have the followingconditions:Condition: Write from 1 to 10And the decision we are deriving is:Decision: Have we reached 10Based on this we can write the belowpseudocode:x 0while x is not 10x x 1print(x)Page 16

The For LoopFor loop is needed for iterating over asequence.For example – We need to calculate thesquare of numbers present in a list.Numbers [1, 3, 5, 7, 13]The pseudo code for this will look likebelow:numbers [1, 3, 5, 7, 13]sq 0for x in numberssq x * xprint(sq)This is the result for the code192549169The Nested LoopLoop can be nested in Python. A loopthat occurs within another loop is callednested loop. Consider the belowprogram.numbers [1, 2, 3]alphabets [a, b, c]for num in numbersfor alphabet in alphabetsprint(alphabet)We have used two loops here. The outerloop, iterates over the numbers arrayand the inner loop iterates over thealphabet array. So each of the alphabetsget printed 3 times.Finally, we have 9items that are printed.abcabcabc2.3 Exit CriteriaNow that we have understood aboutloops and its iterations, it is alsoimportant to understand when andwhere should one stop iterating throughthese loops. As mentioned in theprevious topic, it is very important tokeep in mind while programming thatthe looping condition should result falseat a certain point in time. Otherwise, theblock of code will enter an infinite loop.To make sure that the loop does notenter an infinite loop, it important todefine an exit criterion for the loop.Exit criteria is defined as a conditionthat must be met before completing aspecific task. It is a set of conditions thatmust exist before you can declare aprogram to be complete. Exit criteria isone of the most important componentswhile defining a loop. As without an exitcriterion, the program tends to enter inan infinite loop. These criteria differ fromprogram to program as per therequirement.For example, while creating a loop toprint numbers from 1 to 1000, exitcriteria is that loop should exit the blockof code when the 1000th number isPage 17

printed, else the program will enter aninfinite loop.Activity 2.1Write a pseudocode to print primenumbers from 1 to 1002.4 Activity: Cat RainYou might have heard the phrase “raining cats and dogs”. In this exercise we will seehow you can rain cats from the sky. You should try this exercise on the Minecrafteducation edition.By now you should already have an idea of block coding. Below is how the exercise willlook when implemented with block coding with MinecraftThe final output of this exercise should look like as shown in the image below.Page 18

However, in this exercise, we will try to implement the same code using python.Page 19

Follow the below code block. We have used a for loop with range 100 – This means thatthe loop will run 100 times.So, the line mobs.spawn(CAT, pos(0, 10, 0)) will be executed 100 times.Page 20

After you click on play 100 cats will rain from the sky.Note: Minecraft is just one of the platforms to achieve this output. You can use manysimilar platforms available online to achieve similar output like – Scratch(https://scratch.mit.edu/) and Code.Org (https://code.org/)2.5 Activity: Create a staircase using for loopIn this example we will create a block of stairs using tube coral black material wherethe for loop will run 10 times so the height of the stairs will be 10 blocks and the widthwill be three blocks.Below is how the code will look when implemented with block code using Minecrafteducation edition.At the end of this exercise, the final output should look like shown in the below image.Page 21

So, we see how the same action is performed using a for loop. The detailed explanationof the previous code is given below:Step 1: Teleporting the builder to the specified positionStep 2: Creating a for loop which will run 10 timesPage 22

Step 3:Step 4:Step 5:Step 6:blocks.Inside the for loop we will move the builder forward by 2 stepsMove the builder up by 1Finally the builder traces the path travelled and puts a block on the positionClick on play. You will see a flight of stairs of height 10 and having width of 3Note: Minecraft is just one of the platforms to achieve this output. You can use manysimilar platforms available online to achieve similar output like – Scratch(https://scratch.mit.edu/) and Code.Org (https://code.org/)2.6 Activity: Create a staircase using while loopIn one of the previous activities we used for loop to create a staircase. Now let us createa staircase with while loop.If we implement this with block coding, below is how the code will lookPage 23

At the end of this activity, the final output should look like shown in the image below.Below are the detailed steps:Page 24

Step 1: Set the value of size variable to 10Step 2: Teleport the builder to a specified positionStep 3: Create a while loop of size greater than zeroStep 4: Inside while loop move the builder forward by 1 stepStep 5: Next, move the builder up by 1 stepStep 6: Update the size variable by size size - 1Step 7: Finally, the builder traces the path travelled and puts a block on the positionStep 8: Finally run the code by clicking on play then on the chat window type step 10Results: You will see a stair of height 10 formed in your Minecraft world2.7 Activity: Raining pigs and pandasWe have already gone through an exercise to rain cats using for loop. We will now try totake it further by raining Pigs and Pandas using while loop.Below is how the code looks like when done using block code in Minecraft:Page 25

And when done with Python, the code will look like below.At the end of this activity, the final output on screen should look like shown in the imagebelow.Page 26

Below are the detailed steps:Step 1: In the on start command, first set variable “animals” to 0.Step 2: Now start a while loop which will run till the value of “animals” variable is lessthan or equal to 100.Step 3: Inside while loop, set spawn of pigs to specified position.Step 4: Inside while loop, set spawn of pandas to specified position.Step 5: Lastly, update the value of variable “animals” to “animals animals 1”.Step 6: Finally run the code by clicking on play then on the chat window type rain 100Result: After you run the code you will see 100 pigs and 100 pandas dropping from thesky in your Minecraft EnvironmentNote: Minecraft is just one of the platforms to achieve this output. You can use manysimilar platforms available online to achieve similar output like – Scratch(https://scratch.mit.edu/) and Code.Org (https://code.org/)2.8 Quiz timeObjective Type QuestionsQuestion 1Which type of loop can be used till a condition is met?Option 1Option 2While loopFor loopQuestion 2Which type of loop can be used to iterate over a sequence?Option 1Option 2While loopFor loopQuestion 3Which statement is used to break the loop?Op

The book is intuitive with practical examples of theoretical concepts and applied exercises. There are mini projects that students can work on. Additionally, the handbook also focuses on creating exposure to ethics of . Minecraft education edition Minecraft education edition is a game-