PROGRAM IN PYTHON - Permanently

Transcription

PROGRAMMING SERIES SPECIAL EDITIONPROGRAMIN PYTHONVolume OneFull Circle Magazine is neither affiliated, with nor endorsed by, Canonical Ltd.

Full Circle Magazine SpecialsAbout Full CircleFull Circle is a free,independent,magazinededicated to the Ubuntufamily of Linux operatingsystems. Each month, itcontains helpfulhow-toarticlesandreadersubmitted stories.Full Circle also features acompanion podcast, the FullCircle Podcast which coversthe magazine, along withother news of interest.Please note: this SpecialEditionis provided ibutors nor Full CircleMagazineacceptanyresponsibility or liability forloss or damage resulting fromreaders choosing to apply thiscontent to theirs or otherscomputers and equipment.Find e to another 'single-topic special'In response to reader requests, we are assembling thecontent of some of our serialised articles into dedicatededitions.For now, this is a straight reprint of the series'Programming in Python', Parts 1-8 from issues #27through #34; nothing fancy, just the facts.Please bear in mind the original publication date; currentversions of hardware and software may differ from thoseillustrated, so check your hardware and software versionsbefore attempting to emulate the tutorials in these specialeditions. You may have later versions of software installedor available in your distributions' forumdisplay.php?f 270IRC: #fullcirclemagazine onchat.freenode.netEditorial TeamEditor: Ronnie Tucker(aka: r: Rob Kerfia(aka: admin / linuxgeekeryadmin@fullcirclemagazine.orgPodcaster: Robin Catling(aka cations Manager:Robert Clipsham(aka: mrmonday) mrmonday@fullcirclemagazine.orgThe articles contained in this magazine are released under the Creative Commons Attribution-Share Alike 3.0Unported license. This means you can adapt, copy, distribute and transmit the articles but only under the following conditions:You must attribute the work to the original author in some way (at least a name, email or URL) and to this magazine by name ('full circle magazine') andthe URL www.fullcirclemagazine.org (but not attribute the article(s) in any way that suggests that they endorse you or your use of the work). If you alter,transform, or build upon this work, you must distribute the resulting work under the same, similar or a compatible license.Full Circle Magazine is entirely independent of Canonical, the sponsor of Ubuntu projects and the views and opinions in the magazine should in noway be assumed to have Canonical endorsement.Full Circle Magazine

HOW-TON/ADevGraphics Internet M/media SystemProgram In Python - Part 1(Graphical User Interface)programming. Let's jump rightin, creating a simpleapplication.to set it to be executable. Dothis by typingOur First Programin the folder where you savedyour python file. Now let's runthe program.Using a text editor such asgedit, let's type some code.Then we'll see what each linedoes and go from there.Type the following 4 lines.CD/DVDHDDAUSB Drive LaptopWirelessmong the manyprogramminglanguages currentlyavailable, Python isone of the easiest to learn.Python was created in the late1980's, and has maturedgreatly since then. It comes preinstalled with most Linuxdistributions, and is often oneof the most overlooked whenpicking a language to learn.We'll deal with command-lineprogramming in this article. Ina future one, we'll play with GUIchmod x hello.pygreg@earth: /python examples ./hello.pyHello. I am a pythonprogram.#!/usr/bin/env pythonWhat is your name? FerdBurphelprint 'Hello.program.'Hello there, Ferd Burphel!I am a pythonname raw input("What isyour name? ")print "Hello there, " name "!"That's all there is to it. Savethe file as hello.py whereveryou would like. I'd suggestputting it in your homedirectory in a folder namedpython examples. This simpleexample shows how easy it isto code in Python. Before wecan run the program, we needfull circle magazine #27greg@earth: /python examples That was simple. Now, let'slook at what each line of theprogram does.#!/usr/bin/env pythonThis line tells the systemthat this is a python program,and to use the default pythoninterpreter to run the program.print 'Hello. I am a pythonprogram.'7Simply put, this prints thefirst line "Hello. I am a pythonprogram." on the terminal.name raw input("What isyour name? ")This one is a bit morecomplex. There are two partsto this line. The first is name ,and the second israw input("What is your name?"). We'll look at the second partfirst. The command raw inputwill print out the prompt in theterminal ("What is your name?"), and then will wait for theuser (you) to type something(followed by {Enter}). Nowlet's look at the first part: name . This part of the commandassigns a variable named"name". What's a variable?Think of a variable as a shoebox. You can use a shoe-box tostore things -- shoes, computerparts, papers, whatever. To theshoe-box, it doesn't reallymatter what's in there -- it'sjust stored there. In this case, itstores whatever you type. Inthe case of my entry, I typedFerd Burphel. Python, in thiscontents

