100% found this document useful (1 vote)
4K views

Python Class 6

Uploaded by

sashankraj27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
4K views

Python Class 6

Uploaded by

sashankraj27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS LEARNING IN THIS CHAPTER ® Introduction to Python, 1 Varabes in Python 1 Basic data types in Python © lastaliog Python 1 Working in Script Mode put) Function 1 Components of Python Window Datatypes . Have you ever tried making pasta on your own? Figure 8:1 shows a recipe to make Tomato Pasta. It solves the problem of “how to make Tomato Pasta?” The recipe sa set of instructions on what to do, how to do, and when to doit. eset of instructions usesingredients (inputs) tomake Tomato Pasta output). Fue 81 Making Tomato Pata _Adéing all the required ingredients tothe recipe is input. Simmering theingredientsis processing, andthe product thatyouget afterprocessngis output, whichin our casefspasta. Likewise computer also works in three stages. To get the work dane on a computer, you enter the raw data (Gout), computer operates on thisdata (processing), and the desired result is obtained (Output). ea ‘To get the desired output from the computer, you kein instructions to the computer using diferent programming languages. There are some spect computer languages, which ae used to write programs. Some ofthe popular ‘examples of Programming nguages are Python, C, Ci, LISP, Pascal, Java, PHP, etc. Moder computers follow the set of operations called programs. In simple words, a program i 3 sequence of instructions that specifies how to perform a computation. These programs help a computer to perform wide range oftacks. In this chapter, you wil lean the basics of Python programming language, which is one of the most powerful, high level programminglanguages. htps:pntmis.comfogptektibasic ane. ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS ~al ® INTRODUCTION TO PYTHON Python is a simple Programming language that is used to write codes for the computer programs. Python was created by Guido Van Rossum when he was working at Centrum Wiskunde & Informatica (CWI), which is a National Research Institute for Mathematics and Computer Science in Netherlands. The language was eleasedin 1991 Python sahigh level programming language. ‘Some ofthe features that make Python so popular areas follows: > Itisaneasy toleam general purpose programming language. > Itisa platform independent programming language, which means it can be used on any machine and in any operatingsystem. Ithasasimple syntax. Pythonisa case sensitivelanguage. Itisaninterpretedtanguage. Itisfreetouseandeven ree for commercial products. ‘APPLICATIONS PYTHON PROGRAMMING Pythonis a popular andeasy tolearnlanguage.Itcanbe used to: Buildawebsite Develop games. Programrobots Perform scientific computations Developartfcialinteligence applications ® INSTALLING PYTHON Python can be easily installedon your computer following thegivensteps: 1. Obtain a Python Distribution: Youcan download Python distributes from: ‘www python.orgidownload. Forthischapter, wehaveused Python3.7.4 vvyvyy Figure #2: Downloading Python htps:pntmis.comfogptektibasic 218 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS '2. Python installation Process ‘After downloading the Python distribution all youneed to dois, toexecuteit. Double-click the downloaded installer software. lick on Run in the Dialog box, and the installation process starts. Keep following the instructions and clickingon the Next button untilyousee the highlighted Finishbutton. ‘After youhave installed Python, the IDLE screen lookslike this: Python 3.7.4 (tags/v3.7.426099991126, Jul 6 2019, 19:29 122) (MSC ¥.1916 32 bit (Intel) on win32 type "help", “copyright, "credits" or *License()* for m lore infornation, Figure 8: Python 3.74 Shell Window ‘OnWindows machines, the Python installations usuallyplacedin C\Python 37.4 folder, though youcan change this when youarerunning theinstallr. .» COMPONENTS OF PYTHON WINDOW Justlixeany other application window, Python window has the following components: Python 3.7.4 (tags/v3.7.4r008581120, Jal 8 2019, 1 122) (sc v.1916 32 bit’ (Intel) ] on win32 ‘Type "help", “copyright™, "credits" or *License()* for m lore information. ee =a. sail ~_ Bm ‘This is the area that displays the name of the application and the document. It also contains Sass", commandbuttonsike minimize, maximize restore, anddose. eer MenaBar eee ‘The menu bar consists of various merus with efferent options. The common menus you wil le === ‘working with inthis chapter are le, Et, Shell, Debug, Options, Window, and Help. ‘Working with ile Mena "Tis mens used to work wth he options rested tothe caren wed te. 1 (EL 5 includes sub options like opening a new file, opening an existing file, viewing | tax “™=™) receniyused fies, saving thefles, dosing thefles, andexting the application. Workinguwith Edit Menw ‘This menu i generally used to edit the fein use. You can cut, copy, oF past the selected text. Youcanalsosearchfor apartculartextorphrase,andeven replaelt withsome othertext. Cenpaer wn KiPS htps:pntmis.comfogptektibasic site ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS Werking with Help Mens (HieSieemes | [tere roca ‘To gethelp related to any topic of Python, press Fikeyorclickon __ ABest 1OLE thetlelpmen. OL He SctysAreccThiskthesreawtinsyoulypayourcode, ence Ft ‘Status Bar: The Status Bartels you the curent status of YoU Figs 87: Hep ems contrlicursar onthe window. ‘After installing Python, you areready to workonit. You can workin Python intwoways: > i incerseivemode > i SeriptMode Python Programmingin interactive Mode Inthe interactive mode of Python, theinstructions are executed, ine by ine, giving the output. {In this mode, the commands re typed next to the Python Command prompt (2>>)-For ‘example, ifyoutype3+6nexttothe Python Prompt, twillgiveyou theresultas3. ‘Toworkinthe interactivemode, follow the process given: > Glckon the tartbutton > scroll down to Python 3.7 >IDLE(Python 3.7) Itwillopen the Python shellwindow where youwillsee the Python prompt(>>>)- el Eython 307-4 (Cang/ed 7 42e0S309li26, Jul 8 2018, 19329 £2) (wee va1sie 32 bit fe Theap™, Pot credits” or *icense()* for m Figure 0: Python Shell Window > Type the following commands next to Python prompt and Python wallimmediately - _slvethe output asshownin Figures. ¥ >>>twelcome Lo python world? >o>10 >ooa2.78 >tat >oo40>>10+20 htps:pntmis.comfogptektibasic ane ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS interactive mode benef for testing code where youtype the commands, one ata || Yon pes Fey to time, and get thereault orerrorinmediately werent. Use of interpreter In the interactive mode of Python, the commands are executed line by line. When you type a command next to the python prompt (>>>) and press the Enter key, the interpreter converts the command into machine language. After processing, the interpreter again converts the machine codeintohuman readable form (output). Using print() function ‘The print() function is used to display the output of any command on the screen. It can ‘also beused toprint the specified messages. Forexample: >>>peil HeL1o World") wildisplay Hello World ython (eo, Dal ¥ 2019, LBVZEY EC W-1BI6 32 BIE ‘Figure 10: Using print) function Python isa case-sensitive programing language. It means that Python differentiates between capital and smallleters. For example, ? it (Peapital) and print. (p small) are two different things for Python, where pint. isa valid command in Python, wile Pint isjustawordandnota command. ‘You can also pass more than one argument tothe prin. () function. Insucha case, the arguments are separated by commasasshowninFigures.11. ST, Fython 3-1-4 (age/v3.7 AreOwISO12e, dalW BOTS, 19 BY WS v-IDIC 32 Ble >>> print *10%8-0130"2/10+", 10%8-50430%2/10) b> prints plus 3 eel 5, 45 into =, 999) htps:pntmis.comfogptektibasic 58 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS ‘To evaluate an arithmetic expression, it is not necessary to use the print() function. If you type an arithmetic “expression at the Python prompt and press the Enter key, the interpreter automatically evaluatesitand shows the result Inthiscase, theinterpreteractsasa simple calculator. The expressionsare evaluatedusing operatorslike +,-, * Ite. The asic BODMAS rulesare followed for performing calculations. For example: leython 3.7.4 (tags/v3.7.4:0093991120, Jul 2019, 19: (intel) } on wins? type "help", "copyright", “crodits™ or "Liconso()* for more information. b> 10170 30 b> as/e ns bs 61/8 o >>> 43°78.7 3542.5 sf 22) (MIC v.1916 32 bit Type the following expressions, one by one, next to the Python prompt and note down the output inthe table “givenbelow: i Write the statement nextto the Python promptusing print( function to get the followingoutput: 2. Pythonworksintwo modes: Interactivemode and Script mode. 1b. Interpreterisalanguageprocessor. D VARIABLES IN PYTHON If youneedtostore some food for future use, what willyourequire? Wel, you willneed acontainero store the food. ‘Similarly, when you are working with the values in Python, you require some storage to hold values fr later use. ‘Such storage locations ae known. variables. variable cantor only one data value at atime. Whenanew valueis storedinavariable,itspreviousvaluegetsovervitten. htps:pntmis.comfogptektibasic ete ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS A ‘The Assignment Operator(-) Values are assigned to variables using assignment operator| 25tothevariablex. For example, the statement: Observe the folowing codesto understand the use of assignment operators: 2-10 Value 1Disassignedtothevariablea 1:20 Value Z0isassignedtothevariableb carb #Thenumbersare added and the valucisassignedto the varable te. 30 assigned othe variable c. 3-€10 _#Value20(30-10)is2ssigned to the vanablea.So,now the value of the variables 20,anénot 10. ‘Rulesto writethe variablenames ‘There are certain rules in Python which have to be followed to form valid variable names. The rules for valid Identifier (variablename)are: > Avariablenamemuststart with an alphabet (capital orsmalt)oranunderscore(_). > Avariablename can consist of alphabets, digits, and underscore. No other characterisallowed. > APythonkeyword cannotbe usedasavariablename. > Avariablenamecan beof any length. > Variable namesare case sensitive (e.g., Ageandageareclferent variablerames). [Examples of some valid vaiablenamesare: Class, emp code, Lotnalary, minvalue, bal Cee, age1980, a45e Following are examples of some invalid vaniablenames: "VarbIs Name — Taployee cece | Space ¬ alowed na variable na TOcode Variable name cannot start witha ait A.n.c. Tid | -tenot alowed ina variable name, Ancerta Specil characte Fe not alowed ina variable nome. cise “ee” a keyword in Pyihon, so i cannot be wed a2 vorabie name. Mavariableisbeingused without assigning value Leith varableisnot defined given eer. competes wn KiPS htps:pntmis.comfogptektibasic 78 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS ystee [Figure 613: Undefined Variable ror “The above code gives an error because the variable x is used in the print() function without being defined. ‘® WORKING IN SCRIPT MODE Interactive mode is preferred for small programs, where only 2 few commands are tobe executed. This is because the output in interactive mode fs compressed between the statements andmay create confusion while wrtinglong programs. For writing lengthy programs in Python, Script made Is used, Using this mode, we can createand edit Python programs. Inthismode, we can save ourflesothatitcan beused later. The complete scriptiswritteninaneditor, suchasa NotepadinWindows. 1. Create Module/Script/Program File: | OpentDLE Python. Ji. Glickon the File> New Filein IDLE Python Shellasshownin Figure 8.14. i In the new window that opens, type the commands you want to save as 2 ‘programas shownin Figure&.15. ister aim ot san wanes 32 “Figure 6.15: New Window ‘yay ptm. htps:pntmis.comfogptektibasic ane ‘sm6i24, 12:13PM a Iv. Clickon the File> Save, and save the fle with thename'prog!.py' where pyisthe extension for Python files. (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS ttt CT) mee ‘Flqure 8.16: Saving a Fie 2. Run Module/Script/Program File: ‘After the Python program files created, you can runthe program by following thegivensteps: > OpentDLE Python Shell. > Clickonthe Fle» Open. (Ifthe fileis already opened, you candirectly follow thenextstep)- > ClickontheRun> Run Module or press F5 key. “Figure 8.17: Run Module > ttwillexecuteall the commands youhave stored ina separate Python Shell window. Observethe difference between the Script mode and theInteractivemodeas shown Figure8.18, Fo [Be Est sted Gey Opens anton ep ‘a=10 python 3.7.4 (tags/v3.7.4:20935) be20 19:29:22) [Msc v.1916 32 bit (x cratb ‘Type "help", "copyright", “cred. ee a ae eT, Bes MOR a SIRT a RESTART: C2/Users/Dine: ‘Python/B?7/progl .py ======== the sum of the numbers is: 30 = a Figure 8.18: Program Output in Interactive Mode compar win KIDS: htps:pntmis.comfogptektibasic one ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS 1. witeaprogramto prin geneadetats about yourschoatinfve nes 2. Wit aprogramte caladstethesum of wa gvennumers. ® DATATYPES ‘Suppose, you have planned a holiday trip during vacations, and you have to book tickets for your family members. The first action that you need to take isto fill a form to get the reservation done, where you need to give your required details like train number, date of journey, name, age, etc. Here, every piece of data that you enter is of 2 specific type; As your name isa String type, age is a numeric type, and date of journey is of date type. Similarly, in Python, one must specifyina program, what kind of values willbe storedina specific variable. ‘® BASIC DATA TYPES IN PYTHON InPython, a data type represents the type of data stored ina variable. The data stored in memory can be of many types. Python has various standard data types based on the typeof value. For example, a student'smarks are stored asanumericvalue, whereas his orheraddressis stored as alphanumeric characters. ‘Thebasic data typesusedin Pythonarementioned here: int (Integer): Represents integral numbers (numbers without any fractional pat). There ae three typesofintegers inpython: Integer type Description integer int) ‘Stores values in the range of - 2147483648 to 2147483647. ‘Long Integers (long int) | Support the values that le beyond the range of Integers. represents logical values in the form of True and False. In Boolean, PomEMRRONY represents False and 1 represents True. float: Represents floating point values (numbers with fractional part). The fractional partof afloating point number ‘may beO.as well. Examples of floating point numbersare, 314-486, 180,¢tc. ‘str (String): A String datatyperepresents strings of characters enclosed withinsingleor double quotation marks" on™ Examplesofstringsare, Hella,"Myname",'2 18 "Peace’,ete. Some examplesof datatypesin Pythonare: NO Value [pata Type 1 15 int 2 73 oat 3_| Computer Appicaion | — st 4 Ba boot htps:pntmis.comfogptektibasic 10118 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS OT ®D Input() FUNCTION Jnput() function's used to accept the value fora variable from the user. To inputinteger and flat values, we can use int()orloat() along with input). eT-A3e0ss882126, Tel € 2015, 19428122) MEE W.IOIE 22 iS, Soredica™ or *2icenae()* for mote Jntormation, ‘Figure 8.19: Using input) function InFython, input function takes one string argument. Thismeans that whatever valueis being entered by the user, itwillbetakenasa stringargument. Program 2: ‘Figure 820: String Operator ‘Observe inthe above program, when youadd the two numbers, you do not get the sum. Rather the numbers are joined together andare printedasastring. Program 3: Rlagrelgitt, Screditat or *Licenma)® for mute Information, ‘Figure 8.21: Type Value Err Here, inthis program, when youttrytomultipy these two values, ou get an errorin the program. Thisis because the ‘strings values cannot be multiplied together. ae wi KIS: htps:pntmis.comfogptektibasic se ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS m= (eas. 7 cree, I OTOH Be Figure 822. Sum of Mumbers ‘Observe, when you use int) function, the values are converted to integers and are added. Program > Theprint)functionin Pythonis used to print amessage orvakieon the output device. > Iconvertsthe message or an objectinto astrng before writingit onthe screen. > ‘Reanhavemultipleparameters. > Kt supports multiple escape sequences to format the output, e.g, ‘\n’ (new line), “k' (tab space), and '¥ (coriage return). Using separators with print() function Using ‘operator : When you use'" operator as the separator among the values the values are. space betweenthem. htps:pntmis.comfogptektibasic rane ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS Q eat foe be alc ib=20 e=100 print (a,b,c oe Output Using (tab space): When youuse "W escape sequences the separator among the values, the values are displayed witha tabspace between them. Program: ‘re 0.26: Using Escape Sequence Using (Newline character yee fintsant pe tangs) Serre ‘Oaput Anewline character n Pythons used to end line and start a newline. In Python, the new linecharacter canbeused ‘withthe input function and with the print function. "nis newline character usedin Python. Program’: Se fe tone be toe eo a=10 fp=20 =100 [print ta,\n",b,"\n",e) ‘Figure 27: Using Wn Escape Sequence ucerooenny ,Seopyeis, exes} sassy £10000 Output ‘Let us consider another example. Suppose you want to make a program to accept the name, age, and marks of 2 student For this, add the folowing codeinthe Python crpt file: Program 10: htps:pntmis.comfogptektibasic 1318 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS "Nowinthe Python script file, addin! with theinput and print function: Figure 8.29: Program with Escape Sequence In the above output window, in order to give a better understanding, the text and the values are placed one after ‘another. > Pythonwascreatedby Guide Van Rossum when he was working at Centrum Wiskunde &Informatica(CW!). > Pythonisahigh levellanguageused to write codes for the computer programs. Interactive mode is benefical for testing code where you type the commands one ata time and get the result or cerorimmediately. Script mode's used forwniting lengthy programsin Python. ‘Theptin( function sused to display eoutput of any commandonthe screen. Pythonhasvariousstandard data typesbasedonthe typesof valuesstoredin variables. Input( function susedtoacceptthe valueforavarable fromtheuser. OO SECTION -A A. Fillin the blanks. 1 refers to the grammatical rules to be followed while writing a program in any language. 2 Python was created by 3. menus generally used to edit the file in use. 4. Inthe interactive mode of Python, the instructions are executed —__ 5. Alga named memory location that stores the data. 6. Python cannot he used a6 2 variable name, TEOOBY) © werctic + syntax + Guido Van Rossum = Eat + Line byline» Keyword htps:pntmis.comfogptektibasic sane ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS a 1B. StateTrueorFalse. 1. Toevaluateanarithmetic expression itisnot necessary to use print( function. ‘Avariablename can consist of alphabets, digits, and underscore. ‘Aseriptisa programthat youtypein Python. InPython,onlyone typeof data canbe storedin memory. Print function isused toaccept the value ofa variable fromthe user. 6. Thestringvaluescannothe multiplied together. = 7. When weuse' operatoras the separatoramong the values, the values are displayed witha space betweenthem. GApplication-basedquestions. 1 _Kritka's computer teacher has given her anassignment to display the names ofthe fruts separated witha tab, _pacein Python. Whichseparatorshould she use withthe print{) function? 2. Amanis working on his mathematics project work. He has to perform some quick calculations. Which mode of Python programming should he use fordoing them? SECTION: 8 1. Which ofthe following data types is not supported in Python? 23. Numbers string cust 2. Whena new valu is stored in a variable, its previous value gets : a. Accepted ». Overwritten <-Overiopped 3. Values to varables are assigned sing the operator. 2. String print) Assignment 4. Thedata type for 124 shouldbe : aint float esr 5. Togo stab space whe printing the statement, yotsuee——______. ate bre Tobey 6 The area where you type the codes called 2. Work area bs. Worksheet Script area 7. >>> pint(10'+20) wal give the output 2.30 1020 «2010 Crogan wn KIDS: htps:pntmis.comfogptektibasic 15118 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS 3. Explainthe different working modesof Python. 6. Whatisaninterpreter? Howisit different froma compiler? htps:pntmis.comfogptektibasic 1618 ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS Pie ag Learning While Playing A. Write the output forthe following code of statements. >> printing, eth’) >> print(India’, Wt, Det) >> >print(India’, i, Delhi) >>sa-10 >>>b-20 peoer(aebyt >> >print(c) >>> ant >>> be20" >>> prints) £ >o>a-10 >>>b-20 >>> prints) ange B._Rewritethe following statements after correcting them. sootdre — >>> Prntnd’) ee >> Print(age) aso, >eoato soobe20 seoaib=c >>rprnt(o) aoge C_ Write the following code in the Script mode of Python and write theoutputinthe given box. one=1 two=2 three=one + wo hellowortd = ella +" + world Print(helloworld) tenon wn KIDS htps:pntmis.comfogptektibasic wine ‘sm6i24, 12:13PM (CHAPTER 8 - INTRODUCING PYTHON (clas 8) Pages 1-18 - Flip PDF Download | FipHTMLS > ‘A. Givetheoutput ofthe following commandsin the Interactivemode of Python: 1 23.485 2 445/398-5 '._Whtethecode for the following programs using the Script Mode: 1. Writeaprogram to find the product of twonumbers xandy, where x=150.and y=200, 2. Ittakes 3 hours to drive a distance of 192km on.a motor way. Create 2 program to calculate the average speedinkm/h? 3. Tocaleulateand print the circumference and area of acirle. 4. To input the roll number, name, and marks in five subjects of a student. Calculate the total and percentagemarks of the student. ro cone oy Divide the class into two groups and conduct a group discussion on the following topic: Interactive mode vs Script mode MR tecttna For more, To know more about programming in Python vist the following links: netpss/iwww.tutorialspoint.comipython] https:/fwww.w3schools.com/python| htps:pntmis.comfogptektibasic 1818

You might also like