🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Adobe Scan Aug 09, 2024.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

SweepingRuby

Uploaded by SweepingRuby

KV Business School

Tags

python programming programming languages computer science

Full Transcript

INFORMATICS PRACTICES 28 2.2 Python - Pluses is competing with e ever-popular...

INFORMATICS PRACTICES 28 2.2 Python - Pluses is competing with e ever-popular yet it Though Python language came into being inearly1990's, index. languages such as C, C+t, Java ctc. in popularity Let's see what are these pluses of Python. orientedlanguage with very simple use object 1. Easy to Use Python is compact and easy to syntax rules. fewer lines of code and simpler syntax ac language - 2. Expressive I'ython is an expressive programming languages like C++, Java etc. Language compared to other popular compiled language. 3. Interpreted Python is an interpreted language, not a Language functionality is available through various *. I1s Completeness For most types of requiredlibrary'. Thus, it is also called - Python follows modules of Python standard "Batteries Included" philosophy. 5. Cross-platform Python can run equally well on variety of platforms Windows, Language Linux/UNIX, Macintosh, supercomputers, smart phones etc. 6. Free and Python language is freely available along with its source-code. Open Source 7. Variety of Usage/ Python has evolved into a powerful, complete and useful language over Applications these years. These days Python is being used in many diverse fields/ applications. 2.3 Python - Some Minuses (So Human Like) Although Python is very powertulyet simple language with so many Perfect Programming language. advantages, it is not the Let's see what these are: 1. Not the Fastest Pvthon offers faster development times but Language compared to some compiled languages. execution-times are not that tast 2. Lesser Libraries Python offers thon C, Java librarysupport for almost all library is still not competent with languages likecomputing programs, C, Java, Perl etc. but its 3. Not Strong on Python interpreter is not very Type-binding strong on catching Type-mismatch' issues. 4. Not Easily Because of its lack of Convertible difficult to translate insyntax, other Python is an easy inbut programmi language definedngsyntax. other larnguages have to structured language. prograt because most This is 1. If you install Python through Anaconda Python Distribution it 2. Python even has versions that run on different languages suchloads most as Java libraries and Jython). NET packages with Pythol. Chapter 2 GETTING STARTED WITH PYTHON 29 So, now you are familiar with what all Python offers. As a NOTE free and open-source language, its users are leaps and bounds. growing by Python is an interpreted language, that is, all the commands you As per Jan 2020 popularity index, Python was 2nd most write are interpreted and popular programming language after JavaScript. That is the executed one by one. reason, it's part of your syllabus. Together well make it playful Python ;). 2.4 Working in Python Before you start working in Python, you need to install Pythorn on your computers. There are multiple Python distributions available today. > Default installation available from www.python.org is called CPython installation and Comes with Python interpreter, Python IDLE (Python Gu) and Pip (package installer). > There are many other Python distributions available these days. Anaconda Python distribution is one such highly recommended distribution that comes preloaded with many packages and libraries (e.g., NumPy, SciPy, Panda libraries etc.). IDE etc. Of these, > Many popular IDEs are also available e.g., Spyder IDE, PyCharm Spyder IDE is already available as a part of Anaconda Python distribution. To install any of these distributions, please refer to APPENDIX A. ready to work on it. You can work Once you have Python installed on your computers, you are in Python in following different ways : (i) in Interactive mode (also called Immediate Mode) (ii) in Script mode 2.4.1 Working in Default CPython Distribution interpreter, Python IDLE (GUI based) The default distribution, CPython, comes with Python mode, you need to open Python and pip (package installer). Towork in interactive as wellas script IDLE. IDLE) 2.4.1A Working in Interactive Mode (Python command- one command at a time, and the Interactive mode of working means you type the gives you output. In interactive mode, Python executes the given command there and then and prompt >>>. command you type the command in front of Python prompt, it will give you result as 7: For example,if you type 2 + 5 in front of Python command/expression given here >>> 2+5 + Result returned 7 by Pyshon site/pydatalog/pypl/PyPL-PopularitY-of-Programming-Language. 3. Source : https://sites.google.com/ INFORMATICS PRACTICES - XI 30 To work in interactive mode, follow the process given below: (Python GUID [see Fig. 2.1(a)l (i) ’Python 3.x.X ’ IDLE Click Start button - All Programs line) Python (command Or Click Start button ’ all Programs ’ Python 3.x.x -’ Python 3.6 3.632-bit) e DLE (Python Python3.6 (32-bit) Manuals (32-bit) B Python 3.6 B2 Click here to open IDLE Module Docs Scit Oiceeez007 P Python 3.6 Python's own interactive environment. Back AfHPrograms Figure 2.1 (a) Starting Python Shell. (ii) It will open Python Shell [see Lé Python 3.6.5 Shell Window Help Fig. 2.1(b)] where you'll see File Edit Shell Debug Options [M5C v.1900 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) the Python prompt (three > Python 3.6.5 32 bit (Intel)]on win32 signs i.e., >>>). "license()" for more information. Type "copyright", "credits" or Python command prompt front of (iii) Type commands in (See >>>) this Python prompt and In interactive mode, you can type commands in front of it Python willimmediately give you the result. (see Fig. 2.1(c)] Figure 2.1 (b) Python's interactive interpreter - Python Shell. NOTE Python 3.65Shel# File Edt Shell Debug Dptions Window Help The interactive interpreter Prthon 3.6.5 (v3.6.5f59cD932b4, Mar 28 2018, 16:07:46) IMSC v,1900 32 bit (Intel)] on win32 also called Type "copyright", "credits" or "licerse()" for more information. of Python is >>> 2+5 Python Shell. 7 >>>5= 13 This way of giving See, various commands typed on prompt >>> and name or expression in 13 front of >>>is called >>>5+ 20 Python immediately displayíng. 33 returned the output. >>> Ln10 Cot: 4 commands and their output in Python Shell. Figure 2.1 (c) Interactive frontof Chapter 2: GETTING STARTED WITH PYTHON 31 2.4.1B Working in Script Mode (Python IDLE) What if you want to save all the commands in the form of program file and want to see all output lines together rather than sandwiched between successive commands ? With mode, you cannot do so, for : interactive ) Interactive mode does not save the commands entered by ou in the form of a program. > The output is sandwiched between the command lines [see Fig. 2.1{c)). The solution to above problems is the Script mode. To work in a script mode, you need to do the following : Step 1 : Create Module / Script / Program File Firstly, you have to create and save a module / Script / Program file. To do so, follow these instructions : () Click Start button ’ All Programs ’ Python 3.xx ’ IDLE. (Fig. 2.2(a)] (i) Chck File -’ New in IDLE Python Shell. (Fig. 2.2(a)] (iii) In the New window that opens, tvpe the commands vou want to save in the form of a program (or script). [ig. 2.2(b)] NOTE For instance, for the simple Hello World program, you'll need to type following line : You can display as wel as print values in interactive mode, but print (" Hello World ! ") for script mode, print{ ) command 7% Python Shell is preferably used to print File Edit Shel Debug Options Windows Help results New WndowCN Dpe... Ctrh Recent Files Dpen Module.. At+M Cass Browser Alt-C Path Browser ie Untited To see File Edit Fomat Run Options Window Help Working in ython iDLE Save Ctre5 in acion Save As. Ctrt+ ShiYtS Save Copy As.. At+ Shift+S print( "Hello Word! Priet Window Ctr+P Close Alt+F4 Exit Ln2 Cot 21 Scan QR Code (a) File ’ New command in Python Shell (b) Type commands in new blank file (scrnpt mode) Figure 2.2 (iv) Click File ’ Save and then save the file with an extension.py, The Python progràms nas -py extension (Fig. 2.2(c)]. For instance, we gave the name to our program as Hello-py. appears on sCTeen) but that 4. Python GUI Shell IDLE lets you save the entire session (commands followed bv their results -asit is not the Python program/script containing only the instructions. INORMATCS 32 t t Fomat Run Ootons Windos He Nie Wndga Cpen.. sito Recent Fles Open iodle At-M Cass Brtwser Save the Python Path Browser programsoriptfile withPY extension Save As. SaveCopy As AR-Shst-S Prirt Wndge Cose At-F4 Ext SeEne yche fies Ctrh-Q -py If you forget to give won't be extension, Python able to run your script mode). extension with File ’ Save command (Scipt rigure 2.2 (c) Save file with.Dy and the saved file will have.py evtensi Now vour program wouldbe saved on the disk Step 2 : Run Module / Script/ Program File instructions After the program/script file is created, vou can run it by following the given () Open the desired program/script file that you created in previous Step 1bv u IDLE's File ’ Open command. If the program / script file is already open, you can directly move to next instructit (i) Cick Run ’ Run Module command [Fig. 23a)] in the open program/script file's window You may also press F5 key. (ii) And it will execute all the ie Heloy-Uers EdupAooData9 commands stored in Fle Edt FomaRun Options Windoa Help Click at Run-’Run Mae module / program / script Python Shel print "e lo Wan Check odle At-X Command to run he a that you had opened and program/son show you the complete output in a separate Python Lr? Cot Shell window. [Fig. 2.3(b)] Figure 2.3 (o) Run ’ Run Module command (Script mode. Aython 3.65 Shel Fle Fdit She Debug ptions indow Help Tvoe 26Sw36.5.f59c0932b4, "copyright,"credits Mar 28 2018, or icense( 16:07:46) [MSC for more information. v.1900 32 bit (tntell) on win32 =RESTART: CAUsers\Edu This is the output Python produced Hello Word! by the applied Run when Moduleyou 5-32\Hello.py Command (Youcan see complete module in previous fiqure) Figure 2.3 (b) Output of a module-run is shown in the shell window. Chapter 2: GETTING STARTED WITH PYTHON As you can see that with script mode, you can store all commands together in the form of module / program / script and can get all output lines together. (No more command-outp sandwiching :). 2.4.2 Working in Spyder IDE Spyder is a powerful interactive development environment for the Python language with advanced editing interactive testing, debugging and introspection features. In fact, spyder3 DataCamp community recommends Spyder IDE as the most preferred choice out of top 5Python development environments recommended by it. Spyder IDE comes preloaded with Anaconda distribution. It is my personal NOTE favourite for working on Python. The IPython console Tolaunch Spyder IDE: takes commands in front () Launch Anaconda Navigator of in[ ]prompt and often shows output with Out[ (i) Click on Spyder tile in Anaconda navigator (refer to Fig. 2.4) lines. [Alternatively,you can directly click at Start button -’ Programs ’ Anaconda (folder name) ’ Spyder Spyder Interface Once the spyder is loaded, you willsee following interface : Conscles iect Iook e Hde Fle Edt Seach ebug CUersdo Edr-cers Eáp,evdeeT 3SDyder Editor Here yoU Can get help of any 5 This is a temporary script file. objet by pressing Cr+I in front of , ether an the Edtor or the Console. reare Freleye Python 3.6.4 (Anaconda, Inc. (defsult, Jan 16 2018, 10:21:59) [SC v.1900 32 bit (Intel )] Type "co0yright, "credits" or "license for Bore inforestíon. IPython 6.2.1 -- An ethgnced Interctive Python. Editor pane In (1): print("hello") To create scripts, hgllo Work here Ir (2]: IPython Console To work in interactive mode, type command(s) here and it will give try the output below the command End-gl ngs: C Ecedmg - Fiqure 2.4 Fie... PyctaT es Fiqure 2.5 bi Atue ye have typed your script (and saved it), you can run your seript Cliking at Run icon (see below) on the toolbar Or by eliking at Run -> Run command Or by pressing shorteut key F5. NOTE ckc Sureto famitar witlh different ways of working in Please make befare consolet in IPython SCTipt.So discusuion of Python. You can your thot 6. you run Cursor in to have console. INFORMATICS PRACTICts- 34 Chacter command(s) in the Interactive Mode type your command there itself IPython See conso, To work in interactive mode in pane of spyder window. It will SpyderIDE, give youthe output of the figure24 above where we typed command : print("Hello") it. the result beloww in the IPython console pane and it gave us Script Mode commands in the editor pane. type your script's To work in script mode in Spyder IDE, File... ’ To start a new Scriptfile, click File -’ New Save as... or File ’ command File ’ Save > To save current script, use -py. > Python scripts have File extension as Python Files. select file type as > Please make sure to Seve file Chsp 01 « CS Python X (2018) File Edt Searcir Source Fun Deou New folder 9 New file... Ctrl-N Create new script file Date moat e: DOYniDads Name Recent Places PHW Open.. Ctrl+0 scratchwork- Short Open last closed Ctri+ Shift+T Libraries 2. Open recent Documents Save Ctri-S tMusic Ctrl-Alt+S Save commands Save all Make sure to select Savve S... Ctrt- Shift+S Type file Save as type by Homegroup name here clicking this arow, as: Save copy as.. Revert Comnputer Python files Locsi Disk (C:) Fide name HW.p Save as typePython files To see Working in Spyder IDE a Hide Folders in action Figure 2.5 After you have typed your script (and saved it), you can run your scriptby Scan > Clicking at Run icon (see below) QR Code on the toolbar Or by clicking at Run ’ Run command Or by pressing shortcut key F5. NOTE Now that you are familiar with different ways of working in Please make sure proceed with our Consolebeo Python, we canthese. discussion of Python. You can in IPython work on any of script. You run your i nAth to have cursor console. Chapter 2 GETTING STARTED WITH PYTHON 35 Run your soript by clicking here Uage Here yoU Can get hetp of ay obfect by pressing Ctrl+I in front of t, elther on the Edtor or the Console. &arinti! am progreing in ython") Vareble eplorer Fe p l r Phon corgole Type commands for 10:21:59) [MSC v. 1900 32 bít (Intel )] your script here and Type "copyright", "credíts" or "license" for more informat ion. save it using File > Save or IPython 6.2.1 -- An enhanced Iteractíve Python. Fille-’ Save As commands In : print("helio ") hello In : rúnfile('C:/Users/fdupf spyder py3/temp.py', Hello Horld I am progranning in Python The output of executed script In : Prton corscke Hstory log Pemissions: RW End-of-ines: F Encoding UT Lin Column 1 Memory S74% 2.4.3 Writing and Compiling Python Program with Command Line in Linux Tocreate and run a Python program on Linux platform, you need to do this : () Write your program code in a text editor. (i1) Save your program with.py extension. (ii) Compile and run on the command prompt by giving appropriate command. Let us see how. Typing Python program in a Text Editor There is a variety of choices for text editors when it comes to Linux. There are command line editors like nano, vim, emacs etc". ; Or youcan work with the GUIeditors like Sublime Text, atom, brackets etc. This really is the choice of the user. But here, we will be working with Sublime Text 3. Let us see, how we can write a simple Hello World program in Sublime Text and compile and run it using the terminal. (Please note that Sublime Text editor must be installed on the machine before you can use it.) Coding in Text Editor (Sublime Text) (i) Open Sublime Text. Press the super key (windows key) and search for Sublime Text. You willfind an option to open sublime text. Click on the icon and it will appear. (i) Create a New File. Either usecommand File -’ New or press Ctrl +N on the keyboard. 6. Vim and emacs have their GUI version as well. INFORMATICS PRACTICES. 36 world code : (ii) A new untitled file will open. Write the hello print("he llo iwor ld" ) SublimeText (UNREGISTERED) Joesktop/helto.py 1ools PrOject PerereneP Seection Find Viewi coto print ("Hello world Python Desktop (i0) Save the file with proper extension. Nf For this, use command File ’ Save or press Ctrl + S from the keyboard. In the Save dialog that appears, write sitee the name of the file and give an extension.py. We have named the file as hello.py. Compiling and Running the Code using the Terminal (i) Open the terminal. Press Ctrl + Alt +T from the keyboard. A command prompt will (ii) Go the folder where you saved the appear file'. (ii) Type the following command in front of the prompt and press Enter : python.py That is we should type following command to compile and run our python hello. py programn hellopy edupillar oFLASH:-Desktop Fike Edit Vie Seerch Tetminat Hetp dupttlaraFLASH$ cd Deskton dupiliarFLASH7besictogK python hello. 0y (iv) It will compile and run terminal window. your program. You will see the output of the Programint edupl irch terral Hel cd 9esktop! Desktog5 pytho laroFLASHEDe hello oy You can use the command cd. 7 Alternatclickivel"Open Right click in the empty space and y, openin files (press Windows key and 8, There is no concept of extensionsin You can Linux however, Terminaltext". sublime search for files). Go to the conectfole thesyntax accordingly. externally set the syntax formatusesasthese well. ext Butensiweonsareto identify the format and highbý not covering that. Chapter 2 : GETTING STARTED WITH PYTHON 37 2.5 Understanding First Program/Script Let us create our first program - asimple "Hello World" program. (We are using Spyder IDE for this. You can use any of the above mentioned options.) Tocreate this, 1. Start Python IDLE or Spyder IDE or any other editor of your choice. 2. Start new file (File -’ New File) and type the following text in the editor window : #My First Program print ("HelloWorld!") 3. Now save your script with a desired name. Make sure to select Save as type as Python Files. Give py extension to your python program file. LG Python 3.J.4 Shel File Edit Shel! Debug Option: CtrlaN Open.. Ctrl-O Open Moduie... Ait+M Recent Files L"untitled Module Browser Alt-C File Edit Format Run Options Window Help Path Browser # My first progran Save Ctri+S Save As... Ctrt- Shift print ("Helio Worid! ") L Save As Save Copy As.. Alt+ Shift « Program Files (86) » Python37-32 º Print Window Ctrl+P Alt+F4 Type your code in File name: programl.py Close the code window Save astypePython files Exit Ctrl-Q And save your file Browse Folders Save Cancel with.py extension 4. Now run your script by clicking Run -’ Run command or by pressing F5. ). It will show you the output in the console window pane (see below). File Edit FormatRun Options Windo Help Python Shel! Check tiodule Run Mod Python 3.7.4 Shell # My first Run.. Customized Shift-fS File Edit Shel! Debug pticns indcw Help print ("He ===== * = = = RESTART: 0:Vsers/ Hello World! The outputof executed program/script INFORMATICS PRACTICES M 38 Analysing Script and Output You typed two lines : vow carefully look at the seript that vou typed. # My First Program print("Hel lo World") But Python gave you just one line's output as : Hello World! a comment in Python. That is, it is Ihe reason being that anyline that begins with a # symbol is the lines starting ignore all tor the programmer's information only ; Python will completely with a #. Understanding print( ) can use print( ) as 1° prnt or display output, Python 3.x provides print( ) function. You print(...) e.g., when you Wrote String "Hello World!" is the print( ) object to be printed statement 1 print ("Hello World!") it printed: Hello World! Similarly, to print other strings you may give something like. String object 'My name is Misha' print( ) print( 'My name is Misha') to be printed. statement 2 it will print My name is Misha Carefully look at both the print( )statements given above. Could you notice anything other than two different string values ? No ? Carefully notice that the first string is enclosed in double quotes and the second string is enclosed in single quotes. String enclosed in double quotes print("Hello World!") String enclosed in single quotes print('My name is Misha') Both these strings are valid in Python. You can enclose your strings in either double quotes or in single quotes, but just ensure that opening and closing quotation mark should be of same type. You cannot have a string like "Hey there" + Error! opening and closing Quotation marks do not match Following are some valid print( ) statements. print(' The Golden Ratio') print("has same letters as") print( 'The God Relation') "ith this we have come to the end of this chapter. Let us quickly revise what we have learnt so far. In Python 2.x, print is a statement, not a function.

Use Quizgecko on...
Browser
Browser