PROGRAM IN PYTHON - PART 1instance, simply takes theinput and stores it in the"name" shoe-box for use laterin the program.print "Hello there, " name "!"Once again, we are usingthe print command to displaysomething on the screen -- inthis case, "Hello there, ", pluswhatever is in the variable"name", and an exclamationpoint at the end. Here we areconcatenating or puttingtogether three pieces ofinformation: "Hello there",information in the variable"name", and the exclamationpoint.Now, let's take a moment todiscuss things a bit moredeeply before we work on ournext example. Open a terminalwindow and type:pythonYou should get somethinglike this:greg@earth: /python examples pythonPython 2.5.2 (r252:60911,Oct5 2008, 19:24:49)[GCC 4.3.2] on linux2Type "help", "copyright","credits" or "license" formore information. You are now in the pythonshell. From here, you can do anumber of things, but let's seewhat we got before we go on.The first thing you shouldnotice is the python version -mine is 2.5.2. Next, you shouldnotice a statement indicatingthat, for help, you should type"help" at the prompt. I'll let youdo that on your own. Now type: SyntaxError: invalid syntax That's because the word"print" is a known command,while "Print" is not. Case isvery important in Python.Now let's play with variablesa bit more. Type:var 2 2print 2 2You'll see that nothing muchhappens except Python returnsthe " " prompt. Nothing iswrong. What we told Python todo is create a variable (shoebox) called var, and to stickinto it the sum of "2 2". To seewhat var now holds, type:and press enter. You'll get backprint var print 2 24 Notice that we typed theword "print" in lower case.What would happen if we typed"Print 2 2"? The response fromthe interpreter is this: Print 2 2File " stdin ", line 1Print 2 2full circle magazine #27and press enter. print var4 Now we can use var overand over again as the number4, like this: print var * 28 8If we type "print var" againwe'll get this: print var4 var hasn't changed. It's stillthe sum of 2 2, or 4.This is, of course, simpleprogramming for thisbeginner's tutorial. Complexitywill increase in subsequenttutorials. But now let's look atsome more examples ofvariables.In the interpreter type: strng 'The time hascome for all good men tocome to the aid of theparty!' print strngThe time has come for allgood men to come to the aidof the party! You've created a variablenamed "strng" (short for string)containing the value 'The timehas come for all good men tocome to the aid of the party!'.From now on (as long as we arecontents

PROGRAM IN PYTHON - PART 1in this instance of theinterpreter), our strng variablewill be the same unless wechange it. What happens if wetry to multiply this variable by4? print strng * 4The time has come for allgood men to come to the aidof the party!The time hascome for all good men tocome to the aid of theparty!The time has come forall good men to come to theaid of the party!The timehas come for all good men tocome to the aid of the party! Well, that is not exactlywhat you would expect, is it? Itprinted the value of strng 4times. Why? Well, theinterpreter knew that strng wasa string of characters, not avalue. You can't perform mathon a string.What if we had a variablecalled s that contained '4', asin the following: s '4' print s4It looks as though s containsthe integer 4, but it doesn't.Instead it contains a stringrepresentation of 4. So, if wetype 'print s * 4' we get. print s*44444 Once again, the interpreterknows that s is a string, not anumerical value. It knows thisbecause we enclosed thenumber 4 with single quotes,making it a string.We can prove this by typingprint type(s) to see what thesystem thinks that variabletype is. print type(s) type 'str' integer and then multiplied by4 to give 16.You have now beenintroduced to the printcommand, the raw inputcommand, assigning variables,and the difference betweenstrings and integers.Let's go a bit further. In thePython Interpreter, type quit()to exit back to the commandprompt.Simple For LoopNow, let's explore a simpleprogramming loop. Go back tothe text editor and type thefollowing program.#! /usr/bin/env pythonfor cntr in range(0,10):Confirmation. It's a stringtype. If we want to use this asa numerical value, we could dothe following: print int(s) * 416 The string (s), which is '4',has now been converted to anfull circle magazine #27print cntrBe sure to tab the "printcntr" line. This is important.Python doesn't useparentheses "(" or curly braces"{" as do other programminglanguages to show codeblocks. It uses indentationsinstead.9Save the program as"for loop.py". Before we try torun this, let's talk about what afor loop is.A loop is some code thatdoes a specified instruction, orset of instructions, a number oftimes. In the case of ourprogram, we loop 10 times,printing the value of thevariable cntr (short forcounter). So the command inplain English is "assign thevariable cntr 0, loop 10 timesprinting the variable cntrcontents, add one to cntr anddo it all over again. Seemssimple enough. The part of thecode "range(0,10)" says startwith 0, loop until the value ofcntr is 10, and quit.Now, as before, do achmod x for loop.pyand run the program with./for loop.pyin a terminal.greg@earth: /python examples ./for loop.py01contents

