0% found this document useful (0 votes)
33 views14 pages

C7-L6-Think Like A Computer

The document introduces children to the fundamentals of computer programming, focusing on Python and its turtle graphics library to develop logical thinking. It explains key concepts such as machine language, functions, arguments, loops, and the structure of Python scripts. Additionally, it provides practical examples and exercises to reinforce learning about programming and drawing with Python.

Uploaded by

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

C7-L6-Think Like A Computer

The document introduces children to the fundamentals of computer programming, focusing on Python and its turtle graphics library to develop logical thinking. It explains key concepts such as machine language, functions, arguments, loops, and the structure of Python scripts. Additionally, it provides practical examples and exercises to reinforce learning about programming and drawing with Python.

Uploaded by

Chida Nanda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
> (6) « Think Like a Computer > Dear children, Picking up from the previous learning Pao ‘that computers work differently than human brain about dif ferent types of intelligence. . how dif ferent types of learning aid in dif ferent types of intelligence. what is Artificial Intelligence. about major applications of AT. ».Weak/Narrow AT. .-how computers understand images. We have learnt... eee eanene how computers process human language. Learning fundamentals of Al concepts is one aspect. The other aspect is to know how to write programs to develop Al algorithms. We know that computers can be instructed to perform various tasks. You must have heard people say “program the computer”. When we need to give similar set of instructions frequently to a computer then instead of typing all the | arranged ing instructions every time, we store the instructions in the desired sequence | '®9i¢al sequence ina file. Such a file is called executable file. Then we just need to load that {5 called a file in computer’s memory so that it reads the file and executes the EXERT instructions one-by-one. Easy! Computers only understand machine language (binary sequence of 0s and 1s) so our computer program is translated into machine language by a utility software called translator. In programming, logical order or sequence of instructions is very important, Let us learn to think logically and type instructions for computer using an exciting tool called Python turtle library. The purpose of this chapter is to develop your logical thinking and prepare you to understand serious programming in near future. What is Python? Python is the most popular programming language today used to build programs for websites, artificial intelligence algorithms, games and robots. You will learn in detail about Python in higher classes. Letushave aquicklookat its features: Python isabsolutely free. Python is simpleto learn and use. Python has a rich collection of built-in libraries of programs to pick and use. These libraries are arranged in uniquely named packages suchas turtle, statistics, nlp ete. Python can run on all types of devices and operating systems. Python Packages Python has a huge collection of pre-designed programs called python libraries. These programs are organised in various collections called packages. To use the programs in a package, you just need to importthat package inyour Python script. Python programs are-called scripts. Opening Python Script Editor To launch Python development environment, open ace the Python n.x folder in the Start menu and click on gE IDLE (Python n.x...) option. oem Python IDLE + ienienia IDLE is Python's Integrated Development and Learning Environment. Itallows interactive as well as script modes to work with Python interpreter. It provides an editor to write and edit your scripts (programs) and to save them. Python shell is built into IDLE which interprets the commands andscriptssubmittedto it. ‘Thescripteditor can be opened using Python shell window. Click File> New File (orpressCtrl+N). Aseparate window of scripteditor will open. Type the desired Python program. Python Turtle Graphics Turtle graphics is a drawing library of python which is used as an exciting tool to develop logical thinking while drawing amazing patterns and graphicsona canvas. Letus dive right into drawing with turtle! From this pointonwards, you are supposed to create your scripts by following the steps given here and understand the output by the explanation given alongwith, Python scripts are saved with the extension py. Tom the turtle GB tomt.py - Cruser/eSOFT/Desktopytom py 2.8.1) Turtle is denoted bya small arrow which movesand draws _S £ Fast fin Options window eo on the canvas like a pen does on the paper. We call our 1 2™Poxt turtle turtle Tom! Let us begin. Open script editor and type the eee Formeeationy following lines as shown here: a Savethe scriptby your_name_tom1. Torun the script, press F5 or Run menu> Run Module option. Whatdid you notice? Letus understand whatis happeningin this 3-Line program. importturtle All your turtle graphics scripts will begin with this line because import command is making turtle library available to yourscript. tom=turtle.Pen() All the functions of turtle library can be accessed by mentioning turtle followed by a dot and then the required function. Here, we are usinga function Pen() and assignanametoiti.e.tom. Nowall the drawingcapabilities are available in tom. ‘Turtle canalso be created by function Turtle() such as tom = turtle. Turtle(). tom.forward(100) Function forward() takes 100 asan argumentand move tom forward by 100 steps. <= By default, turtle faces east (rightward). Turtle always moves forward or back in its current direction. f Note | What is a function? A function is a pre-designed program to do some useful task. Tt can be invoked by mentioning its name. What is an argument? Certain functions need some inputs to perform their task. Such inputs are called arguments. E.g. function forward() takes a number as argument to move the turtle as many steps. Let us try a small program to move our friend tom around on canvas as it draws. Open a new blankscriptandtry this code: a Tisport turtle 2 tom = turtle Fen() 3 — 4 tom. foxward (100) 5 tom. 26£0 (90) 6 tom. forward (100) 7 tom.zight (30) 6 tom. forward(100) Crete ee 9 * Letus compare output with the script. Line 4: tom.forward(100) -Firsthorizontal lineisdrawn, Line 5: tom.left(90) -tom turns left (i.e. north or up direction in canvas). Line 6: tom.forward(100) - Vertical line is drawn. Line 7: tom.right(90) -tom turns right from its current pos Line 8: tom.forward(100) -Second horizontal lineis drawn. jon (Le.east), What did youlearn? Turtle can beturnedleftand rightby certain degrees. Some functionstakearguments to complete their task. ‘Try this script: > SS ke 2 Soa EaShenea200) Seon terete) so ) Noticelines4and8. Inline 4, forward() is passed -100 that means 100 steps backwards, Same can be achieved by passing 100to function backward() -seelines 8and 10. Also, compare this output with previous. Earlier, drawing is at the tail of the turtle while th drawingisatthe mouth or tip of the turtle because it finally moved backwards while drawing A. Drawasquare of 100steps. B. Drawarectangle of 100 steps by 50 steps. Function circle() takes the radius as argument and draws the circle. See this script drawing a circle ofradius 50. Brn py -cruswstsortmetop on 4 phon Tate Gace - 0 x fest format an Optons Wedow isp a import turtle 2tom = turtle.Pen() 3 tom. circle (50) 4 Repeating Tasks One great aspect of |. programming is that.» © toms t ope vice vor computer can repeat} 22°s* turtle tasks for you several 3 times as long as you ##o* © in range(t. 5); need. You just need ¢ — fo-forwss\ to tell the computer 7 how many times you need it to execute the tasks. Such process of executing tasks repeatedly is called looping. Let us understand it. Try the followingscript: Totell the computerhow many times tasks should execute, useforkeyword. Noticeline 4: for cin range(1,5):(itterminates withacolon) ton ate ce ax Consider the function range(1,5). This function creates a list of numbers in a range. Here, itis creatinga list 1, 2,3,4. 5 isthe limit. List is created always one less from the upper limit.) Now, see for keyword. It tells the computer to count from first number till last number of the list. But, for cannot count itself. Itneeds a name to identify each count. Here, that nameis. Itis justan imaginary name given to each count. The value of ewill be 1 forthefirsttime. Letus look at the task now. Notice lines 5 and 6. Line 5 will move the turtle 100 steps forward. Line 6 will turn the turtle leftat rightangle (90 degrees), The value of cis 1 for the first time. A horizontal line is drawn. After that, program control will again return to line 4 and next count will occur. This time, value of ¢ will become 2. Still, upper limit is not reached, so lines 5 and 6 will execute the second time. Vertical line will be drawn at rightangles to the horizontal line. Next, program control will again return to line 4 and next count will occur. This time, value of ¢ will become 3. Still, upper limit is not reached, so lines 5 and 6 will execute the third time. Second horizontal line willbe drawn at rightangles to the verticalline. Finally, program control will again return to line 4and next count will occur. This time, value ofc will become 4. Still, upper limit is not reached, so lines § and 6 will execute the fourth and last time. Second vertical line will be drawn at rightanglesto the second horizontal line. Program control will againreturntoline4. This time countisover so looping will stop. We gota squareand turtleisback tohome! How does computer know which tasks to repeat? How did computer know in our program that line 5 and 6 are exactly the part of loop? Well, that is done by the help of indentation. Notice, lines 5 and 6 are shifted rightwards a little. This is called indentation. It is done by pressing tab key once. Python looks at indented lines and figures out which lines belong to which loop. awty D, * "ew the Output of the ScriPt Try this script and answer the questions that follow: Tampere turtle Ql: Which linesare the part of loop? How did youknow? <%= fer#e. Fea) Gor @ Sn ranget.®) 5 tom. forwara(L00) 6 tem. laee(so) 7 toa. 2eFe(€5) tom. forwara(140) Q2: How many times lines 7 and 8 will execute? Youcanuseloop counter to create interesting drawings. Try this script: toe teeta) Line 4: for loop is counting 99 times. Inline 5, function forward (c) is taking value of counter € which is changing every time the loop executes. That is why, the lines drawn get longer and longer in the output. The shape is an octagon (8 sides) because of line 6 which turns the turtle 45 degrees. (45X8= 360 degrees complete). ‘Try changing valuesof cand draw different patterns. ‘Try the following scripts and draw their outputs. Deir cmmeonmmennegnet 2 tam = tartle-Fen() 4 tom. forward (80) S45r' ein rangoca,20 + 0 Som sorearatcy 5 REET 5 eam. xtghe (20) 1 tam Eolas) feoe @ in angela): 5 fam ett (80) 22 for © sn range(a,20): 6 tomeigneas) 33° tem. forwardter 5 34 tom deste) You can setthe colourand width ofthepen to draw. The white background of the canvas can be set to a colour using function turtle.bgcolor() Ittakesthename ofthe colouras “cus « tartie sent) argument, 5S Sarclasbgootor(‘oranae") Function pencolor() takes the §... < .. canseas) name of the colour as argument $ tee-peseaiae( sos) and function widthQ) takes a (° Series” numberforwidthasargument, 2 Sees Seethis script. u Here, inline 4, width ofthe penissetto5 pixels. Inline 5, background colour ofthe canvasisset to orange. Inlines8 and 11, colour ofthe penisset tored and green respectively. The loop is running 4 times, drawing 8 circles. Every time a circle is drawn, the turtle turns left by 45 degrees and colour changes alternatively. (Every red circle is at 90 degree (45+45) and greencircleat45 degree.) Todrawornottodraw Function penup() makes the turtle move without drawing. Function pendown() makes the turtle draw. Both these functions do notneed any argument. See this script that draws dashed line using penup() and pendown() alternatively in a loop which runs 9 times (notice the number of dashesis 9). Cre ate Gach: - oo x import turtle 2 tom = turtle.Pen() 3 tom. width (5) 2o------5 4 tom.pencolor ("xed") 5 for ¢ in range(1,10): : 6 tom. forward (10) < > tom.penup() ‘tom. forward (10) tom.pendown () Filling Colours in Drawings Function fillcolor() takes the name of the colour as argument and fills colour in the drawing. To fill the colour, we must inform the computer when the drawing is beginning and when it is ending. To do this, functions begin fillQ and end_fill() are used. fill_color() always falls between them. See thisscript drawinga yellow square with green outline e (iphetate gie a x import turtle 2 tom = turtle.Pen() 9 tom. width (10) 4 tom.pencoler ("green") 5 6 tom. £ilLcolor ("yellow") 7 tom-begin_£i11() 8 9 for © in range (1,5): 10 ‘tom. left (90) a tom. forward (100) a2 133 tom-end_£411() See line 6. Init, function fillcolour() istaking colour name yellow asargument. Notice lines 7 and 13. They are marking the beginning and end of the drawing, Between them, the drawingisdoneby the code inlines9, 10 and 11. When drawing ends, yellow colour is filled. Function fillcolor() also sets the colour of the turtle. also sets the outline colour of the turtle. imilarly, function pencolor() There are certain other functions you canapply on theturtle suchas: Changes the shape of the turtle to turtle, arrow, triangle, shape() cirele, square and classic, shapesize() Changes the size of the turtle. setpos() Moves the turtle to specified x.y coordinates on the canvas. undo() Cancels the last action done by turtle. clear() Clears the canvas, reset Clears the canvas, resets turtle to all default settings and brings the turtle to coordinates 0,0. See the example below (lines 4, 6and 8): 2 tom = turtle Turtle() 4 tom. shape ("turtie S tom f1zleoter ("zea") 6 tem shapesize (2) 7 tom pene 0 © tom setpon (-280 200) 9 tem poncelor ("blue") * 10 tom Bete ($0) The centre of the canvas is x=0, y=0. As you move up, y coordinate increases and as you move down, y coordinate decreases. As you move right, x coordinate increases and as you move left, x coordinate decreases. cuss foam ° g eooeeee A Computers only understand machine language. Computer program is translated into machine language by a utility software called translator. Python programming language is free, simple to learn and loaded with powerful libraries. Python IDLE is an integrated learning and development environment to develop and manage Python programs Python IDLE works in interactive and script modes. Python turtle library is useful to learn Python basics. Python files have extension py. Python turtle draws ona canvas. Translator: Utility software that converts computer language program into machine language. Library: Collection of pre-designed programs. Package: Organisation of libraries. Script: A Python program. Function: Anindependent piece of code identified by aunique name. Argument: Value passed toa function, Loop: The block of program executing repeatedly. Indentation: Tab-shifting the line of code to align them as the part of ablock. Exercise Select the correct answer. 1, Acomputer file containing a computer program is called a/an. file. a. Logic b, Instructions c. Executable d. Icon @ 2, A translator is which of the following types of software? a. Computer b. Useful c. Utility d. Machine 3, Python is which of the following? a. Software b. ATProgram cc. Programming language. 4. Utility 4, Collections of useful, predesigned programs are called which of the following? a. Library b. Template cc. Theme d, Allof these 5. Python libraries are organised as which of the following? a. Themes b. Templates ¢. Botha)andb) d. Packages 6. Python programs are called which of the following? a. Utilities b. Libraries c. Packages d. Scripts 7. We can save our Python programs inwhich of the following modes of IDLE? a. Interactive mode b. Script mode ¢. Botha)andb) d. None of these. 8. The extension of Pythonprogram files is which of the following? a. -ipy b. pyt c. .pyn d. py 9. One of the most appealing features of Python is that it a. isfree b. issimple tolearnanduse c. has huge collection of useful libraries d. Allof these 10. Touse.a package in our Python programs, weneed to. it, a. Insert b, Export cc. Import d. Select 11, The two ways toruna Python script inPython IDLE are: a. Press F5,Run>Run Module b. Press F6,Run>Run Module. c. Press F5,Run>Run Script d. Press F6,Run>Run Script 12, turtle.forward(50)- in this statement, what is 50? a. Anumber b. Direction c. Argument d, Output @ 13, turtle.right(45)- in this statement, what is 45? a. Steps b. Degree cc. Length d. How many times 14, turtle.backward(-50) and turtle.forward(50)means what? a. Same b. Not same c. Errorinstatements d, None of these 15. for xin range(1,10):- this loop should execute how many times? au b. 10 a9 d. None of these 16. Thestatement whicharea part of ablock suchas loop are together. a. Coded b. Kept c. Saved d, Indented 17. If Python turtle has to draw adashed line (-----) thenit must us a. penup() b. pendown() c. Botha)andb) d. draw(yes/no) 18, turtle.fillcolor(‘red")- this statement is doing what? «a. Filling colour in the figure drawn b. Only setting the colour tobe filled c. Filling the outline colour 4. Only setting the outline colour 19. To clear the canvas, reset default settings and bring the turtle to the centre of the stage, we use which of the following functions? a. clear() b. reset() c. Botha)andb) d. undo() 20. The centre of the turtle canvas is denoted by which of the following values of coordinates x,y? a. 0,0 b. 100,100 . 500,500 dit Match the functions in column A with their use in column B. A B 1. Pen() a. Clear the canvas. 2. range() b. Creates aturtle by some name, 3. bgcolor() ¢. Marks the end of filling colour ina figure drawn. 4, end_filld) d. Brings turtle to coordinates 0, 0. 5. clear() e. Creates alist of numbers. 6. reset() f. Sets the colour of the canvas. @ Explain the following terms in one sentence. 1. Program 2. Script 3, Translator 4, PythonLibrary 5. Package ‘Answer the following questions. How isinteractive mode of Python IDLE from Script mode? Explain the use of the term import with an example. List major features of Python What is turtle? Why dowe need to import it in Python script? What is a function Python programming? What isa function argument? Explain with asmall example. What is the significance of indentation in Python programming? Which function help in starting and stopping filling colour in a figure drawn by Python turtle? 9. How canwe set the outline.colourof afigure tobe drawnbyPython turtle? Give example. 10.Briefly explain Python turtle canvas coordinates. PNETawNE Draw the output of the following Python turtle scripts. Give brief explanation wherever you think necessary. import turtle import turtle t= turtle Pen() t= turtlePen() for x in range(t.9) for x in [50, 60, 80, 90, +.forward(100) 100} tleFt(45) tincle(x) ‘t.backward(25) tleft(180) import turtle t= turtlePen() for x in (5, 10, 15}: +t forward(100) twidth(x) tleft(-120) import turtle += turtle Pen() + illcolor("red") import turtle += turtle Pen() + filleolorC'yellow") turtle.bgcolor(“blue") teinele(50) turtle.bgcolor("yellow") ‘tpencolor("green" t.width(10) +.begin_fillO +circle(50) tend_fill) ) F. Write Python turtle scripts to display following outputs. ) www.youtube.com/edusoftknowledgeverse @

You might also like