0% found this document useful (0 votes)
60 views

Tricks and Tips - C++ & Python - 16th Edition 2023

Uploaded by

Eric Kwong
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
60 views

Tricks and Tips - C++ & Python - 16th Edition 2023

Uploaded by

Eric Kwong
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 78
@ Next level secrets zi and fixes get tothe [i aVag se] you need to take peat ee our coding & programmin coding language MA 1 Ms) prog ) UR oh dat cm (ayes SECRETS & HACKS @ We share our awesome tips and shortcuts for coding Python and C++ @ Advanced guides and tutorials for programming with C++ & Python FREE Software! Great Games! Essential Hardwa ak, 192ateere Re. IES INSIDE! ome Head over to your web browser and follow these simple instructions... 1/ Enter the following URL: www.pelpublications.com/exclusives 2] sign up/in and from the listings of our exclusive customer downloads, highlight the Tech Shopper Magazine option. 3/ Enter your unique download code (Listed below) in the “Enter download code” bar. 4] Click the Download Now! Button and your file will automatically download. 5/ Your file is a high resolution POF file, which is compatible with the majority of customer devices/platforms. PCL37862RE NOTE: This is limited reader offer running from Ist November 2023 to Tet March 2024. Terme and conditions apply and can be found at www.pelpublicationscom TRICKS & TIPS C++ & Python Tricks & Tips is the perfect digital publication for the user that wants to take their skill set to the next level. Do you want to enhance your user experience? Or wish to gain insider knowledge? Do you want to learn directly from experts in their field? Learn the numerous short cuts that the professionals use? Over the pages of this essential advanced user guide you will learn everything you will need to know to become a more confident, better skilled and experienced owner. A user that will make the absolute most of their coding use and ultimately Over the page the platforms themselves. our Journey contin An achievement you can and we will be sagas earn by simply enabling us at every stage t, . et e te i inspire you to” 90 Further. to exclusively help and teach you the abilities we have gained over our decades of experience. Contents me Orn kc) One) Lists While Loop 10 Tuples 58 ForLoop 12 _ Dictionaries 60 Do... While Loop 14 Splitting and Joining Strings 62 IF Statement 16 _ Formatting Strings 64 If... Else Statement 18 Date and Time 20 _ Opening Files oe 22 Writing to Files PA Ria k eke 24 _ Exceptions 68 Common Coding Mistakes 26 Python Graphics 70 _ Beginner Python Mistakes 72__ Beginner C++ Mistakes & Using Modules 74 Where Next? 30 Calendar Module 32 OSModule 34 Random Module 36 Tkinter Module 38 Pygame Module 42 Create Your Own Modules 44) C++ Input/Output 46 _ User interaction 48 Character Literals 50 Defining Constants 52__ File Input/Output — ( Contents Cl "..We've taken two of the most powerful and versatile ramming languages ~ E available, Python and id broken them, € down into bite-sized tutorials and guides to help you learn how they work, and how to make them work for you... TT Working with Data) Working Vaan Dye] er- Peer tai mW un seth Ke Ceol cel MELO ECR nek Python to your every demand. Over these RoE Re Ole ela a elke) fare )eo Ma) (ome (tea ENR CTU Le co} Peterlee Rime ie CLs Then, you can learn how to use date and time Functions, write to Files in your system and even create graphical user interfaces that take your coding skills to new levels and into new Polke) rad (ol Ce Zz » Working with Data : Lists Lists are one of the most common types of data structures you will comes across in 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 lists, and lists within lists. EEG EDD Alissa sequence of data values calleditems. You [BETESEWM You can also access, or index, the last tem in alist by create the name of your lst followed by an equals Using the minus sign before the item number Et), ‘sign, then square brackets and the itemns separated by commas; or the second to last item with [-2] and so on. Trying to reference an note that strings use quotes: item that isn’t in the list, such as [10] will return an error: numbers = [1, 4, 7, 21, 98, 156] numbers[-1] mythical_creatures - [“Unicorn”, “Balrog”, mythical_creatures[-4] “Vampire”, “Dragon”, “Winotaur™] FETED orxe you've defined your list you can call each FTE DD tiing is similar to indexing but you can retrieve by referencing its name, followed by a number. Lists multiple tems in a ist by separating item numbers start the firsttem entry as 0, Followed by 1,2, 3 and soon. ‘with a colon. For example: For example: nunbers[1:3] Lalaiecas ‘will output the 4 and 7, being tem numbers 1 and 2. Note that the To call up the entice contents of the lst. returned values don't include the second index position (as you ‘would numbers{t:3] to return 4,7 and 21), punbers[3] ‘Tocall the third From zero temin the lst 21 in this case). ‘You can update tems within an existing list, eemove items and even join lists together. For example, to join two lists you can use everything = nunbers + mythical_creatures: ‘Then view the combined list with: everything BTID cers can be added to a list by entering: nunbers-nunbers+[201] Or forstrings: nythical_creatres=nythical_creatures+[*Griffin"] ‘Or by using the append Function nythical_creatures .append(“Nessie”) ‘nunberss. append(278) Removal of items can be done in two ways. Te First Is bythe tem number: del nunbers[7] ‘Alternatively, by tem name: inythical_creatures.renove("Nessie”) ‘You can view what can be done with lists by entering >>>>>>>>Leap Year Calculatorccecccecee\n” )ylaintCinput“Enter the first year: “)) y2nintCinput(“Enter the second year: “)) Veaps=calendar.Leapdays(y1, y2) print(“Nunber of Leap years between”, yl, “and”, ye, “is”, Leaps) ‘You could even fashion that particular example into ‘apiece of working, user interactive Python code: PPID You can alco create a program that will display all the days, weeks and months within a given year: import calendar year=intCinputC“Enter the year to display: “) print(calendar.preal(year)) |We're sure you'll agree that’s quite 3 handy bit oF code to have tohand. Interestingly we can aso lst the number of daysin 2 ‘month by using a simple For loop: import calendar cal=calendar. TextCalendar(calendar -SUNDAY) for i in cal.itermonthdays(2018, 6): print(i) fe tm onto ro BAR cos cvuicurgicciomematc BERD wosccsocstonescemina referee poten aren month. So the counting ofthe days will start on Friday 1st June 2018 and will total 30 as the output correctly displays. (Calendar Module ( CG BETeEED You're also able to print the individual months or days ofthe week import calendar for name in calendar month name: printCname) ‘import calendar for name in calendar .day_name: print(nane) PPD The calendar module also allows us to write the Functionsin HTML, so that youcan display iton a website. Let's start by creating a new file import calendar cal=open(“/hone/pi/Document's/cal .htmL” cecalendar .HTMLCalendar(calendar . SUNDAY) cal.write(c. formatmonth(2018, 1)) cal -close() ‘This code wil create an HTML file called cal, openit witha browser and it displays the calendar for January 2018. Te EREE 0f course, you can modify that to display a given, year asa web page calendar: ‘import calendar year=int(input(“Enter the year to display as a webpage: “)) cal=open(“/home/pi/Documents/cal.html”, “w") cal .write(calendar.HTMLCalendar(calendar..MONDAY). formatyear(year)) cal.close() ‘This code asks the user fora year, then createsthe necessary ‘webpage. Remember to change your File destination, z=) 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. ESTED voucan startthe 0s module with some simple PETER the windows output isifferent as that's the Functions to see how it interacts with the operating current working directory of Python, as determined system environment that Python is running on. IFyou'e using Linux by the system; as you might suspect, the os.getcwd( Function is orthe Raspberry Pty his asking Python to retrieve the Curent Working Directory Lnuuses villse something along the same nes asthe Raspbery Pas wil SoPEREEE maxcosusers mene hone-os..getowd() printchane) Tretuedreitrompatngtniie tone REM ere reenter te OS male eleiZ is the current user's home folder on the system. ued is its ability to launch programs that are installed Inour example that's home/oiitwillbe different depending on _in the host system. For instance, iFyou 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. import os 5 browser-os..system(“/usr/bin/chromium-bronser") The os system) function s what allows interaction with external programs; you can even call up previous Python programs using this method. You will obviously need to know the ful path and program filename for it to work successfully, However, you can use the following: import os os.systen(‘start chrome “https://mmw.youtube.con/ Feed/music”?) FETED £0" Step 5's example we used Windows, to show that the OS module works roughly the same across allplatforms. In that case, we opened YouTube's music Feed page, so itis therefore possible to open specific pages: import os os.system(‘chromium-browser “http:// bbdmpublications .com/"*) Perea Note in the previous step's example the use of single and double-quotes. The single quotes encase the entire command and launching Chromium, whereas the double ‘quotes open the specified page. You can even use variables to call, multiple tabsin the same browser: import os ‘-(‘chromium-browser “http://bdnpubl ications. con/”?) b=C‘chromium-browser “http: //ww.google.co.uk”?) ‘os. system(a + b) (0s Module cH ‘The ability to manipulate directories, or folders if {you prefer, is one of the OS module's best features For example, to create a new directory you can use: ‘import. os, fs. mkdi rC*NEW") This creates a new directory within the Current Working Directory, named according to the object the mkdir Function. You can also rename any directories you've created by entering STEP 9 import os os.rename(“NEW", “OLD") To delete them: ‘import. os, os.rmdirr(*OLD") —_———_ ‘Another module that goes together with OS is shutil You can use the shutil module together with OS and time to create a timestamped backup directory, and copy ies into: ‘import os, shutil, time root_sre_dir = r*/home/pi/Document's” root_dst_dir = ‘/hone/pi/backup/? + time-asctime() for src_dir, dirs, files in os.walk(root_src_dir): dst_dir = src_dir.replace(root_srcdir, root_ dst_dir, 1) if not os.path.exists(dst_dir os .makedirs(dst_dir) for file_ in files: src_file = os.path.join(src_dir, file) dst_file = os.path. join(dst_dir, file) if 05.path.exists(dst_file): os.renove(dst_file) shutil.copy(src_file, dst_dir) print(“s>ss>sss>>Backup completeccecceRandom Word Finderceceeccece”) primt(“\nUsing a 466K English word text file I can pick any words at randon.\n”) nds-int(input("\nHow many words shall I choose? » with openc“/hone/pi/DowniLoads/words. txt”, “rt”) as, t words = f.readlines() words = [w.rstrip() for w in words] print¢* 2 for w in random.sanple(words, wds): print(w) a ) Using Modules ) Tkinter Module GETTING GUI ‘Tkinter 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 into it Before long you will discover just how powerful this module really is. “gers aly bit no Python, However es ous4) available when you enter: import tkinter, then youneedtopip install tkinter from te command promet We canstart to mport modules ferent thn before tosaveon ‘ying and by importing al ther contents import tkinter as tk from tkinter import * PPE DD snot recommended to import everything from a module using the asterisk butt won't do any harm normally. Let's begin by creating abasic GUI window, enter: wind-TkO) ‘This creates a small, basic window. There's nat much else to do at this point but click the Xin the comer to close the window. ‘The ideal approachis to add mainloop( intothe SMD et conrctheThter event op, but vel sgetto that soon, You've just created a Tkinter widget and there are several more we can play around with: btn-ButtonC) btn.packQ btn["text®: The first line Focuses on the newly created window. Click back into the Shell and continue the other lines. Hello everyone!” Ft ow ar PEED You can combine the above into a New File: import tkinter as tk from tkinter import * btn-ButtonC) btn.packQ btn[text”” Then add some button interactions: def clickQ: print(*You just clicked me! btn{"“conmand™}=click Hello everyone!” Save and execute the cade from Step 4 and a window appears with ‘Hello everyone inside. IFyou lick the Hello everyone! button, the Shell will output the text ‘You just clicked met. t's simple but shows you what can be achieved with a Few tines of code, You can also display both text and images within a Tkinter window. However, only GIF, BGM or PPM formats are supported. Sond an image and convert it before using the code. Here's an example using the BOM Publishing logo: from tkinter import * root = TkO, Logo = Photolmage(file=”/hone/pi/Downloads/B0M_logo. Gif”) Wi = Label(root, root.titleC“B0M Publications”), ‘image=Logo). 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 two to one of the biggest anes in global bookazine publishing, for two simple reasons. Our passion and commitment to deliver the very best product each and every volune. While ‘the company has grom with a portfolio of aver 250 publications delivered by our international staff, ‘the foundation that it has been built upon remains, the sane, which is why we believe BOM isn’t just the first’ choice it's the only choice for the smart. consumer. “”* w2 = Label(root,, justify-LeFT, padx = 10, ‘text=content).pack(side~"LeFt”) root mainloop() The previous codes ‘quite weighty, mostly ‘due to the content variable holding a part of BOM's About page from the company website. Youcan ‘obviously change the content, the root ttle {and the image to suit your needs BETEEE DD You con create rai buttons too. Try from tkinter import * root = Tk, v = IntVar() LabelCroot, root. titleC“Options”), text="""Choose @ preferred language:”*”, Justify = LEFT, padx = 20).pack() RadiobuttonCroot, ‘text-"Python”, padx = 20, variable=v, value=1) .packCanchor=W) variable-v, value=2).packCanchor=W) maintoop() You can also create check boxes, wth buttons and Siar) ‘output to the Shel from tkinter import * root = Tk, def var_states(): print(*Warrior: %d,\nMage: Kd” % (varl.getQ), var2.getQ)) Label(root, root. titleC“Adventure Gane”), text~">>>>2>>>>2Your adventure roleccc File) and create a True/False while loop: ‘import pygame from pygane. locals import * pygane.init() ganewindow=pygane display. set_node((800, 600)) pygane. dispLay.set_caption(“Adventure Gane”) running-True while running: for event in pygane.event.get(): if event. type=-QUIT: running-False pygane. quit) fle Est Farmat_ Bun tions Windows. Hep eerandoeytane splays nade 800600) SF event. SypenstutT BRED the Pyaame window still won't dose don't worry, it's ust a discrepancy between the IDLE (whichis written with Tkinter) and the Pygame module. I you run your code via the command ne, It closes perfectly well ESRD You're going to shift the code around a bit now, running the main Pygame code within a while loop; itemakes it neater and easier to Follow. We've downloaded a graphic touse and we need to set some parameters for pygame: import pygame pygame.imt) while running: gamewindow=pygane .dispLay. set_mode((800,600)) pygane.display.set_caption(“Adventure Gane”) black-(0,0,0) white=(255,255,255) PEPPD cx's quickly go through the code changes. We've defined two colours, black and white together with their respective RGB colour values, Next we've loaded the To pene 1 pgane locals oper * ‘ganerindon-pygane. splay .set_mode((800.600)) Breone display. setccoption-Aaventore cane") Biseke(0.0-0). sntten( 258,235,255) “ngspyeae. image Load“ /hone/p3/Oonnlosds/sprive} eng") et spritece 5 ( Pygame Module cl ‘img-pygane image. Load(/home/pi/Downloads/ spritel png”) def sprite(x,y): ganewindow.blitCing, Ox,y)) x-(800*0.45) y=(600"0.8) gamewindow -fiLLCwhitte) sprite(x,y) pygame..display.update() for event in pygane.event .get(): if event. type=-pygame.QUIT: running-False downloaded image called spritet.png and allocated it to the variable img; and also defined a sprite Function and the Blt Function will allow us to eventually move the image. (8000.45) yrts00"0"8) ganenrindon.£111(t6) Sprstecxey) Preane, display update) for event in pygane.event.get( SF event yper=qurr rumingeraise PramesauitO Using Modules ) FETTER) Now we can change the code around again, this imgspeed=0 time containing a movement option within the hile loop, and adding the variables needed to move the sprite ‘around the screen: while running: for event tn pygone.event.get(): ‘if event.type==QUIT: import pygane running-Patse speateeenerl oss eniwart if event. type = pyacme,KEYDOM: j {f event.Rey--pygane. CLEFT: running=True xchange _gamewindow=pygane. display. set_mode((800, 600)) ELLER EEE KESS=PHGOMNEFKORTGITE fvoane, display set-captionC*Adventure Gane") ceed ‘fF event. Rey==pygane.K.LEFT or event {ng-pygane image. Load(*/hone/pi/Domnloads/spriter, KeY=-Pygane. K RIGHT: png”) xchange=0_ def sprite(x,y): x += xchange ganewindow.blitCina, Cx.y)) ‘amewindow.fU1Cahite> ‘+ sprite(x,y) yocen0"0:8) pygame.display.update() xchange pygame. quit) BETTER) Copy the code down and using the left and right arrow keys on the keyboard you can move your spite across the bottom of the screen, Now, itlooks like you have the makings of a classic arcade 2D scroller inthe works. You can now implementa Few additions and utlise some previous tutorial code, The new elements are the subprocess module, of which one Function allows usto launch ‘second Python script from within another; and we're going to create a New File called pygametxt py: import pygane import time import subprocess ( Pygame Module cl Pygane. display ip) clock. tick(60) continue break pygame.quit() pygane. init) screen = pygame.display. set_mode((800, 250)) clock = pygane.time.Clock() font = pygame.font.Font(None, 25) Pygane. tine. set_timer(pygane.USEREVENT, 200) | def text_generatorCtext): | tm = 0 for letter in text: ‘tmp += letter if letter I= yield tp class DynanicText(object): def _init_(self, font, text, pos, autoreset-False): self.done = False self.font = font self.text = text self._gen = text_generator(self. text) self.pos = pos self.autoreset = autoreset self updateQ) def reset(self): self._gen = text_generator(self. text) self.done = False self update) def update(self): if not self.done: try: self.rendered = self. font. render(next(self..gen), True, (0, 128, 0)) ‘except Stoplteration: self.done = True time.sleep(10) subprocess. Popen(“python3 /home/pi/Documents/ Python\ Code/pyganel.py 1”, shell-True) def dran(self, screen): screen.blit(self.rendered, self.pos) text=(“A long time ago, a barbarian strode from the frozen north. Sword in‘hand. ..”) message = DynamicText(font, text, (65, 120), ‘autoreset=True) while True: for event in pygame.event .getQ: if event.type == pygane.QUIT: break if event. type — pygame.USEREVENT: message. vedate() screen.fill(pygane.color.Color( black’) message.dran(screen) When you run this code it wil display a tong, narrow Pygame window with the intro text scrolling to the right. After a pause often seconds, itthen launches the main game Python scriot where you can mave the warrior sprite around, Overall the effect is quite goad but there's always room For improvement. z=) Using Modules ) Create Your Own Modules BUILDING MODULES Modules are Python files, containing code, that you save using a .py extension. These are then imported into Python using the now Familiar import command. FETED cts start by creating a set of basic mathematics ‘square or raise a number to an exponent (power). Create a New File in the IDLE and enter: def timestwo(x): return x * 2 def timesthree(x): return x * 3 def square(x): return x def poner(x,y) return x ** y Under the above code, enter Functions to callthe code: print Ctimestwo(2)) print (timesthree(3)) print Csquare(4)) print (power(5,3)) ‘Save the program as basic_math.py and execute itto get the results. Now youre goingto take the function defintions oz) ‘out of the program and into a separate file. Hghlght the function dfintons and choose EG» Cut. Choose Fle = New File and use Ede> Paste nthe new window, You now have two separate es, one with the function defnkion, the oer ith the funtion alls PETER you now try and execute the basic math py code ‘again, the error ‘Namerror: name timestwo' is not defined’ will be displayed. This is due to the code no longer having access to the function definitions. TED Return tothe newly created window containing the Function definitions, and cickFile> Save |= : As. Name this minimath.py and save it in the same location a the original basic_math, y program. Now close the Iminimath.py window, sothe basic. math.py window islet open. Back to the basic math py window: at the top of the code enter: from minimath import * ‘This willimport the Function definitions asa module, Press FS to save and execute the program to see tin action ‘Youcan now use the code Further to make the programa little more advanced, utilising the newly ‘created module to its ful. Include some user interaction. Sart by ‘eating a basic menu the user can choose from: print(“Select operation.\n”) print(“1.Times by two”) print(*2.Times by Three”) printC*3.Square”) print(“4.Power of”) choice = input(“\nénter choice (1/2/3/4):") FER vec cnssotcvsrneuoseuiennc ED scars: num = intCinputC*\nénter number: “)) ‘This wll save the user-entered number as the variable numt Bile Edt Format Bun Options Windows Help Tron mininath inport * print("Select operation.\n") rint("1.Times by two") [rint¢"2.Times by Three) Brint(~3.Square") Print("4:Poner of”) choice = input(“\nEnter choice (1/2/3/4):") runt = int(input("\nnter number: ")) PRED Final, you can now create arange of if statements to determine what to do with the number and Utlse the newly created function definitions: if choice = ‘1’: print(timestwoCnumt)) elif choice — ‘2: print(timesthreeCnunt)) elif choice — ‘3?: print(square(num)) elif choice — ‘4: riun2 = intCinput(“Enter second number: )) print(power(num1, nun2)) else: print(“Invalid input”) (eat frat Bon Glos xndows wep BETSER DD Note that forthe last available options the Power of choice, we've added a second variable, aum2. This passes a second number through the function definition called ower, Save and execute the program to see itin action. (. Create Your Own Modules ¢ Cc ) XN C++ Input/Output ic) C++ Input/ Output There's a satisfying feeling when you program Peele Bare ea ee et ee al input to produce something that the user can see. eer eeu en aL) Eire er AY eeu] l(e) ean ee eal elas Ment elec eee RN) constants and File input and output are all covered in the Following pages. All of which help you to Ee eee) kee oon ee

You might also like