PROGRAM IN PYTHON - PART 123456789greg@earth: /python examples Well, that seems to haveworked, but why does it countup to only 9 and then stop.Look at the output again. Thereare 10 numbers printed,starting with 0 and ending with9. That's what we asked it todo -- print the value of cntr 10times, adding one to thevariable each time, and quit assoon as the value is 10.Now you can see that, whileprogramming can be simple, itcan also be complex, and youhave to be sure of what youask the system to do. If youchanged the range statementto be "range(1,10)", it wouldstart counting at 1, but end at9, since as soon as cntr is 10,the loop quits. So to get it toprint "1,2,3,4,5,6,7,8,9,10", weshould use range(1,11) - sincethe for loop quits as soon asthe upper range number isreached.Also notice the syntax of thestatement. It is "for variable inrange(start value,end value):"The ":" says, we are starting ablock of code below thatshould be indented. It is veryimportant that you rememberthe colon ":", and to indent thecode until the block is finished.If we modified our programto be like this:#! /usr/bin/env pythonfor cntr in range(1,11):indentation shows the blockformatting. We will get intomore block indentationthoughts in our next tutorial.That's about all for thistime. Next time we'll recap andmove forward with morepython programminginstructions. In the meantime,you might want to considerinstalling a python specificeditor like Dr. Python, or SPE(Stani's Python Editor), both ofwhich are available throughSynaptic.print cntrprint 'All Done'We would get an output of.greg@earth: /python examples ./for loop.py12345678910All Donegreg@earth: /python examples Make sure your indentationis correct. Remember,full circle magazine #27is owner of,aconsulting company in Aurora,Colorado, and has beenprogramming since 1972. Heenjoys cooking, hiking, music,and spending time with hisfamily.10contents

HOW-TOIn the last installment, welooked at a simpleprogram using raw inputto get a response from theuser, some simple variabletypes, and a simple loop usingthe "for" statement. In thisinstallment, we will delve moreinto variables, and write a fewmore programs.FCM#27 - Python Part 1DevCD/DVDProgram In Python - Part 2Graphics Internet M/media SystemHDDUSB Drive LaptopWirelessI received an email from DavidTurner who suggested that usingthe Tab-key for indentation of codeis somewhat misleading as someeditors may use more, or less, thanfour spaces per indent. This iscorrect. Many Python programmers(myself included) save time bysetting the tab key in their editor tofour spaces. The problem is,however, that someone else'seditor may not have the samesetting as yours, which could leadto ugly code and other problems.So, get into the habit of usingspaces rather than the Tab-key.Let's look at another type ofvariable called lists. In otherlanguages, a list would beconsidered an array. Goingback to the analogy of shoeboxes, an array (or list) wouldbe a number of boxes all gluedside-by-side holding like items.For example, we could storeforks in one box, knives inanother, and spoons inanother. Let's look at a simplelist. An easy one to picturewould be a list of monthnames. We would code it likethis.months Sep','Ocfull circle magazine #28t','Nov','Dec']To create the list, we bracketall the values with squarebrackets ( '[' and ']' ). We havenamed our list 'months'. To useit, we would say something likeprint months[0] or months[1](which would print 'Jan' or'Feb'). Remember that wealways count from zero. To findthe length of the list, we canuse:print len(months)which returns 12.Another example of a listwould be categories in acookbook. For example.categories ['Maindish','Meat','Fish','Soup','Cookies']Then categories[0] would be'Main dish', and categories[4]would be 'Cookies'. Prettysimple again. I'm sure you canthink of many things that youcan use a list for.7Up to now, we have createda list using strings as theinformation. You can alsocreate a list using integers.Looking back at our monthslist, we could create a listcontaining the number of daysin each one:DaysInMonth [31,28,31,30,31,30,31,31,30,31,30,31]If we were to printDaysInMonth[1] (for February)we would get back 28, which isan integer. Notice that I madethe list name DaysInMonth.Just as easily, I could haveused 'daysinmonth' or just 'X'.but that is not quite so easy toread. Good programmingpractices suggest (and this issubject to interpretation) thatthe variable names are easy tounderstand. We'll get into thewhys of this later on. We'll playwith lists some more in a littlewhile.Before we get to our nextsample program, let's look at afew other things about Python.contents

