0% found this document useful (0 votes)
35 views13 pages

AI Chapter 5 Getting Started With Pythons

This chapter introduces Python, a powerful and easy-to-learn programming language developed by Guido Van Rossum. It discusses the advantages of Python, such as its ease of use and cross-platform capabilities, as well as its limitations, including speed and library availability. The chapter also covers how to install Python and work with it in different modes, including interactive and script modes, using various distributions and IDEs like Anaconda, Jupyter Notebook, and Spyder.
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)
35 views13 pages

AI Chapter 5 Getting Started With Pythons

This chapter introduces Python, a powerful and easy-to-learn programming language developed by Guido Van Rossum. It discusses the advantages of Python, such as its ease of use and cross-platform capabilities, as well as its limitations, including speed and library availability. The chapter also covers how to install Python and work with it in different modes, including interactive and script modes, using various distributions and IDEs like Anaconda, Jupyter Notebook, and Spyder.
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
Getting Started with Python chapter In This Chapter 5.1 Introduction 5.2. Python — Pluses 5.3. Python ~ Some Minuses 5.1 Introduction (Ceython programming language was developed by Guido Van Rossum in February Python is based on or influenced with zo programming languages : 5.4 Working in Python 5.5. Understanding First Program/Script roi) © ABC language, a teaching language created as a replacement of BASIC, and © Modula-3 Crython is an easy-to-learn yet powerful object oriented programming language. It is a very high level programming languag) yet as powerful as many other middle-level not so high-level languages like C, C++, Java ete. In this chapter, we shall introduce you to playful world of Piquant Python (Word ‘Piquant’ means pleasantly stimulating or exciting to the mind]. So, are we ready ? And... here we go. 5.2 Python — Pluses Nore be you kaw Python, the protramning, "language was SER ISheT nee coc eomect show namely Monty Python's Flying Circus. Though Python language came into being in early 1990's, yet it is competing with ever-popular languages such as C, C++, Java etc. in popularity index. 99 i a COMPUTER SCIENCE WITH PYTHON Be Let’s see what are these pluses of Python. : © Easy to Use 2. Expressive Language 3. Interpreted Language Its Completeness 5. Cross-platform Language 6. Free and Open Source 7. Variety of Usage/Applications } 5.3 _Python - Some Minuses (So Human Like) f] Ithough Python is very powerful yet simple language with so many advantages, itis not th, | Perfect Programming language. ~ aay Let's see what these are : Nore ~T. Not the Fastest Language 2. Lesser Libraries than C, Java, Perl eeaee an ae <3. Not Strong on Type-binding _4-Not Easily Convertible / commands you write are interpreted ang 5.4 Wotking in Python See one yo | { | 4 | | Before ySu start working in Python, you need to install Python 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 GUD 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.). | 2 popular IDEs are also available ¢., Spyder IDE, PyCharm IDE etc. Of these, Spyder IDE is already available as a part of Anaconda Python distribution. To install any of these distributions, PLEASE REFER TO. APPENDIX A. We shall learn to work with both’these distribution types. Once you have Python? installed on your computers, you are ready to work on it. You can work in Python in following different ways (i) in Interactive mode (also called Immediate Mode) (ii) in Script mode 5.4.1 Working in Default CPython Distribution ‘ The default distribution, CPython, comes with Python interpreter, Python IDLE (GUI based) and Pip (package installer). To work in interactive as well a script mode, you need to open Python IDLE. 5.4.1A_Working in Interactive Mode (Python IDLE} g vat Interactive mode of working means you type the Command — one command at a time, and the Python executes the given command there and then and gives you output{in interactive mode, you type the command in front of Python command prompt >>2. For example if you type 2+3in front of Python prompt, it will give you result as 7 : | a Ni Fesuk seornat >9>.245 <——— command/espression given here thon ————+ 7 a ee _ _— 7 _ _ - £, {yew instat Python through Anaconda Python Distribution ie loads most libraries and packages with Python, | 2 Python even has versions that run on different languages such as Java Qython), .NET (IronPython) etc. 102 COMPUTER SCIENCE WITH PYTHON — 4 5.4.1B Working in Script Mode (Python IDLE) What if you want to save Gime commands in the form of program file and want to see a output lines together rather than sandwiched between aceessive commands J th interactive mode, you cannot do so, for Plnteractive mode does not save the commands entered by you in the form of a . program, —S The output is sandwiched between the command lines [see Fig. 5.1(c)]. {is Zolution to above problems is the Script mode. To work in a script mode, you need to do the following : Step | : Creote Module / Script / Program File Firstly, you have to create and save a module / Script / Program file. To do so, follow these instructions : +49 Click Start button — All Programs — Python 34x —> IDLE. [Fig, 5.2(a) t# Click File — New in IDLE Python Shell. (Fig. 5.2(a)] Lid the New window that opens, type the commands you want to save in the form of a Program (or script). (Fig, 5.2(b)] For instance, for the simple Hello World program, you'll need to type following line : print ("Hello world |") Nore —————, You can cpiy ae we séript mode, print ) command is oy preferably used to print results pended. teh il hotee ver To see i Swe cus Working in Python IDLE cuss in action SaCepy te de Shites Pune tindow Cheb lve anete cea GR Code (2) File + New command in Python Shell (4) Type commands in new blank ile (script mode) Figure 5.2 (2) Click File > Save and then save the file with an extension .py. The Python programs has -Py extension [Fig. 5.2(c)]. For instance, we gave the name to our program as Hello.py. [Python GUTSAcitDLE tts youve the ent seen mana fons thn caseagpoawoasacen Boa ig not the Python program/script containing only the instructions. hopes 5: GETTING STARTED WITH PYTHON 103 Fae (fi) £48 Ferma Pun Options windoos Help New indo Cetett Open. cue 7 5 Recent Files . WO || octet he cevestes tae] Open tedule. Alters 4 ate ‘ | Chas Browter | AEC i “tenes . 1 4 cet ce 2 | Pat Browcer sanion “Save the Python Sreaie GateshneseS PA! | tien | sae Copy Ate Ashes 2 Se program/script fie j Pim indow cited i i Bee. : ose = peste you forget togve py |i) cama extension, Python wor't be |—"$— able to run your script. Figure 5.2 (c) Save file with .py extension with File—> Save command (Script mode). Now your program would be saved on the disk and the saved file will have .py extension. Step 2 : Run Module / Script / Program File After the program/script file is created, you can Tuivit by following the given instructions Open the desired program/script file that you created in previous Step 1 by using IDLE’s File > Open command. If the program / script file is already open, you can directly move to next instruction. —_— (ii) Click Run — Run Module command [Fig. 53(@)] in the open program / script file's window. You may also press F5 key. _ Si Bod it will execute all the commands stored in zl orton module / program / script. arn Chet ttcade At that you had opened and show you the complete ‘output in a separate Python Shell window. [Fig. 5.3(0)] ick at Run Run Modu ‘command to run the opens Bie Ete Shed Gabug Opens dom Hep 2018. 1607-46) MSC v.1900 32 b* (intel on win? ense" for mare information, ee a [sa2wietopy= ‘applied Run Module ‘command, (You can see complete ‘module in previous figure) Figure 5.3 (6) Output of a module-run is shown in the shell window. COMPUTER SCIENCE WITH PYTHON — yy 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 commandcouta sandwiching :)- Put 5.4.2 Working in Jupyler Notebook and Spyder IDE Anaconda distribution comes with many preloaded packages and libraries. You can work init in both interactive and script modes. Anaconda distribution provides the following tools that you can use to work in Python. © Jupyter notebook. It is a web based, interactive computing environment, © Spyder. It is a powerful Python IDE with many useful editin, debugging features. Let us learn to work with both. iG interactive testing and 5.4.2A Working in _Jupyter Notebook a CGrordes to work in jupyter notebook, you need to first launch it using Anaconda Navigator’ as it 1s come preloaded with Anaconda distributi -T. Launch Anaconda Navigator __2> From the Navigator window, click on Launch below jupyter notebook tile. | 1) ANACONDA NAVIGAI _ ® = i boven con | | emma ee 2. [Glick here to taunch 0 ‘epyder. vac . Figure 5.4 Launching applications from Anaconda Navigator. chopter 5 : GETTING STARTED WITH PYTHON ( . Since jupyter no isawk 7 ( 3 See ‘Jupyt oy, ebook is a web based computing environment, it will be launched in a Your web browser wil our browser will now show you notebook dashboard (see below) SF Droearoseses.ir0e < jupyter This is notebook dashboard | jc tors to perform act ons on them eons Pears 4 oa peel Ga sows | pau Smenmesae .| Trina Figure 5.5 On the notebook dashboard, Python 3 to crea click at down-arrow next to New button and select te a notebook for executing Python 3.x code. (see figure above). fun! In a new tab, it will open a new notebook where you can write and run your code. eo eevrnens tr! @ A one tutes 7 [Pymeod 0 1 Betore witing python . code, make sure itis nts 2h ee Rn Om eerste => | Code cel you can ‘ype python code here Figure 5.6 106 COMPUTER SCIENCE WITH PYTHON ~ 9) Interactive Mode _§. To run Python code in interactive mode, type code in code cell and click Run. (see below) > bone 0 Ursiees x © Orccaros: T jupyter Untitled hone ow vores rs © Orccates: Syupyter Untitleds Torun the code in ‘current code cell, click here Twill show the output] below the code and start a new code cell below it. = _ ‘new code cell Figure 5.7 Script Mode To run a script : A — (@) Write the code of a Python script - a group of Python commands in a code cell. ® Now click on its name to give it a new name (see below). Shoe Uti co T jupyter name to your python script » Rename Notebook Enicareu natochneme Specify name to your python script . Priet(cnetie veri") "Tan prograeniag ir Py’non3 ‘python script having multiple python commands Figure 5.8 Chapter § : GETTING STARTED WITH PYTHON (©) Click on save icon first to save it. (@) Click Run to run your script. Sf @teeatos TS yupyter scriptt.py STSCT an programing ie Python Figure 5.9 (©) You can check in the notebook dashboard, which is open in another tab ; it will show you the name of your currently saved script. To create @ new notebook, use command File» New notebook. Figure 5.10 5428 _Wosking 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, DataCamp community recommends Spyder TOE as the ost preferred choice” out of top 5 Python development environments recommended by it. @pyder IDE comes preloaded with Anaconda distribution. It is my personal favourite for working on Python") 5. As per URL : httpsi//wurw datacamp.com /community/tutorials/data-science-pythor-ide. COMPUTER SCIENCE WITH PYTHON 108 ” To launch Spyder ID) . —tiy Taunch Anaconda Navigator N aT = iL Click on Spyder tile in Anaconda navigator (refer to Fig, 5.4) The IPython console taey [Alternatively, you can directly click at commarasn fone ta itton —> Programs —> Anacond. Ider name) + Spyder Prompt and often shows animal ba a (al d a output with Out{ ) lines, Spyder Interface Once the spyder is loaded, you will see following interface : Sieeetinmie e | 1 ew Svan Ber a Sip OP BEMo PGOG ee Sem BE Ze oo came es) 8 seco *| cant Sis ie + tamerany scrap th cn ot et any att by presang Cade > font ot keer onthe Cor Senna Editor pane Hil i To create scripts, Je fBhe wrinee city Hy work here i: if ] marl Python Console To workin interactive mode, type command{s) here and it wl give i GD im|_ eeu commune } Figure 5.21 ae Is is a is j= Is a e Fane of spyder window. It will give you the output of the command there itself. See figure above where we typed command : Print(rHenio") in the IPython console pane and it gave us the result below it Script Mode Towwork in script mode in Spyder IDE, ‘ype your script’s commands in the editor pane. 20 start a new script file, click File > New File... | A770 save current script, use command File > Save or File —> SaveAs. -& Python scripts have File extension as .py. ® Please make sure to select file type as Python Files, Chopter § + GETTING STARTED WITH PYTHON ira) DD Newfiles cten & Open cto. Openlasteclosed —_CtnleShitte om Open recent ‘Make sure to select Save as type by licking this errow, as: Python files: Figure 5.12 To see After you have typed your scri in action script by : ipt (and saved it), you can run your #eking at Run icon (see below) on the toolbar Or by clicking at Run > Run command Or by pressing shortcut key 5. @ aeehomte 3 [ie Sone ose | oe" - Be ER BR 46 5 cumnawmn Bw SSIST TT he aaa 3S a a Eas cepa . ssrameeeatt smrraeeaie, es print d Print > “Type commands for reais) bse your seipthere and aera sso (eaieeeas felch } | : save it using Taorestisn ead fython 6.2.1 == an eahanced Interactive Python: i File->Save As eee Ve ‘commands ttle OTE So 131s continer Please make sure to click in Python console before You run your seript, So as to have cursor in IPython console, Welle norda Tom programming in Python We ah rence | tebe Working in Spyder IDE COMPUTER SCIENCE WITH PYTHO} Now that you are familiar with different ways of working in Python, we can proceed with discussion of Python. You can work on any of these. 5.4.3 Writing and Compiling Python Program with Command Line in Linux To create and run a Python program on Linux platform, you need to do ~ New oF press Ctsl+ N on the keyboar (iii) A new untitled file will open. Write the hello world code : print("Hello World") Compiling and Running the Code using the Terminal (@ Open the terminal. Press Ctrl-+ Alt+T from the keyboard. A command prompt will apf (i) Go the folder where you saved the file’, (iii) 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 program hello.py? : python hello. py Cer eesti ree Ci aCe eee ee See ea ee EERSOREY ae SRS srt (ie) Tt will compile and run your program. You will see the output of the program in the terminal window. Brae ene GT eM een eens pease ac ere iver Boise cts oC Grae cry Perens | 55 Understanding First Program/Script s a ‘st program — a simple “Hello World” program. (We are using Spyder IDE for this. You can‘Use any of the above mentioned options.) To create a) ——1. Start IDLE editor [Fig. 5.2(a), (b)]. 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 (Fig. 5.2(c)]- = Make sure to select Save as type as Python Files. = Give .py extension to your python program file. _—4. Now run your script by clicking Run + Run Module command or by pressing F5. _-5-At will show you the output. ois [Le Python 365 Sra { Shel Qebug Options | Python 3.6.5 (v3.6.5:f59c093284, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit {Intel)] on win32 "credits" or “license()" for more information. | Type “copyright”, | = RESTART: Hello Word! | ___Un6 Coba) Users\Edup\apData\Local\Programs\Python\Python36-32\Hello.py You can use the command cd. Alternatively, open files (press Windows key and search for files.) Go to the correct folde tight click in the empty space and click “Open in Terminal’. here isno concept of extensions in Linux however, sublime text uses these extensions to identify the format and highligh he syntax accordingly. You can externally set the syntax format as well. But we are not covering that. COMPUTER SCIENCE WITH PYTHON — yy) Analysing Script and Output fow carefully look at the script that you typed. it My First Program print (“Hello World") But Python gave you just one line’s output as : Hello World! The reason being that any line that begins with a # symbol is a comment in Python. That is, itis for the programmer's information only ; Python will completely ignore all the lines starting witha ¢, Understanding _print( ) % print or display output, Python 3.x provides print() function®. You can use print() as print(...) 1 typed tivo lines | e.8., when you wrote ting “Helto Worl” the Pr eg

You might also like