You are on page 1of 80
Cane C++ & Python me) mls Photoshop elms ed ET AU WETS Photography For Beginners For Beginners —= C++ & Python For Beginners Cloud Python Computing ele sl} For Beginners Photography For Beginners Google For Beginners iPad Landscape iPhone For Beginners old {ce} NT For Beginners C++ & Python For Beginners eee An eee Redo Pee Rem aol a Colt od Wee Ela R od ee NE CRU Lee) UN ae g Cea ane eA ade} manual decreases or in some cases it simply disappears. At Mace Ra Re RM Ett ua ee Ua em UU od PEC Ee Aas Rd eee rae WA Re ecg ol caemm Wala eM Ce UEul=-Wn ase kas oR aT cae ed EW ee Nn REE ee ea ACen Uebel Bete a Eo eV TmUlet recs e kel mt eRe ere a cae Le Eigen eaten ee eM Rue ella Coat eA RDU eC AUR) ec M ace nya) e-l Ea y marae aU taN OAL Ud scan yea elec yc nN Fiala ym Ramet meee le Maa MUP LUT eRe im core ale) 42 MCR eee CUA OME Menor Teac sald EUnet kt Oa ee Le eae NAOMI CUR CUE Uae aay STM ele) lea ol Renae Contents 8 WhyPython? 10 Equipment You Will Need 12 Getting to Know Python 14 How to Set Up Python in Windows 16 How to Set Up Python on a Mac 18 How to Set Up Python in Linux —_ 20) Getting Started with Python ESO eta ured 22 Starting Python For the First Time 60 YourFirst C++ Program 24 Your First Code 62 Structure of a C++ Program 26 Saving and Executing Your Code 64 Compile and Execute 28 Executing Code from the Command Line 66 Using Comments 30 Numbers and Expressions 68 Variables 32 Using Comments 70 Data Types 34 — Working with Variables 72 Strings 36 User input 74 C++Maths 38 Creating Functions 40 Conditions and Loops 42 Python Modules 46 Why CH? 48 Equipment Needed 50 Howto Set Up C++ in Windows 52 Howto Set Up C++ ona Mac 54 Howto Set Up C++ in Linux 56 Other C++ IDEs to Install wm publications com aa seat ‘ee Paton For Benne Isp ear28e-36 Pied Paps Lined Digital dstbation yr: ea AB no Nope Cfo, Poctags apse merge & les Ns 00519, eons [Efooursicon i mnntinoiiatencon ora publications com Say Hello to Python ME nu ee Cd BC cone ence cet i) ee ee eu e ei) used as minor utilities for operating systems. Python sits somewhere in the middle, combining ease of use eed an cate Peerage cn ies ens ure Pee enue ieee Dee ar a eu. Soe CM Cu ec) lively community behind it that shares knowledge, code and project ideas; as well as bug Fixes for Future releases. It's thanks to this community that the language has grown and thrived and now it’s your turn, Pele tes tire u ee ae cance Begs ds ae cue ty latest version of Python and from there guide you on Pe tetera e en) Functions and Features of the language. Before long, you will be able to code your own helpful system tools, De ee UU eee Dee een ED) sricotonne Why Python? SEEM icns ae cumin) uct eee Cement skeet cn and some still available For older 8 and 16-bit computers too. Some of these languages Ere Kel sre eho ANOTHER Meco Renee farerenketeeiel esta PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved their way into anew Frontier, Forging small routines that enabled the letter ‘to scroll ‘across the screen It may not sound terribly exciting to a generation {that’s used to ultrahigh defintion graphics and open world, multi player online gaming, However, forty-something years ago it was biindinaly brillant. "Naturally these bedroom coders helped form the foundations for, every piece of digital technology we use today. Some went on to become chief developers for top software companies, whereas others pushed the available hardware tots limits and Founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, iOS device, PC, Mac, Linux, Smart TV, games console, MP3 player, GPS device bu tocar, settop box ora thousand other connected and smart’ appliances, behind them als programming. ‘Allthose aforementioned distal devices need instructions to tell. them what to do, and allow them to be interacted with, These instructions form the programming core ofthe device and that core ‘canbe built using a variety of programming languages. ‘The languages in use today differ depending on the situation, the platform, the device's use and how the device wil interact with ts Dn tat Beet BS Ob bot Se Xe ar vivenacee)@/6 Gee +> 7@ ‘Setcursor(p. yz certsichitsentFocusi: itleurgor >= 0) Pefreshpow‘cursor); centTrchitdbastrocust) TeTIMENGT Paine") nati) ® C++ is usually reserved For more complex ‘programs, operating systems, games and so on. old Arraycert::childLostFocus() : void Arraycert::Paint(Oravé 4) ( iets < cetcount()) { top = cattiney 3) LitePeop etze.ey) breaks Hop + opttinecy (i) 4 < column. cetcnune(): 344) { er Settaiasth(3) a) 0) 4c = Blend(scoloroissbled, scoloreaper); obs environment or users. Operating systems, such as Windows, macOS. {and such are usually a combination of C++, C#, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethore of avalable languages such as HTML, Java, Python and soon. ‘More general-purpose programming is used to create programs apps, software or whatever else you want to call them. They/re widely used across all hardware platforms and sult virtually every conceivable application. Some operate Faster than others and some are easier to lear and use than others. Python is one such general purpose language. Python is what's known asa High-Level Language, in that it talks to the hardware and operating system using avarety of arrays, variables, objects, arthmetic, subroutines loops and countless ‘more interactions. Whilst it’s not as streamlined asa Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that it's universally accessible and easy to learn, gag /FiTe= tnvoke. java import java. lang.reflect.*; BM class rnvoke Public static void main string [) args try Cass ¢ = Class. forname( args[0] ); Nethod'm = c.getMethod( args (1), naw class Object Fee = a. imyokeC nulT, nul? systen.out.printin ‘Stqvokee, static method + of ctass: © + args(o tm with no args\nnesults: " + ret); catch ( Classotroundexception € 77 Class. fornane(”) can't find the class Gach € wosuchtiethodexception e2 77 that method doesn't exist * + args( aren ( Tllepalaccesstxception 3 77 we don't have permission to invoke that wnethod. Gatch ( Invocationtargetexception e4 77*an exception ocurred while tnvocing that nethod 1 Systen.out. print yetsNethod threw an: " + ef getTargetexception( ")")} Javaisa powerful language that's used in web pages, set-top boxes, TVs and \< Cinyevon CE Python was created over twenty six years ago and has evolved to become an ideal beginner's language For learning how to program 3 ‘computer. I's perfect forthe hobbyist, enthusiast, student, teacher ‘and those who simply need to create their own unique interaction between either themselves or apiece of external hardware and the ‘computer self. Python i free to download, install and use and is avallable for Linux, ‘windows, macOS, MS:DOS, 05/2, BeOS, IBM iseries machines, and ‘even RISCOS. Ithas been vated one of the tap Five programming languages in the world andis continually evolving ahead of the hardware and Internet development curve. ‘So to answer the question: why python? Simply put, it's Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool y y 2 a a + x 23s 130 iso 150 138 i 2 2 3 5 Score ) spy THEN LET 30; 10 TO i000: “NEXT Se ai i 2 i Se r 3 a Si Bi 3: Si ry et rt ct BASIC was once the starter language that early B-bit home computer users learned. Python is a more modern take on BASIC, i's easy to learn and makes for an ideal beginner's programming language. BE) 2 sctoiortion Equipment You Will Need pare arena nd leeCur Uc kom Une are Case un ll Colota Panto anol] Ng Leet Reon) .U UOT O LNRM OLA Le Key irl] (om WHAT WE'RE USING ‘Thankfully, Python is a multi-platform programming language available For Windows, macOS, Linux, Raspberry Pi and more. If you have one of those systems, then you can easily start using Python. {| compuTeR bvously you're going to need a computer in order to learn howto program in Python andto test your code You can use Windows (rom XP onward) on ether 232 or 6b procestor, an Apple Ma or Lnuxinstaled PC. (_] AN IDE An IDE (Integrated Developer Environment) is used to enter and execute Python code. It enables you to inspect your program code and the values within the code, 2s wells offering advanced Features. There are mary different IDEs avaliable, so find the one that works For you and gives the best results. |_| PYTHON SOFTWARE 1macOS and Linux already come with Python preinstalled as part ofthe operating system, a5 does the Raspberry P. However, you need to ensure that you're running the atest version of Python, Windows users need to download andinstal Python, which wel cover shorty (_] TEXT EDITOR Whilst a text editors an ideal environment to enter code into, it'snotan absolute necessity. ou can enter and execute code directly from the IDLE but atext editor, such as Sublime Text or Notepad++, offers more advanced features and colour coding when entering code. {| INTERNET ACCESS Python isan ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to make it amore efficient language. Having access to the Internet will keep you up-to-date, help you out when you get stuck and give access to Python's immense number of modules. {_] TIME AND PATIENCE Despite what other books may ead you to believe, you won't become a programmer i in 24-nours. Learning to code in Python takes time, and patience. You may become stuck times and other times the code wil flow Uke water. Understand you're learning something entirely new, and you wil get there THE RASPBERRY PI ( Equipment You will Need Cl Why use a Raspberry Pi? The Raspberry Pisa tiny computer that’s very cheap to purchase but offers the user a fantastic learning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras. a aaa) ‘The Raspberry 13 i the latest version, incorporating a more powerful CPU, more memory, Wii and Bluetooth support You can pick up a Pi for around £32 or asa part ofkitFor E504, depending on the kit you're interested in RASPBIAN ‘The Raspberry Ps main operating system is 2 Debian based Linux distribution that comes with everything you need in 2a simple to use package. It’s streamlined for the Piand is an ideal platform for hardware and software projects, Python, programming and even as a desktop computer. FUZE PROJECT ‘The FUZE isa learning environment built onthe latest model ofthe Raspberry Pi. You can purchase the workstations that come with an electronics kitand even a cabot arm for you to build and prooram. You can find more information on the FUZE at wwrw.Fuze.co.uk. We have several great coding titles available via www. ‘bdmpublications.com. Our Pi books cover how to buy your First Raspberry P, set it up and Use it there are some great step bystep project examples and guides to get the most From the Raspberry Ptoo, =r « z= Say Hello to Python ) Getting to Know Python une eer cole ree mae) Cute kerr let rl Reo aaa eRe EL Me fe Rae te CEU RC to understand. WHAT IS PROGRAMMING? It helps to understand what a programming language is before you try to learn one, and Python is no different. Let's take 3 look at how Python came about and how it relates to other languages. PYTHON ‘A programming language isa listof instructions that ‘a computer follows. These instructions can be as simple ‘as displaying your name or playing a music ile, or ‘ascomplex as building 2 ‘whole virtual world. Python isa programming language conceived in the late 1980s by Guido van Rossum ‘at Centrum Wiskunde & Informatica (OW in the Netherlands asa successor to the ABClanguage. Guido van Rossum, the Father of Python. PROGRAMMING RECIPES crore pus 10 arom of selfratsng four Sn + bol Programs are lke recipes For computers. A recipe to bake a cake could go like ths: 2 as 180 grans of butter to she baud Put 100 grams of selFraising flourin a bow ‘Add 100 grams of butter tothe bowl, ‘Add 100 mliitres of milk. Bake for half an hour, CODE Just lke a recipe, @ program consists of instructions that you follow lnorder.A program that describes acake might run lke this: bowit = four = 100 butter = 50 milk = 100 Feehan nna ny bb .append( [flour butter mic] If cake. cookCbon) PROGRAM COMMANDS ‘You might not understand some of the Python commands, lke bowL append and cake.cook(bowi). The firsts alist, the second an object; we'l look at both inthis book. The main thing to know is that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to Figure out how a program works. HIGH-LEVEL LANGUAGES Computer languages that are easy to read are know 2 hightevel Thisis because they fly high above the hardware (also referred to as “the metal) Languages that “ly close to the metal, lke Assembly, ‘are known as low-level’. Low-level languages commands read abit, like this:msg db ,@xa len equ $ = msg PYTHON 3 VS PYTHON 2 Pee ut cuanto. Peete Lene! WORLD OF PYTHON emetic Peer eee eae Anes Cataract peta es that DCR oa eure Ur PYTHON 2.x erie et is Se aeete eer tremely (cetinstoroowxion CE ZEN OF PYTHON Python lets you access all the power of a computer in a language that humans can understand. Behind all this isan ethos called "The Zen of Python." Ths isa collection of 20 software principles thet influences the design ofthe language. Principles include “Beautiful isbetter than ualy" and "simple i better than complex." Type import: this into Python and it wil dsplay al the principles. PYTHON 3.X apunietaenes and enhanced Featu Soren eerste : mete meee wil Doses has since be Pm 3.X WINS ielueueeemn Petits eer ro tsa cece peer bowed Python 3 For snippets of important code, z= Say Hello to Python How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python Downloads page. Whilst most seasoned Python developers may shun Windows as the platform of choice for building their code, it’s still an ideal starting point for beginners. INSTALLING PYTHON 3.X ‘Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. Thankfully, i's an easy process to follow. FETED 2'tby opening your web browser to www.python. ‘0ra/downloads/. Look for the button detailing the download lnk for Python 3.x (in our case thisis Python 3.6.2 but as ‘mentioned you may see later versions of 3) DTC Re oe Ce rm a Te DownloadPython 3.62 | Oownloadython27.13, Click the download button For version 3x, and save the file to your Downloads folder. When the fle is downloaded, double ick the executable and the Python installation wizard wil launch, From here you have two choices Install Now and Customise Installation. We recommend opting for the Customise installation ink Install Python 3.6.2 (32-bit) ® = pythén windows Bis Choosing the Customise option allows you to specify certain parameters, and whilst you may stay with the defaults i's a good habit to adopt as sometimes (not with Python, thankfully) installers can include unwanted additional Features. Onthe first screen available, ensure allboxes are ticked ‘and click the Next button. J Optional Features deemaatin pythén windows tk Nest ant BPD the next page of options include some interesting adtionsto Python. Ensure the Associate fe with Python, Create Shortcuts, Add Python to Environment Variables, recompile Standard Library and install for Al Users options are ticked. These make using Python ater much easier Click Install when youre ready to continve = a pythén windows mae Advanced Options You may need to confirm the installation with the ‘Windows authentication notification Simply click Yes and Python will begin to install, Once the installation is complete the final Python wizard page wil allow you to view the latest release notes, and Fllow some online tutorial Setup was successful yy @ outle * windows. Before you close the istalwicard window, SUS however, it's best to click on the link next to the shield detaed Dsabe Path Length Lt. This wil allow Python to bypas the Windows 260 character imitation enabing outo execute Python programs toredin deep folders arrangements Again cick Yes to authenticate the proces ten you can los the etalon window © Disable path lenath limit ‘close moe ” Windows 10 users will now = find the installed Python 4 Deena 3.x within the Startbutton Recently Added section. The First link, Python 3.6 (32-bit) . wll launch the command line version of Python when dlcked more on that ina moment) To open the IDLE {ype OLE into Windows start How to Set Up Python in Windows Cl Clicking on the IDLE (Python 3.6 32-bit link will launch the Python Shell, where you can begin your Python programming journey. Don't worry iFyour version ismewer, as long as i's Python 3.x our code will work inside your Python 3 interface, environment. To enter Python within the command line, you need totype: python and pres Enter. BSTSET ER) the command line version of Python works in| much the sare way asthe Shell you opened in Step 8; note the three leftfacing arrows (>>>). Whilst it's a perfectly Fine environment, it's not tao user-friendly, so leave the command line For now. Enter: xitO to leave and close the Command Prompt window. BE) 2 sctoiortion How to Set Up Python on a Mac ert Ea CA Meena eet n eT Mn Tales NSA Toe Rese la oda eNO ELK Te NVA) Cre oN Lem OLR Colt COMM RS B VoL MR UTTIAN) TAC) labo INSTALLING PYTHON Apple's operating system comes with Python installed, so you don't need to install it separately. However, Apple doesn't update Python very often and you're probably running an older version. So it makes sense to check and update first: PEPER Oven anew Terminal window by clicking Go> FEED click onthe latest version of Python 3x, in our Utilities, then doubleclick the Terminal icon. Now ‘ase thsi the download button For Python 3.6.2. enter: python’ ==version. You should see "Python 2.5.1" and This wil automatically download the latest version of Python and even later, i Apple has updated the OS and Python instalation. ‘depending on how you've got your Mac configured, it automatically Either way, i's best to check forthe latest version. starts the Installation wizard, PSPTSED) oven safari andhead over to www.python.org/ FETS With the Python installation wizard open, click on downloads, Just as with the Windows setup the Continue button to begin the installation. I's ppracedure on the previous pages, you can see two yellow dawnload worth taking a moment toread through the Important information buttons: ane for Python 3.6.2, and the other For Python 2.7.13. section, in case it references something that applies to your version Note, that version numbers may be different due to the frequent of macOS. When ready, click Continue again releases of Python. wane Stee Download the latest version for Mac OS X ‘Thernext section details the Software License MED s3rccment ands rot particulary interesting to most folks it's probably worth a read, When you're ready, click on the Continue button once again Install button, which you need to click to startthe actual installation (of Python 3.x on to your Mac. You may need to enter your password to authenticate the installation process. Finally you're be presented wit the amount of space Python will take up on your system and an PEPE DD) The installation shouldn't take too long; the older ‘Mac Mini we used in this section isa little slower than more modern Mac machines andit only took around thirty seconds for the Installation Successful prompt tobe displayed. Theres nothing much be fet do inthe Python S18 installation wizard so you can click the Close button. you now rp bckinoo Terminal session and reenter the commang: yhon3 =-verston yu can ee the new version now sted To ete the command ine version of Python you need toenter python3. Toes ts exiEO, FSTTSEB You need to search in Finder For the Python IDLE; when you've found it, clckitto launch and it should look similar to that of the Windows IDLE version shown on, the previous page. The only difference being the Mac detected hardware platform it’s running on. ese Pon 160 Set Pyar 3.6.0 G3.6.0414F926I1, bee 22 286, 1723-0) (EeC21 Cate ines bua S666) (ot 39} serie Fev Ce50) von ay bo conan Colder Mac versions may have trouble with the newer versions of Python, in which case you will need to revert toa previous Python 3.x build; as long as you're using Python 3.x, the code in this book will work for you. Python 3.1.2 (r312:79360M, Mar 24 2010, 01+33:18) {Gce 4.0/1" (apple inc. build 5493)} on’ darwin Type "copyright", “credits or "license()" for mo Ee ineornation. How to Set Up Python on a Mac cll Na AVAXHOME? nee cd providing you various content: LC eC a Ee ee eS mea eas ces Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction PRE Uys ETC emer ol Tei AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu Say Hello to Python How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it's often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial FETED) Fistyounced to ascertain which version of Python MEE some Linux distros will automatically update iscurrently installed in your Linux system as we the instalation of Python tothe latest versions mentioned, we're going to be using Linux Mint 18.1 for this section. whenever the system s updated. To check, ist do a system update ‘Aswith macOS, drop into a Terminal by pressing CtrAtsT, and upgrade with a sudo apt-get update && sudo apt-get upgrade Fie Et View Search Terminal Help Enter your passward and let the system do any updates, ESTEE "Nextenter:python’=-version into the Terminal ESTSSIBM Once the update and upgrade is complete, you screen. You should have the output relating to ‘may need to answer Y' to authorise ay upgrades, version 2.x of Python inthe display. Qursinthispartcularcaseis enter: python3. --verssion to see if Python 3x's updated or even Python 2.7.12. installed, In the case of Linux Mint, the version we have is Python, 3.5.2, whichis Fine for our purposes. davide-david-mint Fle Edit View Search Terminal Help pr ot Paurueeetd ww bmpublcations com How to Set Up Python in Linux FETED However iFyou want the latest version, 3.6.2as per [EIB within the python folder, enter: the Python website atthe time of writing, you need sence tpbuld thon rom sure Stary entering these commands ito [__—— ‘This could alittle while depending on the speed of your computer Once Finished, enter: python3.6 ==versivon to check the installed latest version sudo apt-get install build-essential checkinstalt sudo apt-get install libreadLine-gplv2-dev Libncursesn5-dev Libsst-dev libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev Libbz2-dev BETTE) Oren up your Linux web browser and goto FETS Fo" the GUIIDLE, you need to enter the following the Python download page: vwwwpython.ora/ ‘command into the Terminal: downloads. Clickon the Download Python 36.2 (or whichever version it’s on when you look) to download the source Python: 3.62.tarve fle, ‘The IDLE can then be started with the command: idLe3. Note, that IDLE runsa different version fram the one you installed from source, sudo opt-get install idle3 Cyt ure) BETTER the Terminal gothe Downloads folder by PEPPER vou also need Pi Ppinstas Packages) whichisa contents of the downloaded Python source coce with: tar =xvF Enter sudo apt-get install. python3-pip Python-3.6.2. tar.xz, Now enter the newly unzipped folder a, PPPs then installed checkor the atest update with pip3 install --upgrade pip eee ‘When complete, close the Terminal and Python 3 willbe available via the Programming section in your distro's menu. ora vmpublcationscom z= Getting Started with Python Getting Started with Python ee SR ae Usa CTO aaa Cues Ueto se SSeS ATU el Re ule Ro os co) ee NA ene Eo eed PURO U Se Tce ae ON a ee) expressions, user input, conditions and loops; and the types of errors you may well come across in your time Paes 2 @) Getting Started with Pytho +) Starting Python For the First Time Mere ol tern ee uaa ey ed rec cea Renae ode once eaaccel Che EM Ce raced ttc lea so as long as you have a version 3 Shell, all our code will work. STARTING PYTHON We're not going to go into the details of getting the Raspberry Pi up and running, there's plenty of material already available ‘on that subject. However, once you're ready, fire up your Pi and get ready for coding. FETTER) With the Raspbian desktop loaded, cick onthe ELE or example, nthe shell enter: 242 Menu button followed by Programming > Python After pressing Enter, the next line displays the 3 (DLE). Tis opens the Python 3 Shell Windows and Mac users can answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shell fram within the Windows Start button relevant output. ‘meni and via Finder. = PEER ecncicanweenmeracncsnete, RBI ‘nnn suisse nate scner some simple code and processes. sequence of whole numbers can easily be added, subtracted, multiplied and soon. Pe ee TT ee Steet race heme) or mre ita, Starting Python for the First Time E mm ESTEE While that’s very interesting it's not particularly exciting, Instead, try this print(*Hello everyone!”) Just lke the code we entered in Sublime in the Installing a Text Editor section ofthis book ESTED Tisise litle more tke it, since you've just produced your First bit of code. The Print commands Faity selF-explanatory, prints things. Python 3 requires the brackets as ‘well as quote marks in order to output content to the screen, inthis case the ‘Hello everyone! bit. >>> print("Hello everyone!”) Hello everyone! >>> | EaTeeAD You may have noticed the colour coding within the Python IDLE. The colours represent different elements of Python code. They ae: Black -Data and Variables Green~Strings Purple Functions (Orange Commands Blue — User Functions Dark Red Comments Light Red ~ Error Messages, IDLE Colour Coding asked | Comments | ianeaber VAR antes [Ererrosuote | syneanteror ThePython DLE coniquabeenionent F Ella! you don''t like the way the colours are represented, thenyoucanahascunge hems Optons> Conte Leon licking onthe Highlighting tab. However, we don’t recommend that, as you won't be seeing the same as our screenshots. pea «uae ost = 4 zereemn ee FETED ust lke most programs avaliable, regardless ofthe ‘operating system, there are numerous shortcut keys avallable. We don’t have room for them all here but within the ‘Options > Configure IDLE and under the Keys tab, you can see alist. (of the current bindings. PEPISETR Te Pithon IDLE is a power interface and one that's actually been written in Python using ane ‘of the available GUI toolkits. F'you want to know the many ins and ‘outs ofthe Shel, we recommend you take a few moments to view ‘ww-docs.python.org/3/library/idte.html, which details many oF the IDLE's Features ED) ceinsteawtnaenn Your First Code Essentially, you've already written your First piece of code with the ‘print(“Hello everyone!”)’ Function From the previous tutorial. However, let's expand that and look at entering your code and playing around with some other Python examples. PLAYING WITH PYTHON wi most languages, computer or human, it’s all about remembering and applying the right words to the right situation, You're not born knowing these words, so you need to learn them. ESTED you've closed Python 3 IDLE, reopen itin TERED You cansee that instead ofthe number 4, the whichever operating system version you prefer. In outputs the 2+2 you asked to be printed tothe the Shell enter the Familiar Following: screen. The quotation marks are defining what's being outputted tothe IDLE Shell to printthe total of 2+2 youneed to remove the quotes: print(2+2) print(*Hetlo”) ea ama fr notin ESTeeE RD vst as predicted, the word Hello appearsin the FETE You can continue as such, printing 242, 46442343 Shellas blue text, indicating output from a string {and s0.0n ta the Shell. An easier way is touse a 's fairly straightforward and doesn't require too much explanation. variable, whichis something we will cover in more depth later. For Now try now, enter: print(*2+2") Your First Code ( CG \What you have done heres assign the letters and b two values: 2 and 2. These are now variables, \which can be called upon by Python to output, add, subtract, divide {and soon for as long as their numbers stay the same. Try ths: print¢a) print(b) 1 ES) Oia eo ips Sel Set een “ica tr mare intanation ESTEE The output ofthe last step displays the current values of both a and b individually, as you've asked them tobe printed separately. IFyou want to add them up, you can Use the following: print(arb) ‘This code simply takes the values of a and b, adds them together and outputs the result ¥ er ‘You cn ply around with dferentknd of varabes BMD 3 ne Princ uncon. For example, you cold assign variables For someone's name: ae="David” print¢nane) "Now let'sadd a surname: ‘surnane="Hayward” print(surnane) ‘You now have two variables containing a frst name and a surname New Fie. This will open a new window with Untitied as its name. Thisis the Python IDLE Editor and within it You can enter the code needed to create your Future programs. “ThelDLE ators forallintents and purposes a Suse simple text editor with Python features, colour coding and soon much nthe sae vei as Sbme. You ener code 25 you would within the Shel so taking an example from the previous tutorial, enter: printC*Hello everyone!") ESTESEDD You can see thatthe same colour coding isin place Inthe IDLE Editor asitisin the Shel, enabling you tobetter understand what's going on with your code. However, to ‘execute the code you need to first save it. Press FS and you get a Save...Check box open, © Cickon the Ok butonin the Sve box and select a cus? destination where you'll save all your Python code. The destination can be a cedcated Felder called Python oryou ‘anjust dump it wherever you lke, Remember to keep a tidy drive though, to help you out inthe future. Saving and Executing Your Code (c} SED enxera name foryourcode, nth for Susp ‘example, and click on the Save button. Once the Python code is savedit's executed and the output willbe detalledin the IDLE Shell n this case, the words Hello everyone! FETTER Thisishow the vast major of your Python code willbe conducted. Enter it into the Editor, hit F5, save the code and look atthe output inthe Shell. Sometimes things will difer, depending on whether you've requested a separate window, but essentially that's the process's the process we wil Use throughout this book, unless otherwise stated Et shel_De ane wrt We TE aa ee TT ee ye reais yee IF you open the file location ofthe saved Python. code, youcan see that it ends in apy extension. Thisis the default Python file name. Any code you create will be whatever py and any code downloaded from the many Internet Python resource sites will be oy. Just ensure that the code is written for Python 3 SPEED sts extend the code and entera few examples, 2 be2 rname="David” surname="Hayword” printCname, surname) print (a+b) IF you press FS now youll be asked to save the file, again, as t's been modified from before. Siar) you click the Ok button, the File willbe ‘overwritten wit the new code entries, and ‘executed, withthe output in the Shel I’s not a problem with just these Few tines butf you weretto edt a larger file, overwriting can become an issue. Instead, use File > Save As from within the Editor tocreatea backup, Now rate a new fle. Close the Eto, nd open Susy anew instance (File > New File from the Shell). Enter the following and save tas hello: ‘a="Python” be"is? c="cool!” print(a, b, ¢) ‘You will use this code in the next tutorial Talo. Renepboamarai yon Comhalo py Oat Getting Started with Python Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made inthe GUI at the command line level. Ez Python, in Linux, comes with two possible ways o BED Now you'e atthe command tine we can stat ‘executing code via the command line. One of the Python, For Python 3 you need to enter the he and python3 and press Enter. This will put you into the ‘on. Fir ll, with the familar three right: hon 2, whilst the other uses the Python 3 libraries hough, drop into the command tine or Terminal on Your operating system, Enis EED sm here you're able to enter the code you've : looked at previously, suchas: we're using a indows users will ai an2 i printCa) You can see that it works exactly the same. 5 users can get access mmand line by clicking Go> Utities» Terminal wu bmpublcatonscom Executing Code from the Command Line BED sorceeietosctnenecormndtner en EEEED) te eutotrringrytonscoie tombe prompt. Enter the Folder where you saved the code from the tothe differences between the jesn'terror out in any way, dh vious tutorial and lst the available files within; hopefullyyou way Python 3 handles the Print command over Python 2, the result should see the hello.py ile, isn’t as we expected, Using Sublime For the moment, open the hellopy file, BED From within the same Folder as the code you're BED Since Sublime Text isn't available For the Raspberry ‘going to run, enter the following into the you're going to temporarily leave the P for the ‘command line: moment and use Sublime as an example that you don't necessarily need to use the Python IDLE. With the hello file open alter itto FSEIRIADELLNTPD include the Following: This wll execute the code we created, which to remind yous: aaaeinatComattisiyominane?, ‘as*Python” printC‘Hello,”, name) an cacool!” print(a, b,c) FE rly sincetisisPython 3code ui EEE sete tees works when you vse the python command ryeuthe ty thesame code with wth ythen 2 by entering python3 hello. py python hello.py ‘The result willbe the original Python is cool! statement, togethe with the added input command asking you For your name, and displaying tin the command window. ora mpublcatonscom

You might also like