PROGRAM IN PYTHON - PART 2be the space after 'time'.We briefly discussed stringsin Part 1. Let's look at string abit closer. A string is a series ofcharacters. Not much morethan that. In fact, you can lookat a string as an array ofcharacters. For example if weassign the string 'The time hascome' to a variable namedstrng, and then wanted toknow what the secondcharacter would be, we couldtype:strng 'The time has come'print strng[1]The result would be 'h'.Remember we always countfrom 0, so the first characterwould be [0], the second wouldbe [1], the third would be [2],and so on. If we want to findthe characters starting atposition 4 and going throughposition 8, we could say:print strng[4:8]which returns 'time'. Like ourfor loop in part 1, the countingstops at 8, but does not returnthe 8th character, which wouldWe can find out how longour string is by using the len()function:['The', 'time', 'has', 'come'].This is very powerful stuff.There are many other built-instring functions, which we'll beusing later on.The result from this code is:print len(strng)which returns 17. If we want tofind out where in our string theword 'time' is, we could usepos strng.find('time')Now, the variable pos (shortfor position) contains 4, sayingthat 'time' starts at position 4in our string. If we asked thefind function to find a word orsequence that doesn't exist inthe string like this:pos strng.find('apples')the returned value in pos wouldbe -1.We can also get eachseparate word in the string byusing the split command. Wewill split (or break) the string ateach space character by using:print strng.split(' ')which returns a list containingfull circle magazine #281,30,31]for cntr in range(0,12):print '%s has %ddays.' %(Months[cntr],DaysInMonth[cntr])There is one other thing thatI will introduce before we get toour next programmingexample. When we want toprint something that includesliteral text as well as variabletext, we can use what's calledVariable Substitution. To do thisis rather simple. If we want tosubstitute a string, we use '%s'and then tell Python what tosubstitute. For example, toprint a month from our listabove, we can use:print 'Month %s' %month[0]This would print 'Month Jan'. If we want to substitute aninteger, we use '%d'. Look atthe example below:Months Sep','Oct','Nov','Dec']DaysInMonth .days.days.days.days.days.days.days.Something important tounderstand here is the use ofsingle quotes and doublequotes. If you assign a variableto a string like this:st 'The time has come'or like this:st “The time has come”the result is the same.However, if you need to includea single quote in the string likethis:contents

PROGRAM IN PYTHON - PART 2st 'He said he's on hisway'code.you will get a syntax error. Youneed to assign it like this:st “He said he's on hisway”Think of it this way. To definea string, you must enclose it insome kind of quotes ‒ one atthe beginning, and one at theend ‒ and they must match. Ifyou need to mix quotes, usethe outer quotes to be the onesthat aren't in the string asabove. You might ask, what if Ineed to define a string like“She said “Don't Worry””? Inthis case, you could define itthis way:st 'She said “Don\'tWorry”'Notice the backslash beforethe single quote in 'Don't'. Thisis called an escape character,and tells Python to print the (inthis case) single-quote ‒without considering it as astring delimiter. Other escapecharacter sequences (to showjust a few) would be '\n' fornew line, and '\t' for tab. We'lldeal with these in later sampleWe need to learn a few morethings to be able to do our nextexample. First is the differencebetween assignment andequate. We've used theassignment many times in oursamples. When we want toassign a value to a variable, weuse the assignment operator orthe ' ' (equal sign):variable valueHowever, when we want toevaluate a variable to a value,we must use a comparisonoperator. Let's say we want tocheck to see if a variable isequal to a specific value. Wewould use the ' ' (two equalsigns):Don't worry about the if andthe colon shown in theexample above yet. Justremember we have to use thedouble-equal sign to doevaluation.if loop 12:The next thing we need todiscuss is comments.Comments are important formany things. Not only do theygive you or someone else anidea of what you are trying todo, but when you come back toyour code, say 6 months fromnow, you can be reminded ofwhat you were trying to do.When you start writing manyprograms, this will becomeimportant. Comments alsoallow you to make Pythonignore certain lines of code. Tocomment a line you use the '#'sign. For example:variable value# This is a commentSo, if we have a variablenamed loop and we want tosee if it is equal to, say, 12, wewould use:You can put commentsanywhere on a code line, butremember when you do,Python will ignore anythingafter the '#'.if loop 12:full circle magazine #28Now we will return to the "if"statement we showed brieflyabove. When we want to makea decision based on values ofthings, we can use the ifstatement:This will check the variable'loop', and, if the value is 12,then we do whatever is in theindented block below. Manytimes this will be sufficient,but, what if we want to say If avariable is something, then dothis, otherwise do that. Inpseudo code you could say:if x y thendo somethingelsedo something elseand in Python we would say:if x y:do somethingelse:do something elsemore things to doThe main things toremember here are:1. End the if or else statements9contents

