You are on page 1of 80
tech Photoshop Tricks and Tips Cloud Cetus -4 Tricksand Tips a, Photo; hy Wiss snd Tips Instagram Tricks and Tips Discover more of our Se a Android) iF (4 eee We S | = Ge Python: Codin ee aT dole and Tips Eiht = rs US cr FRITZ!Box Tricks and Tips Pact oii E iPhone iPad Landscape Tricksand Tips | TricksandTips) Photography Tricks and Tips eo tech | C++ & Python Tricks and Tips Welcome back... Having completed our exclusive For Beginners digital guidebook, we have taught you all you need to master the basics of your new device, software or hobby. Yet that's just the start! Advancing your skill set is the goal of all users of consumer technology and our team of long term industry experts will help you achieve exactly that. Over this extensive series of titles we will be looking in greater depth at how you make the absolute most from the latest consumer electronics, software, hobbies and trends! We will guide you step-by-step through using all the advanced aspects of the technology that you may have been previously apprehensive at attempting. Let our expert guide help you build your understanding of technology and gain the skills to take you froma confident user to an experienced expert. Over the page our journey continues, and we will be with you at every stage to advise, inform and ultimately inspire you to go further. Contents @> 6 |) Working with Data 8 Lists 10 Tuples 12 Dictionaries 14 Splitting and Joining Strings 16 Formatting Strings 18 Date and Time 20 Opening Files 22 Writing to Files 24 Exceptions 26 Python Graphics, & Using Modules 30 Calendar Module 32 OSModule 34 Random Module 36 Tkinter Module 38 Pygame Module 42 Create Your Own Modules Cyn: 46 User interaction 48 Character Literals 50 Defining Constants 52 _ File Input/Output BE) sirosiaioncon 54) Loops and Decision Making 62 If Statement: 64 ~~ If... Else Statement 68 = Common Coding Mistakes 70 Beginner Python Mistakes 72 Beginner C++ Mistakes 74 ~~ Where Next? tan c++ Tack and Tos Ison ore onaerst9 opus whut be pec ton prmaten fhe pus Pubished by PaperautLinaed th tsps nd ors be Pia debtion by: Minheenepenon Wem peccominaerbecsy ea Al Zio. Most Cao, oceans rt rowan sees et et eos ky ape age epee ote hott ch ever EET We abc tnt ye oe @ Festi ios ‘Soman aeulenen Medal pman turner te WQS Reps nErgand 8 wes Wo 20013 Tovinosss [Eeourticnons i wntcnpisiasnscon —————: Working with Data” Working Vaan Dye]e- Pert awn ake Uke See Ceol ecole Ce msec ES LS Petnenecak curate emacs eo eer Ra ore aol ke) ele emt Come ate CUM eur a aU W ment Bea ince) forge exciting and useful programs. Then, you can learn how to use date and time eee UR ul Cy ukegs eke) ieee alae e dened Ret meter dea Crue Rice ii Pic) rede wu bmpublcationscom a Mere eon eRe Reet atk Ceo cetera Python. A list is simply a collection of items, or data if you prefer, that can be accessed as a whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include Functions in ists, and lists within lists. FETEEERD Alistisa sequence of data values called items. You create the name of your list followed by an equals sign, then square brackets and the items separated by commas; note that strings use quotes: nunbers = [1, 4, 7, 21, 98, 156] mythical_creatures - [“Unicorn”, “Balrog”, “Vampire”, “Dragon”, “Minotaur”) ES veep ent we stn (Once you've defined your list you can call each sure! by referencing its name, followed by a number. Lists start the first item entry as 0, Followed by 1,2, 3 and so on. For example: unbers To callup the entire contents ofthe lst unbers[3] To call the third From zero item in the lis (21 in this case). BEPISEDD You can also access, orindex, the last ter in alist by using the minus sign before the item number [-], ‘or the second to last item with [2] and soon. Trying to reference an iter that isa in the ist, suchas [10} wil return an error: unbers[=1 mmythical_creatures[~4] TEEPE icingis similar toindexing but you can retrieve ‘multiple tems in a lst by separating ten numbers with a colon. For example: unbers[1:3] villoutput the 4 and 7, bing item numbers 1 and 2. Note thatthe returned values don'tinclude the second index position (as you ‘would numbers[t:3] to retum 4,7 and 21). SBE ene cn 4 ESTED Youcon update tems within an exiting list, remove EES woocuctiinatceree tare join two tists you can use: everything = nunbers + mythical_creatures ‘Ten view the combined lst with: everything Items can be added to alist by entering: nunbers=nunbers+[201] Or for strings: mythical_creatres=mythical_creatures+[“Griffin”] (Or by using the append Function: mythical_creatures.append(“Nessie”) ‘numbers .append(278) inte Talia) tog, mie, eager, wee i mci" natn hse BETTER) Removal of tems can be done in two ways. The fist isby the tem number: del nunbers{7] Alternatively, by item name: mythical_creatures. renove(“Nessie”) Youcanvew what canbe done withlsts by entering S128 dir(list) into the Shell. The output is the available Functions fr example, insert and pop are wet add and remove iemsat certain postions To insert the number 6 at emindex numbers.insert(4, 62) To remove ‘numbers .pop(4) You also use the ist Function to breaka string down into its components. For example: List (“Davie”) Breaks the name David into 0 toanew list: naneslist(“David Hayward”) ‘name age=[44] user = nane + age user \V,,'4. This can then be passed BITE 225d on that, ou can create a program to store someone's name and age as alist: amesinputC“hat"s your name? “) ‘TnaneslistCname) ‘age=intCinput (“How old are you: “)) ‘lage=[age] user = Inane + lage ‘The combined name and age lists called user, which canbe called by entering user into the Shel. Experiment and see what you can do, eee Tuples are very much identical to lists. However, where lists can be updated, deleted or changed in some way, a tuple remains a constant. This is called immutable and they're Pred ROUEN THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program intended to do. Normally a tuple is reserved for something special but they’re also used for example, in an adventure game, where non-playing character names are stored. PEPER’ tupleis created the same way asalistbutin this, instance you use curved brackets instead of square brackets. For example: months=(“January”, “February”, “March”, “April”, “May”, “June”) months BTERE DD You can create grouped tuples into lists that contain ‘multiple sets of data. For instance, here sa tuple ‘called NPC (Non-Playable Characters) containing the character name ‘and their combat rating For an adventure game: NPC=[C"Conan”, 100), (“Belit”, 80), (“Valeria”, 95)] Just as with ists, the items within a named tuple can be indexed according to their position inthe data Gis rd range, months] months[5] However, any attempt at deleting or adding to the tuple wil result inanerrorin the Shel. ERERE DD 2h of these data tems can be accessed asa whole by entering NPCinto the Shell or they can be indexed according to their position NPC[0, You can also index the individual tuples within the NPC lst: Neco] [13 will display 100. ESTED |’: worth noting that when referencing multiple tuples within ist, the indexing i sightly different From the norm. You would expect the 95 combat rating of the character Valeria to be NPC{A][S], butt’ not. e's actually: wec2] (1) Now unpack the tuple into two corresponding variables: Gname, conbat_rating)=NPC ‘You can now checkthe values by entering name and combat. rating, Sia) BETTIE) Thismeans of course that the indexing Follows thus: @ ua ao g a1 20 1 a 1,0 \which as you can imagine, gets alittle confusing when you've got a lot of tuple data to deal with. “Tuples though utilise a feature called unpacking, ‘where the data items stored within atuple are assigned variables First create the tuple with two items (name and ‘combat rating): NPC=C*"Conan”, 100) Sis ESTEE Remember, as with sts, you can also index tuples Using negative numbers which count backwards From the end of the data list. For our example, using the tuple with multiple data items, you would reference the Valeria character with: Necrz1C-0] You cn use the max and min functions to find the SALEM iret and ovest values tuple composed of numbers, For example: runbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) ‘The numbers canbe integers and oats, To output the highest and lowest use print(maxCnunbers)) print(min¢nunbers)) ee Dictionaries Lists are extremely useful but dictionaries in Python are by far the more technical way of dealing with data items. They can be tricky to get to grips with at first but you'll soon Peper Miia atime kes KEY PAIRS. A dictionary is ike a list but instead each data item comes asa pair, these are known as Key and Valu‘ ‘unique and can either be a number or string whereas the Value can be any data item you like. PRP DD >55>>>5>Leap Year Calculator Using Modules ) OS Module INTO THE SYSTEM (One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with files stored on the system, making it the perfect module for backup code. FETED You can startthe 0S module with some simple ESTED The Windows outputs different as thats the functions to see howit interacts withthe operating current working directory of Python, as determined system environment that Python sunning on. IFyou're using Linux by the system: as you might suspect, the os getcwd Function is Cor the Raspberry Pi, try this: ‘asking Python to retrieve the Current Working Directory Linux users a wise something along te same nes the Raspes hhome=os.getcwd() print (home) PEPER the returned result From printing the variable home VFM yer another interesting element to the 0S module, isthe current user's home folder on the system. Isis ability to launch programs that are installed nour example that’s fhome/piit willbe different depending on _inthe host system. For instance, if you wanted to launch the the user name you lag in as and the operating system you use. Chromium browser from within a Python program you can use For example, Windows 10 will output: C\Program Files (x86)\ the command Python36-32 oes bronser=os. system(*/usr/bin/chromiun-browser”) FETS The ossystem( function is what allows interaction with externa programs; you can even call up previous Python programs using this method. You will obviously ‘need to know the Ful path and program fle name for itto work successfully, However, you can use the Following: ‘import os os.system(‘start chrome “https: //nwu. youtube. com/ feed/music”") FETTER For Step 5's example we used Windows, to show that the OS module works roughly the same across all platforms. n that case, we opened YouTube's music Feed page, so itis therefore possible to open specific pages: ‘import os os.system(‘chromiun-browser “htt bbdnpublLi cations .con/”*) BRED) ote in the previousstep' example the use of single and double quotes. The single quotes encase the entire command an launching Chromium, whereasthe double quotes open the specified page. You can even use variables to cl ‘multiple absinthe same browser: inport os a=(‘chromium-browser “http: //bdmpublications. con") b=C'chromium-bronser “het os. system(a + b) ‘/umw.google.co-uk”?) The ably to manipulate drectores, or folders SIE) you prefer, is one of the OS module's best Features. For example, to create anew directory you can use import os (os.mkdirC*NEW") ‘This creates a new directory within the Current Working Directory, named according to the object inthe mkdir Function, You can also rename any directories you've created byentering: import os ‘os.renameC*NEW”, “OLD” Todelete ther: import os os. rmdir(“OLD") _ ‘Another module that goes together with OSis shutil You can use the shutil module together with OS and time to create a time-stamped backup directory, and copy files into import os, shutil, time root_sre_dir root _dst_dir for srcdir, dirs, files in os.walk(root_src_dir): dst_dir = src_dir.replace(root_src_dir, root_ dst_dir, D if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: src_file = 0s.path. join(sre_dir, file) dst_file = 0s.path. joindst_dir, file_) if os.path.exists(dst_file): 0s. renoveCdst_file) shutil.copy(srefile, dst_dir) print(Sssssssss2Backup completecceeceeece”) °° /nome/pi/Documents* “/nome/pi/backup/? + time.asctimeC) | OS Module Cll @) Using Modules ) Random Module RANDOM NUMBERS There are numerous Functions: Python programs. in the random module, which when applied can create some interesting and very useful Fe wna rosisyoreccmace we're going to look at in this tutorial, Let’s begin by simply printing a ‘import random printCrandomint(0,5)) Inour example Suave the number Four was returned. However eter the pt ncn afew more times and tll dlpay dere integer values fromthe setor rumba gven,2eot fhe The overal efectsthough pseudo fandom s adequate forthe average programmer tous in Sereode Forabige st of numbers nding lang ld point values, you can extend the range by using the ‘multipication sign: import random printCrandom.random() *100) Will display a Floating point number between 0 and 100, tothe tune ‘of around Fifteen decimal points. However, the random module isn’t used exclusively S14) for numbers. You can use it to select an entry from a lst From random, and thelist can contain anything import random random. choice({“Conan”, “Valeria”, “Belit”]) Tis will display one of the names of our adventurers at random, whichis great addition toa text adventure game. BEER You can extend the previous example somewhat by having random choice) select from list of mixed variables For instance: import random Lst=[“David”, 44, “BOM Publications”, 3245.23, “pi”, True, 3.14, “Python”] rnd=random. choiceCIst) print (rnd) Interesting, you can ao wea function whine Suz6 random module to shuffle the items in the list, thus adding ite more randomness into the equation: random. shuffleClst) print(Lst) ‘This way, you can keep shuffling the ist beFore displaying a random item from it. PEPER Using shure, you can create an entirely random lst cof numbers, For example, within agven range: ‘import randon Lst=[Ci] for I in range(20)) random. shuffle(Lst) print(lst) Keep shuffiing the list and you can have a different selection of items from 0 to 20 every time. BEPTID) You can also select. a random number frama given range in steps, using the start, top, step loop: ‘import random for i in range(10): printCrandom.randrange(®, 200, 7)) Results will vary but you get the general idea as to how it works, (Random Module Cll L Let's use an example piece of code which fips SLED icon ten thousand times and counts how mary times it wil land on heads or tals: import random ‘output={*Heads”:0, “Tails”:0} coin-listCoutput.keys()) for i in rangeC10000): ‘output[random. choice(coin)]+=1 printC‘Heads:”, output[“Heads”]) print(“Tails:”, output[“Tails”]) Here's an interesting piece of code. Using atext file containing 466 thousand words, you can pluck ‘a.user generated number of words from the file (text file Found at: ‘wwwegithub.com/dwy{/english-words): import random print(>ss>5ss59Random Word Findercccceceece”) printC*\nUsing a 466K English word text file I con pick any words at random.\n”) wds=intCinputC*\nHow many words shall I choose? Bi with openC“/home/pi/Downloads/words.txt”, “rt”) as fa words = f.readlines() words = [w.rstrip() for w in words] a for w in random.sanple(words, wds): print(n) print print¢ @) Using Modules.) Tkinter Module GETTING GUI a fer is easy to use but there's a lot more you can do with it. Let's start by seeing how it works and getting some code i Before long you will discover just how powerful this module reall “inter sul bul to Pthon3, Howes, Fis Sut" available when you enter: import tkinter, then youneedtopip install. tkinter fom the command prompt Wecan stat toimpot males ferent than before tosave on ping nd by imporehgal thet contents import tkinter os tk from tkinter port * PEPER is not cecommended to import everything from a ‘module using the asterisk but it won't do any harm ‘normally. Let's begin by creating a basic GU window, enter: windsTkO This creates a small, basic window. There's not much else ta do at this point but click the X inthe corner to close the window. FRED ics roxnsioaivnaiovs te btn=Button() btn.pack() ben[“text”]="Hello everyone!” ‘The first line Focuses on the newly created window. Click back nto the Shell and continue the other lines. You can combine the above into a New File ‘import tkinter as tk from tkinter import * btnsButton() ben.pack() ben[*text”]-"Hello everyone!” ‘Then add some button interactions: def clickQ: print(“You just clicked me!”) ben{conmand™}=click Save and execute the code from Step 4 anda window appears with ‘Hello everyone! inside. IFyou click the Hello everyone! button, the Shell will output the text You just clicked met. I’ simple but shows you what can be achieved with 2 few lines of code. FEPTID You can also display both text and images within a Tknter window. However, only GIF, PGM or PPM Formats are supported. So Find an image and convert it before using the code, Here's an example using the BDM Publishing logo: from tkinter import * root = Tk ‘logo = Phototnage(file="/hone/pi/Dowiloads/BOM_Logo.. aif") WL = Label(root, root. titleC“BOM Publications”), ‘image=1ogo) .pack(side="right”) content = “”” From its hunble beginnings in 2004, ‘the BOM brand quickly grew from a single publication produced by a team of just tno to one of the biggest ‘names in global bookazine publishing, for two simple reasons. Our passion and conmitnent to deliver the very best product each and every volume. While ‘the company has grom with a portfolio of over 250 publications delivered by our international staff, ‘the foundation that it has been built upon renains ‘the sane, which is why we believe BOM isn’t just tthe first ‘choice it’s the only choice for the snart consumer.” W2 = Label(root,, justi fy=LEFT, padx = 10, textecontent) .pack(sides" Left’ root .nainloop©) The previous code is uite weighty, mostly due tothe content variable holding apart ‘oF BOM's About page From the company website. You can obviously change the Content, the root title and the image to suit your needs. FETED ou can create radio buttons too. Tr: fron tkinter import * root = TkO v = IntVarQ) Label(root, root.titleC“Options”), tex a preferred language:”*”, justify = LEFT, padx Radiobut tonCroot text="Python”, padx = 20, variable=v, value=1).packCanchors=") Radiobutton(root, ‘text="CH", padx = 20, variable=v, value=2).packCanchor=") rmaintoop() FETTSEM) You can also create check boxes, with buttons and outputtto the Shelt from tkinter import * root = Tk) def var_states() printC*Warrior: %d,\nMage: %d” % (vard.getC, var2.getQ)) Labelroot, root.titleC“Adventure Gane), texte">>>>s>>>>>Your adventure roleccececce Using Modules ) Pygame Module PYGAMING Pygame isn't an inherent module to Python but those using the Raspberry Pi will already have need to use: pip install pygame From the command prompt. ‘any of the Functions being used: import pygane pygane. init installed. Everyone else BED yes cstcsete ner ccacypone import pygame from pygane. locals import * pygane. init) ‘gamewindow=pygane. di spLay.set_mode((800, 600)) Pygane. display. set_caption(“Adventure Gane”) runningeTrue hile running: for event in pygane.event.get(): if event -type==QUIT: running=False Pygane.quitC) fle_Esk Famat Bun Getone Windows Heb FEE Ei ccate uport FETED 2t's create a simple game ready window, and give itatite: Frame. display-set-caption( "Adventure cane") ‘gamewindon=pygane. di spLay.set_node((800, 600)) pygane. display. set_caption(“Adventure Gane”) You can see that after the fist ine is entered, you need to click back into the IDLE Shell to continue entering code; also, you can change the ttle ofthe window to anything you ike, unningetrue Tunninger ise Prameseuit0) ~ pygame Module cl ESTEE the Pygame window sil won't close don't worry it's just a discrepancy between the IDLE (which is written with Tkinter) and the Pygame module. F you ‘un your code va the command tne, it closes perfectly well You're going to shift the code around abit now, running the main Pygame code within a while loop; Itmakes it neater and easier to Follow. We've downloaded a graphic to use and we need to set some parameters for pygame: ‘import pygame pygane. initQ running=True while running: ‘gamewindow=pygane. display. set_modeC(800,600)) Pygane. display. set_caption(“Adventure Gane”) black=(0,0,0) white=(255,255,255) oo nite eum gmerindow-pygane. display set_node((800.600)) Presme, display setacaption( Adventure Cane") Biseke‘o.0-0) seniten( 255,235,255) “ngspygae image lad“ /hone/ps/Downoade/sprste) png det spritecs.y) imerindon 1stCam, (4.99) ‘img=pygame. image. load(“/home/pi/Donnloads/ spritel.png”) def sprite(x,y): gamewindon.blitCimg, (x,y)) x=(800*0.45) ‘y=(600*0.8) ganewindow.flUCwhite) sprite(x,y) ygame display. update) for event in pygane.event.get(): ‘if event. type==pygane. QUI downloaded image called sprite1.ong and allocated it to the variable img; and also defined a sprite Function and the Bit Function will allow us to eventually move the image. ganenindon-fillemhite) Spritecny) yzone.dizplay.upeatec) for event in pygane.event.get() event. RypersdutT eningeeaise Pyeanes quite z= Using Modules FeTeeE AD Now we can change the code around again, this time containing 3 movement option within the \while loop, and adding the variables needed to move the spite around the screen: ‘import pygame from pygame.locals import * pygame. init) running=True ‘ganewiindow=pygame display. set_node((800, 600)) ygame display. set_caption(“Adventure Game”) blacks(0,0,0) whites(255,255,255) ‘img=pygame. image. Load(“/home/pi /DownLoads/spritel. png”) def sprite(x,y): ‘gamewindow.bLitCima, (x,y) xchange=0 ‘imgspeed-0 white running: for event in pygane.event.get(): if event. type==QU running=False ‘if event. type == pygame.KEYDONN: if event. key==pygane. K_LEFT: xchange=-5 elif event .key==pygame.K RIGHT: xchange-5 if event. type==pygame. KEYUP: if event. key==pygane.K_LEFT or event keye=pygane.K RIGHT: xchange=0 x 4= xchange ganewindow.flLCwhite) sprite(x,y), pygane display. update) pygame. quit©) PEPER Cony the code down and using the left and right arrow keys on the keyboard you can move your sprite across the bottom of the screen. Now; it looks ike you have the makings ofa classic arcade 20 scroller inthe works. sea Pygame Module ‘Youcan now implementa few additions and wise Pygae.display.Fiip) Sua) ‘some previous tutorial code. The new elements are clock. tick(60) the subprocess madule, oF which one Function llowsus to launch a continue second Python script From within another andwe're going tocreatea ‘break ewe caled pygaretst.y rete ‘import pygane inport tine TrROREI SLE GOERS Ps tone bm rn we pygae. init ‘screen = pygane.display.set_node((800, 250)) clock = pygane. time. Clock font. = pygane. font..Font(None, 25) Joos tar vecrrocs weer, 0) Pygame. time. set_timer(pygane.USEREVENT, 200) |=" seneworcnss def text_generatorCtext): | ap "i for letter in text: PT ie, ct, we, mame ‘tmp += letter a - if letter f= 6 *: 000 yield tmp lass DynanicTextCobject): or reeeman def init__(self, font, text, pos, i autoreset=False): sself.done = False self.font = font self.text = text self._gen = text_generator(self. text) ‘saligmostaipos Sree teEF ean, tpn self.autoreset = autoreset ees tg ema nari rs re he rm rh rd self updateC) i = rn tert, (rete text_generator(self. text) z False soa nse i ‘self .updateQ) = def updatesetf): es ieee So a try: self.rendered = self.font. ‘when you run this code it wil display long, render(next(self..gen), True, (@, 128, 0)) ‘atrow Pygame window with the into text except Stoplteration: scroling tothe right. fee a pause often seconds, itthen launches ‘self done = True the main game Python script where you can move the warrior sprite time.sleep(10) around. Overall the effect is quite good but there's always room ssubprocess.Popen(“python3 /home/pi/Documents/ _forimprovement. Python\ Code/pyganel.py 1”, shell=True) def dran(self, screen): screen. blit(self.rendered, self.pos) ‘text=("A long time ago, @ barbarian strode from the frozen north, Sword in hand...) message = DynamicTextCfont, text, (65, 120), ‘autoreset=True) while True: for event in pygame.event .get(): ‘if event.type = pygane.QUIT: break if event. type — pygane.USEREVENT: message. date ‘screen. fil (pygane.color.Color¢‘black’)) mmessage.dran(screen) t @) Using Modules Create Your Own Modules BUILDING MODULES ‘Modules are Python files, containing code, that you save using a py extension. These are then i import command. ported into Python using the now fami PETISEDD L New Fle ands Ed > Paste nthe new window You now have {wo separate Fes one vith the funtion dtntions te ater th the function cl PEP you now tryand execute the basie_math.py code ‘again, the error‘NameEsror: name ‘timestwo' is not defined! willbe displayed, This is due to the code no longer having access to the function definitions. St FEED Retumtothe newly created ‘window containing the Function definitions, and click File > Save {s, Name this minimath.py ‘and save it in the same location asthe original basic math. Py program. Now cose the minimath py window, so the basic_math.py window is left open. PEPTIDD b2ck to the basic_math.py window: a the top ofthe code enter: fron minimath import * ‘Thiswill import the Function definitions as a module, Press FS to save and execute the program to see tin action, FEPTIEDD You can now use the code further to make the program alittle more advanced, utilising the newly created module to its Full Include some user interaction, Start by creating a basic menu the user can choose from: print¢“Select operation.\n”) print¢“1.Times by tno”) print¢2.Times by Three”) print¢3. Square”) print¢“4.Poner of”) choice = input¢“\nEnter choice (1/2/3/4):”) unl = Now we can add the user input to get the number the code will work on: intCinput(“\nEnter number: “)) Thiswillsave the user-entered number as the variable num Ble Edt Format Bun Options Windows Help ‘from minimath inport * print("Select operation.\n") irint("2.Tames by Thr irint("3.Square") print("4:Poner of") fas "1.Times by two" choice = input("\nénter choice (1/2/3/4):") punt = int(input("\nenter number: » l 6 (_ Create Your Own Modules Finally, you can now create a range of if statements. BLEED «> etcrmine what to dowith the number and utilise the newly created function definitions: if choice = ‘1’: printCtimestwoCnumt)) elif choice == ‘2 print(timesthreeCnumt)) elif choice == ‘3’: print(square(num)) elif choice == <4": num2 = intCinputC“Enter second number: print(poner(numl, nun2)) else: printC*Invalid input”) » 1s Eat Frat at opens sone tp Note that forthe ast valable options the Power SrePilo of choice, we've added a second variable, num2. Tis pases asecond number trough the function definition cle power Save and eect program a seein acon C+ Input/Output S aa aeleieg Output Bee Eee hl aU ele eel La) etree ee eae input to produce something that the user can see. ea eee iti uccceurur a CNM Rea eum ee Dc) Ev ela le Urge les uM ievecm elms Tl} constants and file input and output are all covered jin the following pages. All of which help you to understand how a C++ program works better. cee ee ~ z= C++ Input/Output ) User Interaction Dearne Mice ee Sait ect ae Tecan tcc cos oR ORES basic user interaction is one of the most taught aspects of any language and with it you're able to do much more than simply greet the user by name. HELLO, DAVE You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard put stream, to prompt a user response. ETeGRED A rything that you want the user to input into the program needs tobe stored somewhere in the system memory soit can be retrieved and used. Therefore, any input mus fist be declared asa variable, so it's ready to be used by the user. Start by creating a blank C++ file with headers. Winclude using namespace std int main () FETESEDD The date type ofthe variable must also match the type of input you want from the user. For example, to aska usertheir age, you would use an integer tke this: #include using namespace std; int main © { int age; cout << “what is your age: cin >> ages cout <<”\nYou are “ << age << * years old.\n”; FESED) The cin command works in the opposite way from the cout command, With the Fist cout ine you're ‘outputting ‘Whats your age’ to the screen, as indicated with the ‘chevrons, Cin uses opposite Facing chevrons, indicating an input. The input is put into the integer age and called up in the second cout ‘command. Build and run the code. PEFR you're asking a question, you need to store the inputas@ string; to askthe user thei name, you would use: #include using namespace std; int main © { string nane; cout << “shat is your name cout << “\nello, “ << name << “. I hope you're well today?\n"; I aia ea = ee Sie = Zon (User Interaction ‘SC ESTeGEERD The principal works the same as the previous code. “The user's input, theirname, is stored in a string, because it contains multiple characters, and retrieved in the second cout line, As long as the variable ‘name’ doesn't change, then you can recalit wherever you liken your code Barer You can chain input requests to the user but just make sure you havea valid variable to store the input to begin with. Lets assume you want the user to enter two whole numbers: #include using namespace std; int main © ‘int num, mums cout << “Enter tno whole nunbers: cin >> num >> num2; cout << “you entered “ << numl << “ ‘pun << “\n"; and “ << FETTER Likewise, inputted data can be manipulated once you have it stored in a variable. For instance, askthe ser Fortwo numbers and do sore maths on them: #include using namespace std; int main © { float num, nun; cout << “Enter two nunbers: \n"; cin >> num >> nun2; cout << num <<“ +“ using namespace std; int main © { string mystr cout << “Enter a sentence: \n"; getline(cin, mystr: cout << “Your sentence is: “ << mystr.size) << characters long.\n"; FETED sui and execute the code, then enter a sentence with spaces. When you're done the code reads the number of characters. IF you remove the getline line and replace it ‘with cin >> mystr and try again, the result displays the number of characters upto the frst space, Gettine is usually a command that new C++ programmers forget to include. The terminating white space is annoying when you can't figure out why your code isn't working. In short, i's best to use getlne(cin, variable) in Future: #include using namespace std; int main © i string nane; cout << “Enter your full name: \n?; getlineCcin, nane); cout << “\nHello, “ << name << “\n"; ~ z= C++ Input/Output) Character Literals In C++ a literal is an object or variable that once defined remains the same throughout lent Reolel MRC eee Rel Cek ND e Ch enEen AUR ol RC eee cuog fete cutscene Ue ESCAPE SEQUENCE When used in something like a cout statement, character literals are also called Escape Sequence Codes. They allow you to, ‘and much more. sert a quote, an alert, new BPTSERD reate anew c+ Fle and enter the relevant headers: #include using namespace std; ‘int main © ESTeER Youve already experienced the \n character literal placing anew tine wherever i’ called. The line: cout -<<"Hello\n” <<"I'ma C¥4\n" << "Program\n"; outputs three lines of text, each starting after the last. x eden [slog FETED you vanted toinsert speech quotes inside @ cout statement, you would have to use a backslash as it already uses quotes: #include using namespace std; int main © { cout << “Hello, user. This is how to use V'quotes\”.”5 FST There's even a character literal that can trigger an alarm. In Windows 10, isthe notification sound that chimes when you use \a Try this code, and turn up your sound, #include using namespace std; int main © i cout << “ALARM! \a"; } Rie =| rm- using namespace std; ‘int main © { cout << “\U00A9"; CHARACTER TABLE ‘Acomplete list of the available Unicode es mouse over the character to see its nique code to enter in C+. ~ z= C++ Input/Output ) Defining Constants Constants are fixed values in your code. They can be any basic data type but as the Meets eet ieee rset mele en ceto Merle Peek ine onde ee ai erect Kona #DEFINE The pre-processors are instructions to the compiler to pre-process the information before it goes ahead and compiles the code, clude isa pre-processor ass #define. BETTE You can use the itdefine pre-processor to define any constants you want in our code, Start by creating a new C+ file complete withthe usual headers: #include using namespace std; int main Q Gis ther with Now let's assume your code has three different constants: lenoth, width and height. You can define #include using namespace std; define LENGTH 50 define WIOTH 40 define HEIGHT 60 int main © BETS RD Note the capitals for defined constants i's considered good programming practise to define all constants in capitals. Here, the assigned values are 50, 40 and 60, 50 let's callthem up: #include using namespace std; ‘define LENGTH 50 define WIDTH 40 define HEIGHT 60 int main © i cout << “Length is: “ << LENGTH << “\n"; cout << “Width is: “ << WIDTH << “\n"; cout << “Height is: “ << HEIGHT << “\n"; Buld and run the code. Just as expected, i isplays the values for each of the constants created, ls ‘worth noting that you don't need a semicolon when you're defining a constant with the #define keyword. You can also define other elements as a constant. For example, instead of using \n for a newline in the cout statement, you can define it at the start ofthe code: #include using namespace std; define LENGTH 50 define WIOTH 40 define HEIGHT 60 define NEWLINE ‘\n? int main © { cout << “Length is: “ << LENGTH << NEWLINE; cout << “Width is: “ << WIDTH << NEWLINE; cout << “Height is: “ << HEIGHT << NEWLINE; The code, when built and executed, does exactly the same as before, using the new constant NEWLINE toinserta newline in the cout statement. Incidentally, creating @ ‘newline constant isn'ta good dea unless you're making it smaller than \n or even the endl command. BETTER Defining a constant isa good way of iitalisng your base values atthe stat of your code. You can define that your game has thre tives, or even the value of Pl without hhaving to call up the C++ math brary #include using namespace std; define PL 3.14159 int main © { cout << “The value of Pi i “ ce PI << endl; - (_ Defining Constants Cl Aroher method of dering a constant withthe SIE) ‘const keyword. Use const together with a data type, variable and value: const type varable= value. Using Pi as an example: #include using namespace std; int main © { const double PI = 3.14159; cout << “The value of Pi is: “ << PI << endl Because you're using const within the main block of code, you need to finish the line witha semicolon. STEP 9 You can use either, as long asthe names and values don't clash, but it’s worth mentioning that #define requires no memory, so iF you're coding toa set amount of memory, tdefine is your best bet Const works in much the same way as define You can create static integers and even newlines: #include using namespace std; int mainQ) i const int LENGTH = 50; const int WIDTH = 40; const char NEWLINE = ‘\n"; int area; area = LENGTH * WIDTH; cout << “Area is: “ << area << NEWLINE; oer File Input/Output The standard iostream library provides C++ coders with the cin and cout input and Cote Maa arena UNA Nod Ell ANCE R CROMER eR Lel ce) (ile olent- 1m Great In el Ce ec FSTREAMS There are two main data types within the fstream library that are used to open ale, read from it and write to it, ofstream and stream. Here's how they work, “The First task sto create a new C+ file and along \We've included commentsin the screenshot of step withthe usual headers you need to include the new 2 tohelp you understand the process. You created fstream header: string called name, to store the usersinputted name. You also created a textfile called name.txt (withthe ofstream newfle and newfile.open lines), asked the user for their name and stored it and then writen the data to the fle #include #include Using namespace std; int main © t i ‘incluae finclude ‘using namespace std: FPR To read the contents ofa file, and output it to the screen, you need to do things slightly differently. First you need to create a string variable to store the file's contents at {ine by ine), then open the file, use getline to read the fil line by tne and output those nes to the screen Finally, close the le tnt main 0) Begin by asking a user For their name and writing string line; Siar that information tafe. You need the usual string tostore the name, and getline to accept the input from the user. #include include using namespace std; int main © { string none; ofstream newfile; rnewfile.open(“nane. txt"); cout << “Enter your name: “ << endl; getlineccin, none); ewfile << name << endl; nenfile.close(); ifstream nenfile (name. txt”); cout << “Contents of the file: “ << endl; getlineCnenfile, Line); cout << Line << endl; nenfile.closeQ; b: string Lines ifstream newfie (*c:\\users\\davia\\ Document's\\Cinmeria. txt"): cout << “Cimeria, by Robert E Howard: \n” << endl virile CgetlineCnewfile, Line)) cout << Line << endl; newfile.closeQ); os Lan FEED Youcanno doubt see that we've included a while loop, which we cover ina Few pages Lume, le means that while there are lines to be read from the text file, C44 getlines them. ‘Once all the lines ae read, the outputis displayed on the screen and the fief closed. PEPTIEDD You can also see thatthe location ofthe text Fle Cimmeria.txt isnt inthe same Folder asthe C++ program, When we created the first name txt ile, t was writen to the same folder where the code was located; this is done by default To specify another Folder, you need to use double-back slashes, as per the character literalsfescape sequence code. Fienpuount CREE cout << “Enter your none: “ << endl; getline(cin, nane); nenfile << nane << endl; cout << “\nHow old are you: “ cin >> ages nenfile << age << endl; newfile.closeQ; << endl; FEED the code from step 8 difers again, But only where it comes to adding the age integer. Notice that ‘we used cin >» age, instead ofthe previous getine(cin, variable) The reason for thiss thatthe getline Function handles strings, not, integers; so when you'r using a data type other than a string, use the standard cin, Here's an exercise se ifyou can crest code to Sarid write several different elements to a text file. You canhavea wser'sname pe phone nuber etc Maybe even the value of Piand various mathematical elements t's all good practice newt can yo cm oh WHAT IS BERG Lae en ee cd providing you various content: LC Coe a a ae ee ee ee CCS eM Co [ooo 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 to Brand new content elt et) AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu Loops and Decision Making Rete Wei e UL ema es eee ace eee UTR Cle [tLe Lert tele Me ere Pcl en le ely exactly what you want it to and delivers the COST Rll cee Rae a ee cel Without loops and decision making events within the code, your program will never be able to offer Or eee ee eRe Ueto Feit Tar eR Cee ET TUE etme Lance om Co z= Loops and Decision Making While Loop Pe Seis Mine eee curl Saget aCe Tec condition remains true. When the while loop starts, it initialises itself by testing the Conoco mascot artes os TRUE OR FALSE? While loops are one of the most popular Form of C++ code looping. They repeatedly run the code contained within the loop while the condition is true. Once it proves False, the code continues as normal Ceahstyovedonesoficadcesteanew coe TERED Fetyou nap) file, There's no need For any extra headers at the Sua?) need to, moment oad the sande Jheades ape sul create acondtions0 we 8 Vatibl called num and ie itthe valve 1, Now create the while loop, stating that #include using namespace std; int main © along as numis ess than : 30, the loop is true. within the loop the value of num ' is displayed and adds 1 until its more than 30. PEP D Were introducing afew new elements here, The first ae the opening and closing braces For the hile loop. This is because our loop is a compound statement, meaning a group of statements; note also, there's no semicolon after the while statement. You now also have return 0, which isa clean and preferred way of ending the code, Creat simple wile oo, Ente the code below, eu? build and run (we've added comments to the screen shot) t oo int nun = 15 . while (nun < 30) nine { cout << “Number: “ << num << endl; run = num #1; : [ster ) I compound while statement and instead just added num by itself Until reached 30, and then displayed the value { int num = 15 _— while Crum < 30) cout << “Number: “ << num << endl; return 0; Iesimportan to remember nt toad semicolon Suz at the end of a while statement. Why? Well, as you know the sericlon represents the endo C++ ne of coe. you lace one athe end of while statement your loop wl be permanent tuck unl you dose the program Inour example, if we were to execute the code the value of num would be 1, as et by the int statement. When the code hits the while statement it reads that while the condition of 1 being less than 30 strue loop. The semicolon closes the line, so the loop repeats; but It never adds 1 to ‘num, as it won't continue through the compound statement. BSTeEE RD You can manipulate the while statement to display different results depending on what code lies within the loop. For example, to read the poem, Cimmeria, word by word, you would enter: #include #include using namespace std; int main © ‘ string word; ifstream newfile (*C:\\users\\david\\, Documertts\\Cimmeria, txt”); cout << “Cimmeria, by Robert E Howard: \n” << endl; wile (newfie >> word) { cout << word << endl + return Q; © While Loop Cl #include #include using namespace std; int main © { string word; ifstream newfile (*C:\\users\\david\\, Docunents\\Cinmeria.txt" cout << “Cimmeria, by Robert E Howard: \n” << endl; while (newfile >> word) { cout << word << endl; Steep(1000); } return 0; ‘Sleep() works in milliseconds, so Sleep(1000) is ‘one second, Sleep(10000)sten seconds and so ‘on. Combining the sleep function (long with the header it needs) {anda while loop enables you to come up with some interesting countdown code. #include include using namespace std; int main © i int @ = 10; while Ca != @) { cout << a << endl; a=a-1; Steep(1000): cout << “\nBlast OFF!" << endl return 0; Insome respects, a for loop works in a very similar way to that of a while loop, although it's structure is different. A for loop is split into three stages: an initialiser, a condition and an incremental step. Once set up, the loop repeats itself until the condition becomes False. LOOPY LOOPS The initialise stage of a for loop is executed only once and this sets the point reference for the loop. The condition is evaluated by the loop to see ifit’s true or False and then the increment is executed. The loop then repeats the second and third stage. FERED ciesteanewc++file wth the standard headers: RIBBWFB) ater the loop, you created a compound statement in braces (curly brackets), that displays the current #include Sc MaRS MME |—_______ using namespace std; return 0; int main © i //For Loop Begins BREED Working through the process ofthe for loop, begin for( int a= 10; a != 0; a= by creating an integer called num and assigning ita { value of 1. Next, setthe condition, n this case num being less than cout << a << endl; 30. The lst stage is where you create the increments; here ts the SLeep(1000); ‘value of num being added by 1, z cout << “\nBlast OFFI” << endl; si aeteal return 0; for( int mum = 1; mum ¢ 30; mom = mum si) Wwesibecutéoun cade dnt farstoicae ETRERE ve'sn eal aferloy deatte Suz the windows.h library, so you can use the Sleep Sua) multiplication tables of a user inputted number. command, Buld and un the code: nthe command consleyoucen Handy for students seetherubers 1080 ountdoumin onesecondreeren stl reaches ero and las OF appes, int ny 1 cuneate cout << “Enter a nunber to view its times table: “5 cin >> nj for Cint i=; i

You might also like