0% found this document useful (0 votes)
272 views84 pages

Python Tricks and Tips - 15th Edition 2023

Python Tricks And Tips – 15th Edition 2023

Uploaded by

In Tech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
272 views84 pages

Python Tricks and Tips - 15th Edition 2023

Python Tricks And Tips – 15th Edition 2023

Uploaded by

In Tech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Python Wy coding EIR elcid Everything you need to take programming C++ . erat your Python programming skills to the next level Next level fixes ENaC) LUST a a TU CEC J Gr aun Ce ORT RE Cee graphics, animation ETc FREE Software! Great Games! Essential Hardwa 19 AMAZING Ri WO Qs. Aa. Head over to your web browser and follow these simple instructions... 1/ Enter the following URL: [Link]/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 frorn Ist July 2023 to Ist December 2023. Terms and conditions apply anc can be found at [Link] TRICKS LAS Python Coding Python Coding 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 the new 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 and ultimately Python coding itself. An achievement you can earn by simply enabling us to exclusively help and teach you the abilities we have gained over our decades of experience. Over the page Our je Journey continues, and we will be wits, al every stage to ladbtee (aform and ultimately. spite you to 90 Further. i mined 30 ey 34 Et ET ety 40 co Text to Binary Convertor Jes und UL ee ZL coe Gam Random Password Generator Pree gene Mouse Controlled Turtle is a ea 7 Pn i) Oe ere eu cS 6 Ba @ a ements on eee meena eras a Rte (TELE TED lh wgiitus = ~~ “There's so much you can do with Python and within these pages you'll find everything you need to know to become a Python programmer, ready for the next level of advanced coding.” G Weelactiang at the cree ae = False ae ay i Core’ a | Using Modules ean eae Sete code for classes, Functions and global Ser CONUS Ue cee Gites een tetcuni and create even more spectacular sssBackup completecceececeee”) ina Using the Math Module Colt Tolman Mure ae eM Corel Ce OLR Reon ce Cece eT Maa COM Teel CHCA RUS mentioned previously in this book, mathematics is the backbone of programming and there's an incredible number of uses the Math module can have in your code. E=MC ‘The Math module provides access to a plethora of mathematical functions, from simply displaying the value of Pi, to helping you create complex 3D shapes. FR sath odie stuikinto Python’ sotheres ssyou ln doubtbe vere byron you team noneed toPP salt tht ther modules the nme tend onchons wnt present, you can import the module's Function by simply entering module you can specifically import them. For instance, the Floor and import math into the Shell, or as part of your code in the Editor. Ceil Functions round down and up a float: “tle E6t She Debug Opens Wodows HP yihey te Gril, Oe T9201, TTT (ee'a.oc1) on Line Ayes “ooyhsghess Screditar or “Licensety" for nore information. Python 3-42 (éefaule, Oct V9 2014, TaE3IF (eee 4.8.1} on Linu Type “copytaghe™, “credits” or “License()” for more infomation. SIS iSetaath injort Floor. ceil Soe Hser(t-2) D> eattcr.2y EEE porting the Math module il give you access to [EATER The Math module can also be renamed as you the module's code. From there, you can call up any import it as with the other modules on offer within ‘of the avallable functions within Math by using math, followed by Python. This often saves time, but dor‘t forget to make a comment the name of the Function in question. For example, enter: to show someone else looking at your code what you've done: math. sin(2) import math asm ; ‘This displays the sine of 2. nc (123.45) # Truncate removes the fraction [Python 3-4-2 (eefaule, Oct 19 2008, 13 {eee 4.8.1} on linwe Hype *copyrige®. “credits” or “License()* for nore information. PS" ingert math sw Sop mvbrne( 123.35) Scapytigne™, Meredite™ or “License()" Sao" pert ath ersopaonsneeseex7 Saf snore information. ‘Although it's not common practise, itis possible to impott Functions from 3 module and rename them. Oia In this example, we're importing Floor from Math and renaming it tof. although where lengthy code sin use, this process can quickly become confusing: Python $4.7 (Getault, Oct 19 2076, ype Scpyrsghe™, Seredsts” or “Lcense()* for more Snormat See restate ingore Floor 26 f 7 Imposing al the Functions ofthe Math Module can Siar bbe done by entering: hile certainly handy, thisis often frowned upon by the developer ‘community 3 it takes up unnecessary resources and isn’t an efficent way of coding, However, fit works for you then go ahead, vovafensedoesertaze ses Bee AD terestingly, some functions within the Math ‘module are more accurate orto be more precise are designed to return amore accurate value, than others. For example: i will etur the value of 0999999999, whereas: 2 (default, Oct 19-2048, 13:31) (ce 4.9.4) on time Type copyright”. “credits” or “License()* for nore information. DS" ron math port 33 sumttede teats 1 SPtaimctate te. Using the Math Module ea precise values For further accuracy, when it comes to numbers the ‘exp and expt Functions can be used to compute 42 Catal. Oot 19 2014, tien din ibe “copyright”, “credits” or “License()* for more information. DE" rsemath inport expe expe Teonopsoscabeastoe-os Teopopsosesieasene-05| Soa Ta This level of accuracy is really quite impressive, but ‘most used functions are e and Pi, where eis the numerical constant equal to 2.71828 (where the circumference of acircle i divided by its diameter BEER) The wealth of mathematical functions available through the Math module is wast and covers everything from factors toinfinity, powersto trigonometry and angular conversion to constants. Look up https//[Link]/3/ Uibrary/math html fora list of available Math module Functions. ED) virto Random Module The Random module is one you will likely come across many times in your Python programming lifetime; as the name suggests, it’s designed to create random numbers or letters. However, it’s not exactly random but it will suffice for most needs. RANDOM NUMBERS ‘There are numerous Functions within the Random module, which when applied can create some interesting and very useful Python programs. ESTED Just2s with other modules you need to import FETED fioweves: the Random module isnt used exclusively random before you can use any ofthe functions For numbers, You can use it to select an entry froma ‘we're going to look t inthis tutorial Let's begin by simply printing alist from random, and thelist can contain anything: random number from 1 to 5: ‘This will display one of the names of our adventurers at random, “which is a great adeition toa text adventure game. a ee perma oe al crea asa Se nhs ‘on biscunel oe rar BEER ou canextend the previous example somewhat by having random choice) select from alist of mixed variables, For instance: mnd-random. choice (1st) ERLE DD 012 bigger set oF numbers, including floating point values, you can extend the range by using the multiplication sign: Amport random Print (random. random() +200) ill cisplaya floating point number between O and 100, to the tune cof around fifteen decimal points. Pe ita han se. a, Ble ter) BRED | terestinaly, you can also use a function within the Random module to shuffle the items inthe list thus ‘adding alittle more randomness into the equation: ‘random. shuffle (1st) print (1st) ‘This way, you can keep shuffing thelist before displaying a random item From it. sh Using shuffle, you can create an entirely random lst of numbers. For example, within a given range: sd import random Aste [{1] for Tin vange(20)] ‘random. shuffle (1st) print (1st) Keep shuffling the lit and you can have a different selection of items From 0 to 20 every time, import random for i in range (10): print ([Link] (0, 200, 7)) Results will vary but you get the generalidea as tohowi works. Youcan also select arandom number frama given range in steps, using the start, stop, step loop: ReaD Letsuse an example piece of code which flips a virtual coin ten thousand times and countshow ‘many times it wil land on heads or tals Amport random output=("Heade”:0, coinsList (output keys ()) wraiier 0} for 4 in range(10000} ‘output [[Link] (coin) ) print ("Heade:", output ("Heads") print ("faile:", output [*Taile"]) Here's an interesting piece of code, Using atext Say file containing 466 thousand words, you can pluck a user generated number of words From the file (text file Found at: ‘[Link]/dwyVenglishawords}: import random print ("ssssssssssRandom Word Pinderceeeeeeeee") print ("\nUsing a 466K Englich word text file I can pick any words at random. \n") wdgeint (input (*\nllow many vos ” Sea TAUNTON TERED je shall 1 choose? "examen seecai words = [[Link]() for w in words] print ("= for w in [Link](words, was): print (w) print ("= =) EE) uirsioies ) Tkinter Module NNR Meh Vo IMeole (Air M ENA ENMRRMNeN eS PCa Python is capable of so much more. The Tkinter module enables the programmer to set VFO Te) )a (es MO Tm Nei cle MoM a ccir-le mia R Oa MOLE TaeR eS Saye] Vee WCU a kele 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. TERED Thinteris usually uit into Python 3. However iFit's available when you enter: import tkinter, then youneed to pip install tkinter from the command prompt. ‘We can star to import modules differently than before, to save on typing and by importing all their contents: PEPER 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: windemc() This creates asmall, basic window. There's not much elseto do at this point ut click the X in the comer to close the window. ryrenaa2stet |e ie at ag tien nan BATES) Te ideal approachisto add mainioop( into the code to control the Tkinter event loop, but well getto that soon. You've just created 2 Tkinter widget and there re several more we can play around with: [Link]() ben["text*]="ello everyone!" ‘The first line Focuses on the newly created window. Click back nto the Shell and continue the other lines. [Link]() btn["text*]="Hello everyone!" “Then add some button interactions: ‘irae pyaneppDoame jon Corareecoiel py B42) ~ 6 > (Be Git Fmt in tan nds He Fn go at ny PETIIM save and execute the code fromstep $ and a ‘window appears with ‘Hello everyone!’ inside. you. 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, FETTER Youcan also display both text and images within a Tkinter window. However, only GIF, PGM or PPM formats are supported. Sofind an image and convert it before using the code. Here's an example using the BOM Publishing logo: from thinter import + aif") WI = Label (root, root .title("BDM Publications”), image=1ogo) .pack (side="right") content = “"Y Prom its humble beginnings in 2008, ‘the EDM brand quickly grew from a single publication produced by a team of just two to one of the biggest names in global bockazine publishing, for two simple xeasone. Our passion and comnitmant to deliver the very best product each and every volune. While ‘the company has grom with a portfolio of over 250 publications delivered by our international staff, the foundation that it hae been built upon remaine the same, which is why we believe BOM isn’t just the first choice it’s the only choice for the smart 2 = Label (root, just ity=LErr, pad = 10, text =content) .pack (sie ‘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 [Link] and the image to suit your needs nome [pi /Dowloada/BOM ego. C Tkinter Module ¢ 0 ma PPD You can create radio buttons too. Try: from tkinter import * root = Tk() vy = mevar() Label (root, root. titie(*options"), text="*"choose: a preferred language:""*, justify = LEFT, pad Radiobutton root , text«"Python", padx = 20, variable-y, valueet) .pack (anchor=i) Radiobutton root , texters", mainleop() PEPIED You can also create check boxes, with buttons and ‘output to the Shel fom tkinter import * root = T() def var_evates( print (Warrior: 8d,\nMage: $a" © ([Link] (), [Link] ())) Label (root, root. titie(*Adventure Gane"), texte">s>ssss>ss¥our adventure rolecccceccee<") « grid(rowso, sticky=N) vari = IntVar() Checkbutton (root, text="Warricr*, variablesvart) grid(rowe1, sticky=W) var2 = IntVar() Checkbutton (root, text="Mage”, variable=vara) . grid(row-2, sticky-N) Button(roct, text=’Quit’, commanderoct .destroy) . grid(row-3, sticky-W, pady=4) Button(root, text='Show’, commandevar_states) grid(row=3, sticky=#, pady=4) mainleop() ‘The code from Step 9 introduced some new geometry elements into Tkinter. Note the sticky=N, E and W arguments, These describe the locations ofthe check boxes and buttons (North, East, South and West). The row argument places them on separate rows, Have a play around and see what you get . z= Using Modules ) Pygame Module We've had a brief look at the Pygame module already but there's a lot more to it that needs exploring. Pygame was developed to help Python programmers create either graphical or text-based games. PYGAMING Pygame isn’t an inherent module to Python but those using the Raspberry Pi will already have it installed. Everyone else will need to use: pip install pygame from the command prompt. EETEERED (Nturally youneed to load up the Pygame modules into memory before you'r able to utilise them. ‘Once that’s done Pygame requires the user tonialise it prior to ‘any ofthe functions being used: import pygame ygame. init () Let's create a simple game ready window, and give itatitle: gamewindow=pygane. display.set_node ( (800,600) ) [Link].set_caption(*adventure Gane") You can see that after the First line is entered, you need to click back into the IDLE Shell to continue entering code; also, you can change the title of the window to anything you like, Sadly you cn'close the ney created Pygame Suz? window without closing the Python IDLE Shell, which et very practical For thiseason, you ned to workin the editor (New > File) and create a True/False while (oop: import pygame ‘from pygame. locals import * pygane. init () ganewindowepygame display. set_mode ( (800, 600)) pygane. display.set_caption(*Adventure Gane") running=True while running: for event in pygame LE [Link]= running-False [Link]() le Edt Format Bin Gptions Windows Hep Trport pyeae Fon pygime locals inport * O runninget-ve ‘or teen 9 pragame-event. 880 ERED [the Pyaamewindowstil wont ===" lose don't worry, it's just 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 PETIED You're going to shift the code around abit 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. init () runningeTrue while running: ganewindowspygame .di splay. set_mode ( (800,600) ) [Link].set_caption(*Adventure Gane”) black= (0,0,0) whites (255,255,255) ( Pygame Module Cll ingepygane . image. 1ead (*/home/pi /Downloads/ sprite png”) def sprite (x,y) [Link] (img, (-¥)) x= (800*0.45) y=(s000.8) gamewindow. £112 (white) sprite(x.y) pygame-display-update () for event in [Link] .get() if event .type==[Link] running-False FETED cts auickly 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 a pene um pyganetocals import * ene. insei) gumenindowepygane display set node((800.600)) Breone display setccoption "Adventure cane") Biseks{0.0-0) wntten( 258,235,255) “nesPyeane. image Load“ /hone/p3/Oonnlosds/=prite} eng") et spritecay: ‘Gamenindon-b1ARCing. 6.99? downloaded image called spritet-png and allocated it to the variable img; and also defined a sprite Function and the lit Function will allow us to eventually move the image. ganeindow.F111(4hite) Speitecuy) Prbane: display update) or event in [Link]: SF event yper=@ulr rumingeraiee Presees quit) Pee z= Using Modules Now we can change the code around again, this time containing a movement option within the loop, and adding the variables needed to move the sprite ‘around the screen: import pygame rom [Link] import + pygane init () ganewindow=[Link].set_mode (800,600) [Link].set_caption (*Adventure Gane") lack=(0,0,0) whites (255,255,255) 4ing=pygame . image. 1oad (* home /pi /Downloads /spritel. png") def sprite (x,y) [Link] (img, (x,y) x= (800*0.45), ‘y= (600*0.8) xchange=0 imgepesd=0 if [Link] == pygame. KEYDOWN: if event -key==pygame.K LEPT: Lf event .key==pygame.K LEFT or event keyeepygame-K RIGHT: xchange=0 x = xchange ganewindow.£411 (white) sprite(x,y) [Link] () [Link] () BATE Co0y 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 like you have the makings ofa classic arcade 20 scroller inthe works. ( Pygame Modules Cll FETED Youcan now implement afew adaltions and utlise some previous tutorial code. The new elements are the Subprocess module, of which one Function allows us to launch second Python script from within another; and we're going to create a New ile called pygametxt py: import pygane import time import subprocess [Link] () screen = [Link].sst_mode( (800, 250)) lock = [Link]() font = [Link] Font (None, 25) [Link].set_timer (pygame .USEREVENT, 200) ef text_generator (text) + tmp =" for letter in text: tmp t= letter Af letter yield tmp clase DynanicText (abject) def _init (self, font, text, pos, autoreset Fale) [Link] = Fales [Link] = font [Link] = text self._gen = text_generator (self. text) [Link] = pos self autoreset = qutoreset self. update () def reset (se1f) self._gen = text_generator ([Link]) eel€.done = False self update () def update (self): Af not [Link]: try: self rendered = self. font. render (next (self gen), True, (0, 128, 0)) except: Stoprteration [Link] = True time .sleep(20) subprocess. Popen(*python3 /home/pi/Documents/ Python\ Code/[Link] 1", shell=True) def draw(self, scresn) [Link] (self rendered, [Link]) texte("A long tine ago, a barbarian strode from the frozen north. Sword in hand...") message = DynamicText (font, text, autoreset True) (65, 120), while True: for event in pygane event get (): if [Link] == [Link]: break if [Link] == [Link]: message. update() elee screen. £411 ([Link] (‘black*)) ‘[Link](acresn) [Link].£15p() clock. tick (60) continue break ygame quit () TERED When you run this code it wil display atong, narrow Pygame window with the intro text scrolling to the right. After a pause often seconds, itthen launches the main game Python script where you can move the warrior sprite around, Overall the effect is quite goad but there's always room For improvement. oe ED) arto Basic Animation Python's modules make it relatively easy to create shapes, or display graphics and E Talat e-eal-ua-ceceodke ine WV APNMIUAT= sora ano el Ree M ens aV RC aco de ace aa} code. There are many different ways of achieving the same end result and we'll show Wetenetecii shies LIGHTS, CAMERA, ACTION ‘The Tkinter module is an ideal starting point for learning animation within Python. Naturally, there are better custom modules ‘out there, but Tkinter does the job well enough to get a grasp on what's needed. Let's make a bouncing bal animation. First, we Insert the new code between the: ED ii ncedts este acaras (window) andine bat aM “canvas create, ova (5,5,60,60, [Link]: Alte’ zea’) line and the gut - un. You will now see the ball move From the top left corner ofthe line. Save itand from tkinter import * animation window, down to the bottom right corner. You can alter SE the speed in which the balltraversesthe window by altering the gui = Te) ime. aleep 02) line, Try (05. BETTER Seve and Run the code. You willsee a blank window appear, with a red ball siting in the upper left corner ofthe window. While tisis great, isnot very animated. Let's add the Following code: 11, a,b) lines the part that moves the bal From one corner to the other; obviously with both a and b equaling 5, We can change things around abit already, such as the size and colour of the ball, withthe line: eae. 0, £411e" xed") sige, wieth000, haight=00, bg="snste") and we can change the values of a and b to something else. ‘balla = canvas.create_oval(7,7, (60, fill='red") ase bes Ee Cine Let's see if we can animate the ballso that itbounces around the window untilyou close the program. xa ss ya = 10 while True! canvas move (ba1l1,xa,ya) pos=[Link](bal11) if pos[3] >=600 or pos{1) ya = -ya Af pos [2] >=800 or pos{o] = acreen.get_height () starti] «0 star(0] = randrange(0, 639) acreen.aet_at (star, (255, 255,255)) Basic Animation | BETEE DD Now add the Following ae sf main () + pygame. init () screen = [Link].set_node ((640,480)) [Link]. set_caption(*starfield Simulation") ses main() clock = [Link] () init_stars (screen) while True: 4 Lock the framerate at 50 FPS lock. tek (50) 4 Handle events for event in pygame-event .get (): Lf event .type == pygame-QUIT: return screen f£411((0,0,0)) ove_and_draw_stars (screen) [Link].£1ip() def wai) yanoe: st) eFoon =" pyyanesisplay. st. node (620, [Link]-cet-eaption(“Searf ela 5 PISEt*-“pypane eames chocktS snst_stars( screen) faoeke ehek(S0} wands events for event in [Link]() Prosme: rt Save and Run the code. You willagree that the simulated starfield code looks quite impressive, Imagine this asthe beginning of some game code, or even the start to-a presentation? Using a combination of Pygame and Tkinter, your Python animations will look fantastic. ED) vino Create Your Own Modules Large programs can be much easier to manage if you break them up into smaller parts and import the parts you need as modules. Learning to build your own modules also makes it easier to understand how they work. 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. Let’ start by creating a set of basic mathematics Functions. Multiply a number by two, three and ‘square or raise @ number to an exponent (power). Create a New File in the IDLE and enter: Under the above code, enter Functions to call the code: Print (timestwo(2)) Now you're going to take the Function definitions ‘outof the program and into a separate file. fighight the Function definitions and choose Eit > Cut. Choose File > New File and use Edit> Paste inthe new window. You now have two separate flles, one withthe function definitions, the other with the Function call, oe. Ses IF you nowrtry and execute the basic_math py code ‘again, the error Name€rror: name ‘timestwo' is not defined’ willbe displayed. Thisis due to the code no longer having access to the Function definitions. Fn entry ctrncth 9p, ie 9, in an fr CTR: es sti sore peer i mayo on close the minimath py window, so the basic_math.py windows, leftopen, Create Your Own Modules ¢ a ma BERD 22ckto the basic_math.py window: atthe top of the [ESTESESMM Finaly, you can now create a range of f statements code enter: to determine what to do with the number and Utlse the newly created function definitions: from minimath import * Af choice == °1) ‘This willimport the Function definitions asa module, Press FS to —— save and execute the program to see tin action. elif choice == 12": print (timesthree (num) } elif choice == 13": ‘print (square (mum2) ) elif choice = 14": puna = int (input ("Enter second number: ")) print (power (num, nun2}) else: print (“Invalid input) (eat Frm Bon Goo andows wep Be cs connrctocontovmraie Print ("Select operation. \n") print (*[Link] by two") print ("[Link] by Three") rint (*[Link]”) print ("[Link] of") choice = input (*\nEnter choice (1/2/3/4) ePSramec"tvatis ireut"> FEI vec cnssooevsrnoucseuienne ED oscars: uml = int (input (*\nEnter number: *)) ‘This will save the user-entered number asthe variable nur. 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 Bile Edt Format Bun Options Windows Help power, Save and execute the program to see it in action. Tron minimath inport * i Square") Power of") choice = input("\nEnter choice (1/2/3/4) rm? © sntcinpuecmwsenter rumbert =>) Python in Focus: Artificial Intelligence Artificial Intelligence (Al) and Machine Learning (ML) are the new hot topics of the IT industry. Al is fast becoming the working science fiction that it has been portrayed as in Serene a aeons Despite how close Al and ML are, there are distinct differences cn Ee ce ‘computer to accomplice the things that humans can do sigificantiy better and Faster. Whereas, ML isthe ability for a computer to learn From its experiences, so that the outcome and performance will, ene at cet hoon s De icra Rete eee Trey Sen Secu eco rauee cca Peer ae Tey poe Tere een ee APPLICATIONS Seen erie ee ae just afew years ago, most of us associated Al withthe rse of Pree eet ee) peter ne Liter cet) Serotec eee eee ees ‘These devices have infiltrated most of our modern world, with Pe ee cere een er 6 billion by the end of 2020, t's little surprise to discover that Al and eee ts ‘With nearly all of the population of humanity within reach of @ ‘smartphone, the coding behind these devices has been developed Ses ee ete ee ee ea eee numbers called are pushed to the top of the ls, i-app and in-game advertising is moulded around our browser and search preferences, ‘as wells other apps we've installed inthe past. And even our Rema rent eres Ea eee rea ee ae IGITAL ASSISTANTS Dee ee ee eer Cee eu een eee eee eee ns are all coded using Python, and are designed to listen, learn and respond to what we ask of them. With Python, this level oF Ali surprisingly simple, thanks to the many libraries and customisation Brier res ater ee etre ey or ecg For intelligent coders, cutting down on the development time in Cee ce aro ea) ‘complex algorithms, these developers can devote significant time to ee Caer hee Se eee ee Eee eens ne tee es . ee ort as ern et et eer eee aera ee eae mee res cet available music appsto select what tis we wanted. Allthe time, the Al code isbeing trained to listen more intent, while the ML is learning from the Alresults so thats acuracys improved For future questions and requests. Python in Focu BEYOND THE SMARTPHONE tee ee Ee as ed have you entered a search string into Google, suchas car parts For a Mkt Ford Escort and, when you've opened Facebook, you suddenly Find a group Peg a an ee ae) tesco Teen as ee heen eee eee ete suggested completions for sentences you ae typing. Fyou frequently sign Biren rea ca rein at ag the ML side ofthe equation to autofllthe remainder ofthe words For you. All the time, the ML i earning while the Als telling what to improve on. eee ae Eee ae Stik ue eae eee cn both smartphones and CCTV Footage have improved dramatically ee ecg ey Pema er er een it does pose a potential threat to our privacy. After all, who watches the ee Tesla’s work on selF-driving cars means they are getting closer to being the norm, and it's Python along with its controlling Al and ML work that's, excuse Pee mice tee at riod Sree eee i cutie’ designed to implement Aland ML In the background, youll usually Find eee aca) overall programin which the Aland Ml. are working, Pee ar ais eee ee character recognition, handwriting recognition, image processing, helping people with vista and hearing Cee aero Ca ae ce Ene eee) eee ces ability to travel. I's not all about two Al bots pete tees THE FUTURE co) AN) Re eed iller robots and self-aware See eri) pene ered mee believing that Al willbe theworst pee Oe ereuccd ee aed Suen Ce eo Pree eet Pesan eee) etd ORs Doers sateen ae ee yest eee SSE 1-18 set ee eS Rae here Pa 4H Jaa) 2 OP SS a2. crs) Seat On St ea yee ob ee ele Cee a tu Vol Tee al ee el} Cre res: s ea Nee) oe Pio ey sake Serer) aT okt RT) alaaid eae i Non ok A ] ee A) =) vee agate Ce 7 Hone ceo Repository MeN ER Sasa csc for you to freely use in your own programs. poses cane nes Ctercr) superb piece of programming, or extend your Peet Renee eer un ee ees BoC es ete cy Deuces eee Cy code, animation code, graphics code, text Peet eeu sears Pee Etre tee ak ol Pee ere eat ee Rectal the code to help you better understand what's PURER DECC aah Cole eres BU Cate tars Rta) inany other Python book. So use it, take it apart, Peed eee ers reer ec) ela aes en ene ees ee i ese This file manager program displays a list of options that allow you to read a file, write to a file, append to afile, delete a file, list the contents of a directory'and much more. It's ceo arere heroes into your own:code, or add to. ‘This part of the cade imports the necessary modules The OS and Subprocess modules deal with the erating system elements ofthe program. -XXX( Functions store the cade for each (of the menu’ options. Once the code within the ‘unction is complete, the code returns tothe main ‘menu for another option Thisis part of the code that checks to see what OS the useris running In Windows the CLS comman clears the screen, whereasin Linux and macOS, the Clear command wipes the screen. IFthe code tries to run CLS when being usedin Linux or macOS, an error occurs, which then promptsitto run the Clear commandinstead pig These are the options, from 1 to 12, Each executes the appropriate Function when the relevant number [Link] Copy the code below into a New > File and save it as [Link]. (Once executed it will display the program title, along with the current time and date and the available options. [import shut import tine | Amport subprocess det Road: Dithcinpot (Eater the Ble path to reads") ‘e-epea(path,"e") = print le-read0) 2 | Snpat('Prees Enter.) q ‘[Link] dot weited: ‘patheinput (‘Enter the path of file to write or create:") Af os:[Link](path): Print(‘Rebuilding the existing file’) Print(‘Creating the new file’) eoxtminput (Enter text:") ‘Ble-open(path,"¥") ‘le write(text) det ada ‘patheinput (‘Enter the file path") toxtminput("Enter the text to add”) ‘le-opantpath,"a") Blewrite( \n'stext) det Dateted ‘patheinput ‘Enter the path of file for di Lf os:[Link](path): Eine(‘Psle Found’) os renove(path) rint(‘File has been deleted’) else: ‘print(‘File Doss not exist’) seion:") det Dirlist0: ‘Patheinput (‘Enter the Directory path to display:”) sortlistesorted([Link](path)) so wasie(icien(sortaiet) print(eortlist{s]e"\n) aot chock) ‘paint input( ‘Check existence of \[Link] \n2, Dizectory\n’)) AE Speed: patheinput("Enter the fle path:") os:[Link](path) (_ Python File Manager S£ [Link](path) true: S.1ist files in a directory print(Pile Found’) [Link] fle existence Print ‘File not found’) [Link] a Me sf spa: [Link] a directory patheinput("Enter the directory path:") [Link] a directory [Link](path) 21.0pen a program Af os [Link](path)=-raiee: aE print(‘Directory Found’) else: po PEint(‘Directory Not Found’) | decent: Resa) dee move) © 4 docan pathisinput(‘Enter the source path of file to move:’) «rite smr=int input ([Link] \[Link] \n’) Lf doomed: Sf mt: aaa PAtQUnput( ‘Enter the destination path and fle name:’) if doom [Link](pathi path2) | beret] rint(‘File renanod’) | Ae dooms sf mr=e2: birtisto [path2-input('Enter the path to move:') | Af dee: [Link] (patht,path2) chock’) pEint(File moved’) © if doom Move aot copy0 © Af dooms: pathisinput(Enter the path of the fle to copy or rename’) Copy() pathZminput (‘Eater the path to copy to:") | doce: [Link] (path path2) ae) Eint(File copied’) © 4 deca: Renovedir) dee Maxedix(: | A dem: ppath=imput("Enter the dixectory name with path to make Openfile() \neg. CA\etio\\Wewdis \ntthere Nevdix is new © if docmen2: directory:") exit ‘[Link](path) | runednt(input (Return to mens\[Link] \n") print(‘Directory Created’) (Ae rune exit) doe Renovedix() ppatheinput(‘Enter the path of Directory:’) ‘troodirsint (input('1 Deleted Directory \n?.Delete Dizectory ree \[Link] \n')) ‘[Link] (path) Sf troediren2 shutil mtroe(path) print(‘Directory Deleted’) exit de¢ opensied Datirinput( ter the path of program’) ey on startmetpatn) i except : PEint(‘File not found’) : eT Imports : 1 a ‘There are three modules to import here: Shutil, OS and : "7 Time. The isttwo deal wth te operating system and fle eee management and manipulation and the ime module simply eee <éspays the currenttime and date peine(\possoooeython 3 File Magerccccececce\) Ee a eae asl einem Note how we've included a try and except blocktocheckiF ete (taosoa] opciones the users running the cde on aLinuxsystem or Windows eonintisnpst "1 Read a Ble Windows ues CLSto dear the screen, while Linux uses clear aite to a Sle ‘The tr block should work well enough butits@poin of [Link] text to a file possible improvement depending on your own system, ‘velete a file ee Claas yor Eye ee eel This is.a simple little piece of code but it makes good use of the Random module, print and input, anda While loop. The number of guesses'can be increased From 5 peel aeteat aint ear etn easily be altered too. OED ened a C 4 [Link] Copy the code and see if you can beat the computer within Five guesses. It’s an interesting bit of code that can be quite handy when your implementing a combination of the Random module alongside a while loop. | Amport andor | guessostsed = Tio! What is your name? °) ] number = [Link](, 30) | Print(Grectings, ' + Name + *, 1m thinking of a | | | number between 1 and 30.’) Af guese < nunber: PEint(‘Too low, try again.’) Af guoss > number: PEint("Too high, try again’) Print(Well done, "+ Nane +‘! You guessed ] str (guessessed) | correctly in * + guessesUsed + * guesses.’) | t | Print('Sorry, out of guesses. The number I was] | thinking of 42 * + nanber) I Although thisisa reasonably easy to follow program, there are lementsto the code that are worth pointing out To begin h, you need to impart the Random module, as you're using random numbers within the code, Jy This section ofthe code creates the variables For the numbes of guesses used, along with the name ofthe player, and also setsup the random number between 1 nd 30. IF wider range of random number selection, then i ‘numbersrandomrandint(1, 30) end value of 3; high though othe player will never be able to quest. player guesses too low or too high, they are given the appropriate output and asked totry agai, while the numbe ‘oF quessesis es than five, You canals increase the number of ‘uesses from 5 by ltering the while quessesUsed < 5: value, player quessedthe correct numberthen theyare given ‘well done’ output, along with haw many guesses they used up, IF the player runs aut oF guesses, then the game over outputs clsplayed instead, along with revealing the number the computer was thinking of. Remember, f you do alter the values of the random number chosen by the computer, or the number o he player can take, then along withthe variable values, need to amend the intructions given in the print staternents atthe start ofthe code, ‘Code Improvements. Since this is such a simple sri to apply to astuation, there's plenty of roam to mess around with itand makeit more interesting, Pethaps you can include an option to take score, the best out of three rounds. Maybe an elaborate way to congratulate the player For getting a ‘hole in one’ correct quess on thei Fist tr. } Moreover, the number guessing game code does offer some room forimplementing into your code ina different manner. What we mean by thsi, the code can be used to retrieve random number between a range, which in turn can giveyou the start of character creation defined Function within an adventure game, Imagine the start of a text adventure written in Python, where the player names their character. The next step isto rll the virtual random dice to decide what that character's combat rating, strength, endurance and luck values are. These can then be ‘awied forward nto the game under ast of variables that can be reduced or increased depending on the circumstances the player's, character ends up. Number Guessing Game For example, as per the screenshot provided, you could use ‘something along the lines of: Endurance=0| cro nek=0 Endurance = [Link](t, 15) (oR » [Link](t, 20) sek = random-randine(1, 20) Print("Your character's stats are as follove:\n") Print("Endurance:”, Endurance) Print(*Combat Rating:", CR) Print("buck:", luck) ‘The player can then decide to eltherstickwith their rollor try again forthe hope of better values being picked. There's ample ways in wiih to implement this code into a basic adventure game. aaa eer Epa ee el User input and the ability to manipulate that input are important. urea Neer Te) language. It's what'separates a good program from a great program, one that'allows the user oder lee eo a el kel ir a sl>s5>950>Random Number Generator: (ea Pees MME CR MEMCME user's entered text string into its binary equivalent. Fyou eg Paka cad@, g os i areas accuracy, you can plug the binary into an ett ro ena NOE toxtsinput( "Enter text to convert to Binary: “) ote eee Pedal) ae ee tae ole Eile Edit Format Run Options Windows Help print(">>>>>>>>>>Text to Binary Conver tor <ooappopoMext to Binary Convertorcccceeecce\n") ‘conversion=input "Enter text to convert to Binary: *) siz0 = (600, 400) screen = [Link] _mode(size) a a, Text to Binary Convertor [Link] _caption("Binary Conversion”) done = False clock = [Link]() text _rotate degrees = 0 Binary=(° ‘join(format(ord(x), 4in conversion)) BY) for x ite not done: for event in [Link](): Lf [Link] == pygame.0UIT: ene = True ‘screen.f11 00275) font = [Link]{Calibri’, 25, True, False) text = [Link](Binary, True, BLACK) text = [Link](text, text _ rotate degrees) text _Fotate_dagress 4= 1 [Link], [100, 50)) [Link].f3p() [Link](60) [Link] Eint(’ ‘oin(formatford(e), "b’) for x aa Caer Eye Dee eel Basic GUI File Browser Pe eeeeowar ll aULE-Tp oR a ecln sre late) piece of code, It’s an extremely basic. File browser that's presented ina foley Ones OUR LeU e fancy Bi sle lm uatore( ore] Col Aol Ke 1} TT elm eeaeecore E-Ten ale cua into your own'programs. er Eera eal eta - a FF io ol Ps] a a 0 e celal [Link] Tkinter is the main module in use here but we're also using idlelib, so you may need to pip install any extras if the dependencies Fail when you execute the code. from thinter import Tk from [Link] import Scrolledcanvas, FiletrecIten, TrecNode oot = Tk) [Link]("File Browser”) 2c = Scrolledcanvas(root, by="white", hhighlightthickness=0, takefocus=1) [Link](expand=1, fill="both’, aide="lett”) itom = FileTrecrtem(os.getowd0) node = Treetiode([Link], None, item) [Link]() [Link]() Advanced Filing When executed, the code wil dsplay the current drectory’s contents. you want to see the contents of another directory, you canrun the code from a command line within the chosen directory, just remember to call the cade from where it's located on your system, as per the second screenshot. You can also double-lick any ofthe file names shown in the directory tree and rename them. ‘Thisisan interesting piece of code and one that you can insertinto ‘your own programs. You can extend the code to include a user specified directory to browse, perhaps your own unique file cons, too. IF you're using Linux create an alias to execute the code and then you can runit-from wherever you are in the system. Windows users may have some trouble with the above code, an alternative can be achieved by using the following from tkinter import * from tkinter import ttk from [Link] import askopenfilenane root = Tk) ot openPiie() ‘ane = askopenfilenane(initialdie="c:/", ‘Slatypes =((*Text File", "*.txt"), CALL Files"), title = “choose a se.” (_ Basic GUI File Browser try: ‘with open(name,'r’) as UseFile: Print ([Link]()) ‘except: ‘PEIne(No files opened”) Title = [Link]( "File opener”) label = ttk-label{rost, text ="File open” foreground="zed",font=("Helvetica", 16)) abel. pack) ‘menu = Mena(zoot) ‘oot config(sensenens) ‘Sle = Mens mens) ‘[Link] _command(iabel = ‘open’, command = OpenFiie) ‘le add command(label = ‘Exit’, command = Lambda: Sei) mmonu.add__cascade(label = ‘File’, menu = fle) oot mainloop() It’s not quite the same but this code allowsyou to open files in your system via the familar Windows Explorer. It's worth ‘experimenting with to see what you can do witht. oa Ey oP Dean eae 4 . 5 Fo a ol ra] a a 0 Cla} Cera eee EDS Ite heme ree aT) Mouse Controlled Turtle YCAV Bs) ecr-leh Veta ea MU ua cd module being controlled by the user via'the keyboard butnow we thought we'd’see how the user can Pelee eee ci hort Mae Wee tsoeece a eee oa e ae works, bestfor you, ov [Link] The first piece of code presents the standard Turtle window. Press Space and then click anywhere on the screen for the Turtle to draw to the mouse pointer. The second allows you to click the Turtle and drag it around the screen; but be warned, it can crash Python. 1st Code Example: from turtle import Screen, Turtle dee 12010) ‘[Link](elick handler) def click _handlerix, y): [Link](None) # disable event inside event handler [Link](x, y)) [Link], y) ‘[Link](click handler) # reenable [Link](ki0t, “ *) # space turns on mouse drawing [Link]() [Link]() 2nd Code Example: from turtle import * shape("eizele”) pencolor("biue”) width) ‘ondrag(gots) Listend) Ninja TurtleMouse ‘This code utilises some intresting sis Obvious wl stretch your Python Turtle skis to come up with any improvements, wich great, butt could make Fo ance piece of code to insert into something ayoung cid wil use. Therefore tcan be fantastic projet for a younger person to get thet teeth no ‘orperhaps even a part ofa game where the man characteris tasked to draw a sll nd crossbones oF something similar ( Mouse Controlled Turtle/ Python Alarm Clock Python Alarm Clock Ever taken a quick break from working at the computer, then suddenly realised many minutes later that you've spent all that time on Facebook? Introducing the Python alarm clock code, where you can, drop into the command prompt and tell the code how many minutes until the alarm goes off. [Link] This code is designed for use in the command prompt, be that Windows, Linux or macOS. There are some instructions on how tose it in the main print section but essentially it’s: python3 [Link] 10 (to go off in ten minutes) import sys import string from time import sleep sa = [Link] Asa = [Link]) Af dea t= 2: print (‘Usage: [ python3 ] AlaraClock py duration _ in _minutes”) print (Example: [ python3 ] [Link] 10") print ("Use a value of 0 minutes for testing the ‘alarm innediately.”) Print ("Beeps a few tines after the duration is over.”) Print (‘Press Ctrl-C to terminate the alarm lock early.”) [Link]() try: ‘minutes = int(sa{t)) fexcopt Valuorror: print ("Znvalid numeric value (ts) for minutes” * sa(1}) print ("should be an integer >= 0”) [Link]() Af minutes < 0: print (“Invalid value for minutes, should be >= 0") [Link]() seconds = minutes * 60 Af minutes = 1: unit _word = * minute” else: ‘unit _word = " minutes” minutes > 0: Print ("Sleeping for "+ str(minutes) + unit _word) sleop(seconds) print (Wake up") for 4 in range(S): eint (ehz(), slecp(1) ‘except Keyboardinterrupt: print ("Interrupted by user”) [Link]@) Wakey Wakey ‘There's some good use of try and except blocks here, alongside some other usefulloops that can help you geta firmer Understanding of how they work in Python. The code itself ‘canbe used in variety of ways:in a game where something happensaftera set amount oftime or simply asa handy desktop alarm clock for your tea break Linux user, try making the alarm clock code into an alias, so youcan una simple command to execute it. Then, why not integrate a user input at the beginning to ask the user for the length of time they want untithe alarm goes off, rather than having to include itn the command tne. ‘Windows users iF Python 3s the only version installed on your system then you will need to execute the code without adding the 3to the end ofthe Python command. For example: python Alarmclock py 10 ‘Again, you could easily incorporate thisinto a Windows batch file and even seta schedule to activate the alarm at certain times ofthe day. What's not to like about vertically [Link] scrolling text? Its uses are many: the We've used the poem Cimmeria by Robert E. Howard for the Lorelle Ree Rs cu Mom alacetelU(aale lay code’s scrolling text, along with a dramatic black background eben tance care ainiat and red text. We think you'll agree, it's quite epic. Ie ir laa forelley- lage ebol me olnTagare ree eS Me ia s-Leo aCe a from [Link] import * poinieg text _list =» I remember ‘The dark woods, masking slopes of sombre hills; ‘The dusky streams that flowed without a sound, And the lone winds that whispered down the passes, Slope beyond slope, each dark with sullen trees, Our gaunt land lay. So when a man climbed up A rugged peak and gazed, his shaded eye Saw but the endless vista - hill on hill, Slope beyond slope, each hooded like its brothers. ee Ca aT) dae nee Tt was a gloomy land that seemed to hold ALL winds and clouds and dreams that shun the sun, With bare boughe rattling in the lonesome winds, And the dark woodlands brooding over all, Not even lightened by the rare dim sun Which made squat shadows out of men; they called it Cimneria, land of Darkness and deep Night. | i i] y a ny + q g i Dy Ht was so long ago and far away T have forgot the very nano men called mo, The axe and fiint-tipped spear are Like a dream, only the stillness of that sombre land; ‘The clouds that piled forever on the hills, ‘The dinnoss of the everlasting woods. Cimmeria, land of Darkness and the Night. Pee] een oe Oh, soul of mine, born out of shadowed hills, ‘To clouds and winds and ghosts that shun the sun, How many deaths shall serve to break at last This heritage which weape me in the grey Apparel of ghosta? I search my heart and find Cimmeria, land of Darkness and the Night! 2e DOM eet Peroni yon lt eee By) tomet tT aNT AY cer SO OVAL AS DT era ee etsy vrgplit(\n’) Oyeh ere ed er 3 class Credits: def _ init__(self, screen _rect, 1st) [Link] = screen rect selelat = lat [Link] = 16 [Link] = (255,0,0) self butt _contery = [Link]/2 + 5 self bute ~ lines = 50 [Link] [Link] [Link] _ surfac dof make _text(sel£ message): font = [Link] ("Arial 5 text textget _rect(center = (self srect. centers, [Link] + self buff _centery) ) dof make _ surfaces(selt) [Link] = (1 for i, Line in enunerate(sel£.1st) 15 [Link] _text(Line) Ally + i*self.butf_ lines [Link](1) def update(selt) Lf [Link] _ticks()-[Link] > [Link]: [Link] = [Link] _ ticks() for text, rect in [Link]: def render(eelf, suxf): for text, rect in sel¥.text: [Link](text, rect) screen = [Link] _ mode((800,600)) screen rect = [Link] _rect() clock = [Link]() ranning=true cred = Credita(screen rect, text _ list) while running: for event in [Link]() Af [Link] == QUIT: running = False screen.fi11((0,0,0)) [Link]() [Link](ecreen) [Link]() Clock. tick 60) (_ Vertically Scrolling Text e ALLong Time Ago. ‘The obvious main point of enhancementis the actual text itself Replace itwitha st of credits, or an equally epic opening storyline to your Python game, and ie will certainly hitthe mark with whoever plays, Dont Forget to change the screen resolution if needed; we're currently running iat 800 x 600. BS . ia a im Ey oO ia ol 0 g pear) ae] Cole eae! [4 pio yl As BUN -E ells N eRe ole eel sole) on the desktop of most operating systems but it’s always handy to have one on top of the currently open MNO trel seus Ma atelterst1 a Python digitalclock thatcan be a companion, desktop widget Foryou. era es a Python Digital Clock [Link] This isa surprisingly handy litle script and one that we've used in the past instead of relying on a watch or even the clock in the system tray of the operating system. import tkinter as tk dof tick(timel="): 4 get the current time from the PC timed = [Link]( MH-AM:4S") Ae time? '= timel: ‘timel = time? clock. configitext=time2) [Link](200, tick) oot = tk-TkO) clock = tk-label(rost, font=(arial’, 20, ‘bold’), bg="gre0n') clock pack{S11="both’, expand=1) tick) root mainloop() Tick Tock Thisisa piece of code we've used many times inthe past to keep track time while working on multiple monitors and with ust 8 uick glance to where we've placed ton the screen, ‘The Tkinter box can be moved around without affecting the time, ‘maximised or closed by the user at wll We haven't given the “Tinter clock window a ttle, so you can add to that easily enough by snipping the cade From other examples n this Book. ‘Another area of improvementis to include this code when Windows or Linuxstarts, so it automatically pops up on the desktop, See als, if you're able to improve its Functionality by including differentime zones: Rome, Paris, Landon, New York, Moscow and soon, Another example, expanding on the original code, could bea digital stopwatch. For that you could usethe following snport tkinter Amport time ‘class stopWatch(tkinter. Frame): Gctasenethod ef nain(cls): ‘[Link]() oot = tkinter.M() [Link]('Stop Watch’) [Link](true, False) [Link] _columnconfiguro(0, weight=1) [padding = dict(pade=5, pady-5) widget = stopmatch(root, *padding) widget grid(eticky=[Link], padding) oot mainloop() ef __ init__(self, master=tone, onf=(), *#k): ‘padding = dict(padx=[Link](‘padx’, 5), pady=kw. pep(‘pady’, 5)) super()._\_init__ (master, enf, **ky) self.grid_columnconfiguro(t, weight=1) Self.grid_rovconfigure(i, weight=t) self. _total = 0 self. _ label = [Link](seif, texta"actal time") self, __tine = [Link](self, +01060000") self. _display = [Link](sol¢, textvariable-seif,_ _ tine) self. _ button = [Link](aelé, texte'StGrt’, command=selé. click) self. __label.grid(row=0, columne0, stickyatkinter 2, **padding) self. __display.grid(row=0, column=1, sticky-tkinter 2x, padding) self. _button.geid{zow=1, column=0, Ccolumnapane2,sticky=[Link], *4padding) click(se1) “_buttonf‘text’] == ‘start: __Tbatton(‘text'] = ‘step’ Tatart = time.clock0 self, _ loounter = [Link] idle(sslf. __ypdate) else: self. __button{‘text’] = ‘start’ self.aéter _cancel(selt. Of. course, instead of playing an existing MP3, you can always make So OAM eee EN Reels ol will play out Pachelbel’s Canonin D, ee a Ci [Link] The code utilises both the Time and Winsound modules, defining the tone and pitch and inserting small pauses of 5 of a second. | import winsound | import tine BOES BERBERS SE>Eog™eBopO Bg EpEESpRRBReRE Playing Music with the Winsound Module @ ‘Sweet Music ‘Obviously the Winsound module isa Windows-only set oF Functions for Python, Open your IDLE in Windows and copy the code in, Press F5to save and execute, then press the Enterkey, asinstructed in the code, to stat the music. for 4 in range (5): [Link]( 16, 2*t) [Link]( hc, *) [Link]( hE, t) [Link]( hs, t) aaa a ‘Naturally you can swap out the [Link] frequency and ") print(nane, “the barbarian, sword in hand and looking [Link]() print(*A pair of bulbous eyes regards the hero...”) tine sleep (2) print(‘Will", name, “prevail, and win great fortune. tine,sleep() print(*Or die by the hands of great evil...") tine sleep() print(*\a" #3) print(‘Only time will tell...") tine,sleep() print(’. print’) [Link]() print(’.) [Link](®) print(*\n” #200) print(”” You Sind yourself at a small inn. There's Little gold in your purse but your sword is sharp, and you're ready for adventure, With you are three other customers. A ragged looking man, and a pair of dangerous ooking guards.””) de start) print(\n -— PEint(‘Do you approach the...”) peint(*\n") PEint('L. Ragged looking man”) Eint("2. Dangerous looking guards") =a endlist=1", °2"1 cend=getond(endl ist) Af end == Vs zagged() elif ond guards() ver def xagged(): rint("\n" * 200) print(\”'You walk up to the xagged looking man and greet hin. He smiles a toothless grin and, with a strange ‘accent, says. “Buy me a cup of wine, and I/11 tell you of great treasure..."") [Link]@2) def guards(): print(*\n" #200) Print(\”'You walk up to the dangerous looking guards and greet then. ‘The guards look up from their drinks and snarl at you. what do you want, barbarian?” One guard reaches for the hilt of his sword..."") ‘[Link](2) Text Adventure Script \ def getomd(endlist): cond = input name>") Af ond in ondlist: = elif ond Tir (nes co goueTeunioon ine Taeentvoaraa ‘the gane.”) Print("or enter ‘quit’ to leave the game”) return getcnd(cndlist) elif ond == “quit”: print("\n—~ ‘[Link]() print("Sadly you return to your homeland without = Adventure Time “This, as you can see is just the beginning of the adventure and takes up a fair Few lines of code, When you expand it, and weave the story along, you'l find that you can repeat certain instances: suchas a chance meeting with an enemy or the ike (We've created each ofthe two encounters asa defined set (of Functions, along with list of possible choices under the cdl list, and cid variable, of which also a defined function Expanding on this i quite easy, just map out each encounter and choice and create a defined Function around it. Providing the user doesn't enter quit into the adventure, they can keep playing. ‘There's also room in the adventure Fora set oF variables designed For combat, luck, healt, endurance and even an inventory or ‘amount of gold eared. Each successful combat situation can reduce the main character's health but increase their combat skills ‘or endurance. Plus, they could loot the body and gain gold, or earn ‘gold through quests. Finally, how about introducing the Random module. This will tenable you to include an element of chance in the game. For ‘example, in combat, when you strike an enemy you will doa random amount of damage as wil they. You could even work out the maths behind improving the chance ofa better hit based on| ‘your or your opponent's combat ski, current health, strength and endurance. You could create a game of dice inthe inn, tosee if you ‘win or lose gold (again, improve the chances of winning by working ‘out your luck factor nto the equation). Needless to say, your text adventure can graw exponentially and prove tobe a work of wonder. Goad luck, andhave fun with your adventure. oe 9

You might also like