PROGRAM IN PYTHON - PART 2with a colon.2. INDENT your code lines.Assuming you have morethan one thing to check, youcan use the if/elif/else format.For example:x 5if x 1:print 'Xelif x 6:print 'X6'elif x 10:print 'X10'else:print 'Xgreater'is 1'is less thanis less thanis 10 orNotice that we are using the' ' operator to see if x is LESSTHAN certain values - in thiscase 6 or 10. Other commoncomparison operators would begreater than ' ', less than orequal to ' ', greater than orequal to ' ', and not equal'! '.Finally, we'll look at a simpleexample of the whilestatement. The whilestatement allows you to createa loop doing a series ofloop 1steps over and over,while loop 1:until a specificresponse raw input("Enter something or 'quit' to end ")if response 'quit':threshold has beenprint 'quitting'reached. A simpleloop 0example would beelse:assigning a variableprint 'You typed %s' % response“loop” to 1. Then whilethe loop variable is less quitquittingthan or equal to 10, print theIn this example, we arevalue of loop, add one to it andcombining the if statement,Notice that when we typedcontinue, until, when loop iswhile loop, raw input'QUIT', the program did notgreater than 10, quit:statement, newline escapestop. That's because we aresequence, assignmentloop 1evaluating the value of theoperator, and comparisonwhile loop 10:response variable to 'quit'operator ‒ all in one 8 lineprint loop(response 'quit'). 'QUIT'loop loop 1program.does NOT equal 'quit'.run in a terminal wouldproduce the following output:Running this example wouldproduce:12345678910Enter somethingend FROGYou typed FROGEnter somethingend birdYou typed birdEnter somethingend 42You typed 42Enter somethingend QUITYou typed QUITEnter somethingendThis is exactly what wewanted to see. Fig.1 (aboveright) is a similar example thatis a bit more complicated, butstill simple.full circle magazine #2810or 'quit' toor 'quit' toor 'quit' toor 'quit' toor 'quit' toOne more quick examplebefore we leave for this month.Let's say you want to check tosee if a user is allowed toaccess your program. Whilethis example is not the bestway to do this task, it's a goodway to show some things thatwe've already learned.Basically, we will ask the userfor their name and a password,compare them with informationthat we coded inside theprogram, and then make adecision based on what wefind. We will use two lists ‒ oneto hold the allowed users andcontents

PROGRAM IN PYTHON - PART 2one to hold the passwords.Then we'll use raw input to getthe information from the user,and finally the if/elif/elsestatements to check anddecide if the user is allowed.Remember, this is not the bestway to do this. We'll examineother ways in later articles.Our code is shown in the boxto the right.Save this as'password test.py' and run itwith various inputs.The only thing that wehaven't discussed yet is in thelist checking routine startingwith 'if usrname in users:'.What we are doing is checkingto see if the user's name thatwas entered is in the list. If itis, we get the position of theuser's name in the list users.Then we useusers.index(usrname) to getthe position in the users list sowe can pull the password,stored at the same position inthe passwords list. Forexample, John is at position 1in the users list. His password,'dog' is at position 1 of thepasswords list. That way wecan match the two. Should password test.py#example of if/else, lists, assignments,raw input,#comments and --------# Assign the users and passwordsusers ['Fred','John','Steve','Ann','Mary']passwords -------------------------------------# Get username and passwordusrname raw input('Enter your username ')pwd raw input('Enter your password ')#----------------------------------------------# Check to see if user is in the listif usrname in users:position users.index(usrname) #Get the position in the list of the usersif pwd passwords[position]: #Find the password at positionprint 'Hi there, %s. Access granted.' % usrnameelse:print 'Password incorrect. Access denied.'else:print "Sorry.I don't recognize you. Access denied."pretty easy to understand atthis point.is owner of,aconsulting company in Aurora,Colorado, and has beenprogramming since 1972. Heenjoys cooking, hiking, music,and spending time with hisfamily.full circle magazine #2811contents

HOW-TOFCM#27-28 - Python Parts 1-2DevCD/DVDGraphics Internet M/media SystemHDDUSB Drive LaptopWirelessIn the last article, welearned about lists, literalsubstitution, comments,equate versus assignment,if statements and whilestatements. I promised you thatin this part we would learnabout modules and functions.So let's get started.ModulesModules are a way to extendyour Python programming. Youcan create your own, or useProgram In Python - Part 3those that come with Python,or use modules that othershave created. Python itselfcomes with hundreds ofvarious modules that makeyour programming easier. A listof the global modules thatcome with Python can be foundathttp://docs.python.org/modindex.html. Some modules areoperating system specific, butmost are totally cross platform(can be used the same way inLinux, Mac and MicrosoftWindows). To be able to use anexternal module, you mustimport it into your program.One of the modules that comeswith Python is called 'random'.This module allows you togenerate pseudo-randomnumbers. We'll use the moduleshown above right in our firstexample.Let's examine each line ofcode. The first four lines arecomments. We discussed themin the last article. Line five tellsPython to use the randommodule. We have to explicitlyfull circle magazine #29tell Python todo this.# # random example.py# Module example using the random module# import random# print 14 random integersfor cntr in range(1,15):print random.randint(1,10)Line sevensets up a 'for'loop to print 14randomnumbers. Lineeight uses therandint() function to print arandom integer between 1 and10. Notice we must tell Pythonwhat module the functioncomes from. We do this bysaying (in this case)random.randint. Why evencreate modules? Well, if everypossible function were includeddirectly into Python, not onlywould Python becomeabsolutely huge and slow, butbug fixing would be anightmare. By using modules,we can segment the code intogroups that are specific to acertain need. If, for example,you have no need to usedatabase functionality, youdon't need to know that thereis a module for SQLite.However, when you need it, it'salready there. (In fact, we'll be7using database modules lateron in this series.)Once you really get startedin Python programming, youwill probably make your ownmodules so you can use thecode you've already writtenover and over again, withouthaving to re-type it. If you needto change something in thatgroup of code, you can, withvery little risk of breaking thecode in your main program.There are limits to this and wewill delve into this later on.Now, when we used the 'importrandom' statement earlier, wewere telling Python to give usaccess to every function withinthe random module. If,however, we only needed touse the randint() function, wecontents

PROGRAM IN PYTHON - PART 3can re-work the importstatement like this:from random import randintNow when we call ourfunction, we don't have to usethe 'random.' identifier. So, ourcode changes tofrom random import randint# print 14 random integersfor cntr in range(1,15):print randint(1,10)FunctionsWhen we imported therandom module, we used therandint() function. A function isa block of code that isdesigned to be called, usuallymore than once, which makesit easier to maintain, and tokeep us from typing the samecode over and over and over.As a very general and grossstatement, any time you haveto write the same code morethan once or twice, that code isa good candidate for afunction. While the followingtwo examples are silly, theymake good statements aboutusing functions. Let's say wewanted to take two numbers,add them, thenmultiply them, andthen subtract them,displaying thenumbers and resultseach time. To makematters worse, wehave to do that threetimes with three setsof numbers. Our sillyexample would thenlook like the textshown right.#silly exampleprint 'Adding the two numbers %d and %d print 'Multiplying the two numbers %d andprint 'Subtracting the two numbers %d andprint '\n'print 'Adding the two numbers %d and %d print 'Multiplying the two numbers %d andprint 'Subtracting the two numbers %d andprint '\n'print 'Adding the two numbers %d and %d print 'Multiplying the two numbers %d andprint 'Subtracting the two numbers %d andprint '\n'%d ' % (1,2,1 2)%d %d ' % (1,2,1*2)%d %d ' % (1,2,1-2)%d ' % (1,4,

The articles contained in this magazine are released under the Creative Commons Attribution-Share Alike 3.0 Unported license. This means you can adapt, copy, distribute and transmit the articles but only under the following conditions: You must attribute the work to the original author in