0% found this document useful (0 votes)
61 views92 pages

Raspberry Pi T&T8 TH 21

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)
61 views92 pages

Raspberry Pi T&T8 TH 21

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
You are on page 1/ 92
LL ae Your Codel Raspberry Pi Tricks and Tips oa isa a i 2 3 coy (- Vass TOTTI \ aN ue Are you a Windows PC user? Then don’t miss our latest essential Windows 11 user guide on Readly now! The Essentials Your essential guide to Microsoft's new Windows 11 operating system oo LX) ec at | | | = Discover new uses ‘and functionality with | an step-by-step guides | Windows 11 update Essential tutorials | All your questions @ insider tips for the | about Windows 11 are answered inside Raspberry Pi i ial a 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 naa out journe, ees &y Continues, understanding of aie we will be with you technology and gain the “ey Stage to advice skills to take you from a inform and ultimatol,” confident user to an inspire you to experienced expert. 90 further. Contents 6 Python Code & Ideas Pane nee 16 10 Number Guessing Game iT Pam eiticicr Ft rmsd 22 Mastering Linux eee 46 POM rasa ec Prete an eta balcd od 30 Creating and Deleting Files 50 Ermer Wea Deierlu cet File and save tas FileMan.py. Once executed it will display the program title, along with the current time and date and the available options. import shutil import os Amport tine import subprocess et Resd() ‘patheinput(Enter the file path to read:”) ‘le=open(path,"r") printiile reed()) Anput('Press Enter. le.close() det write) ‘path=input(Enter the path of file to write or create:") Af of. path issile(path): print(‘Rebutlding the existing Ale’) ote rint((Creating the new fle’) textainput("Enter text:") ‘leropen(path,"w") Sle.writa(text) det ada ‘path=input Enter the Sle path:") texteinput("Enter the text to adds") ‘leropen(path,"2") ‘Sle writa(‘\n'stext) det delete) ppath=input("Enter the path of file for deletion:”) Lf os path existe(path) rint(‘File Found’) os.renove(path) pEint(‘File has been deleted’) ete: ‘Print(‘File Does not exist’) det Dirlist) ‘path=input( Enter the Directory path to display:”) sortlistascrted(es.1istdir(path)) while (Sclen(sortiiet) ‘peint(eort]ist[s}+/\e") Sel det check: ‘print{input{'Check existence of \nl.File \n2 Directory\n’)) Le pests ppath=input("Enter the file path:") Of. path. Sefile(path) Af os.path defile (path)==True: rint((File Found’) eint(‘File not found’) Af p= patheinput("Eater the directory path:”) os.path-isdiz(path) Sf of. path, Sedir(path)=Fal print(‘Directory Found’) euse: Peint(‘Directory Not Found’) det Hove): ‘pathisinput(‘Enter the source path of file to nove: ‘ar=int (input("I Rename \n2.Move \n) Af meet: ‘ath2einput(Enter the destination path and fle name’) shutil.move pathl,path2) peint('File renamed’) sf m=?) [path2=input( ‘Enter the path to move:’) shutil.move pathi,path2}) Print('File moved’) det copy(): pathlsinput( ‘Enter the path of the file to copy or renames") path2=input(‘Enter the path to copy to:") sthutil.copy (path path2) rint('File copied’) det Makedix(): path=input("Enter the directory name with path to make \neg. C:\\seiio\\owdir \nihere Nowdix is new directory") os makedixe(path) rint((Directory Created’) et Renovedix() path=input(‘Enter the path of Directory:") tereedireint(input('L Deleted Directory \n2.Delete Directory Tree \n3.Exit \n’) Sf troedir==i os.zndir(path) Af treedir==2 hati mtree(path) peint(‘Dizectory Deleted’) Af treedixe=t: exit) def opentile(): [path=input( ‘Enter the path of progran: ey: os.startéle(path) ‘except: ‘peine('FLle not found’) re ‘tietuom = = onyetent cle) = a Seeysten(cle? print yoomoooonytion 3 de Manager) ise(tm clout lian and ata arise sina Set ecee ete Enerin inact" htae «Re aueite wo ale Sepend tent fo 0 le ‘Dela « fe Python File Manager S.List files in a directory G.check fle existence Move a file 8.copy a file S.czeate 2 dizectory iO.Delete a directory 3L.0pen a program Preset vm Af dec=: Readi) Af decom weite() Af dace dao Af dec=nt: af Dirlist) Af decené: Check’) Move() Af decom copy) Af decm=d: Makedix() Af dec=0: Renovedir() Af dec==il Opensite() Af dece=i2 exit) unsint(input("L Return 0 menu\n2.Exit \a")) Af rune exit) Imports There are three modules to import here: Shull, OS and Time. The First two deal wth the operating system and file management and manipulation; and the Time module simply displays the current time and date. Note how we've included a try and except block to check iF the users running the code ona Linux system or Windows. Windows uses CLS to clear the screen, while Linux uses clear. The try black should work well enough butt'sa point of possible improvement depending on your own system. wnebdmpubleatonscom — 81 el Ee eee ees i Number Guessing Game SSR teet ec but it makes good use of the Random Date aa ae While loop. The number of guess can be increased from 5 and the random number fange can easily be etched NUMBERGUESS.PY Copy the code and see if you can beat the computer within Five ‘guesses. I's an interesting bit of code that can be quite handy when your implementing a combination of the Random module alongside a while loop. import random guesseatsed = 0 Nane=input(‘Hello! What is your nane? *) number = random.zandint(1, 30) print((Greetings, ‘+ Name +‘, 1m thinking of a number between 1 and 30.’) while guessestsed < 5: ‘quess=int{input(‘Guess the munber within 5 guesses...)) quessesUsed = guessesUsed + 1 Sf guess < number: rint(‘Too low, try again’) Af guess > number: eint ("Too high, tey again.”) Af guess == number: break Print('Well done, "+ Name + ‘! You guessed correctly in * + guessestsed + * quesses.’) Af guess != number: ‘number = str(nunber) Print((Sorry, out of guesses. The number I wi thinking of is + number) ‘Although thisisa reasonably easy to follow program, there are ‘some elements to the code that are worth pointing out. To begin with, you need to import the Random module, as you're using random numbers within the code. ‘Thissection of the code creates the variables forthe number ‘of guesses used, along withthe name ofthe player, and also sets up the random number between 1 and 30. Fyouwant a wider range of random number selection then increase the rnumber=random.randint(1, 30) end value of 30; don't make ittoo high though or the player wil never be able to quessit If the player uesses too low or too high they are given the ‘appropriate output and asked to try again, while the number ‘of guessesis less than ive, You can also increase the number oF ‘guesses from 5 by altering the while quessesUsed <5: value, IF the player uessed the correct number then they are given a ‘well done’ output, along with how many quesses they used up. iF te player runs out of guesses, then the game over output is >>;p>9>>>Awesome Adventureccccccccc<\n") print("\n" * 3) time. sleep(3) print(*\aA long time ago, a warrior strode forth from the frozen north.") ‘tine. sleep() print(‘Does this warrior have a nane?”) ame=input (">") print(nane, “the barbarian, sword in hand and looking for adventure!") ‘tine. sleep() print(*Hovaver, evil ie lurking neazby....") z= print(Will”, name, “prevail, and win great fortune...") time. sleep(1) print(‘Or die by the hands of great evil...2") ‘time.aleep(]) print("\a" #3) print(‘Omly time will tell...”) ‘ime. aleep(2) print’. teime.alé print{( print("\a" #200) print(” You find yourself at a small inn. There's Little gold in your purse but your sword is sharp, land you're ready for adventure, With you are three other customers, A ragged looking man, and a pair of dangerous looking guards.'") det start() peint(*\n — ppEint(‘Do you approach the...”) print (“\n") rint(‘1. Ragged looking man”) rint(‘2, Dangerous looking guards”) endlist=['2", "2" ‘endsgetond(cndlist) Adventure Time This, as you can see, isjust the beginning ofthe adventure and takes up a fair ew lines of code. When you expandit, and weave the story along, youll Find that you can repeat certain instances suchas a chance meeting with an enemy or the ike. We've created each of the two encounters as a defined set of Functions, along with alist of possible choices under the cmalist ist, and cma variable, of which isalso a defined Function. Expanding on thisis quite easy, just map out each encounter and choice and create a defined function around it. Providing the user doesr't enter quit into the adventure, they can keep playing. There's also room in the adventure Fora set of variables designed For combat, luc, health, endurance and even an inventory or amount of gold earned. Each successful combat situation can Feduce the main character's health but increase their combat skills or endurance. Pus, they could loot the body and gain gold, crear gold through quests. Finally, how about introducing the Random module. This will tenable you to include an element of chance inthe game. For cexampie, in combat, when you strike an enemy you will do.a random amount of damage as willthey. You could even work out the maths behind improving the chance ofa better hitbased on your or your opponent's combet sls, current health strength and endurance. You could create a game of dice in the inn, tose iF you win or lose gold (again, improve the chances of winning by working out your luck actor into the equation) Needless to say, your text adventure can grow exponentially and prove to be a work of wonder. Good luck, and have Fun with your adventure, | Text Adventure Script det gotcnd{endlist): fend = input{nanet’>”) Af ond in ondlist: return ond ‘elif ond = “help”: [PEint("\aEnter your choices as detailed in ‘the gane.”) print(Yor enter ‘quit’ to leave the game") return gatond(cndlist) (elif end = “quit”: peint ("\n—= ‘time. sleep(2) Print(Sadly you return to your homeland without, fame or fortune...") 7 ‘time.sleep(5) exit) if __name__=" sareo wubdmpubcavonscom 85 Een Code and res i Python Digital Clock A oer Cee Ne oe as secon Riera nO messes CRC) butit’s always handy to have one‘on top Caren a UALS at er Ngee cy uence Cement Seoul areata Mesos atl DIGCLOCK.PY This is a surprisingly handy litle script and one that we've used in the past instead of relying on a watch or even the clockin the system tray ofthe operating system. import time import tkinter as tk def tick(timel=") # get the current time from the FC tine? = tine. stretime HH: R1S') Sf time? '= timel: timel = tine? clock.contfig(text=time2) clock.after(200, tick) root = tk.tk() clock = tk.Label(root, font=('ariaY’, 20, ‘belé’), 2bg='green’) clock pack{Gll="both’, expands) tick) root.aintoop() Tick Tock Thisis apiece of code we've used mary times inthe past to keep track of time while working on multiple monitors and with usta uick glance to where we've placed iton the screen The Tkinter box can be moved around without affecting the time, maximised or closed by the user at will We havertt given the Tkinter clock window title, so you can add to that easy ‘enough by snipping the code from other examples in this book Another area of mprovementis to include this code when Windows or Linux starts, soit automatically pops up on the desktop. See aso, f you're able to improve its Functionality by including different time zones: Rome, Paris, Landon, New York, Moscow and soon. Another example, expanding on the original code, could bea digital stopwatch. For that you could use the Following Amport teinter Amport tine class Stoptiatch tkinter. Frame) ectassmethod ‘def main(cle) ‘kinter.NeDefaultRoot() root = tkinter.7k() | Python Digital Clock zoot-titie('Stop atch’) root.resizable(trve, False) root.grid__coluanconfigure(0, weight=I) padding = diet(padees, pady=s) widget = Stopatch (root, *¥padding) widget grid(eticky=tkinter.NSOY, “¥padding) root-maintoop() det __ init__(self, mastersone, onf=(), *#ky) padding = dict(padetorpop((pedk’, 5), pady=bw, pop’pady’, 5) super().__init __ master, nf, *kx) selé.grid_colunnccnsgure(1, weight=l) self.grid_ roweontigure(t, weight=1) self. _total = 0 abel = thinter Label(eete, ____ tine = tkinter Stringvar(eelé, 8.680000" self. _ _display = tkinter-tabel (self, det __click(eeis) Af eal. _ _buttont‘text’) == ‘start’: sole, _ _batton{‘text’] = ‘stop’ sele, _ _start = tine.clock) self. _ leounter = selé.atter _dle(self. else: self. _ _button{‘text’] = ‘start’ self-after_cancel(self._ _counter) —vpdate) dof _ _vupdate(eaie) now = time.clock() ie = now ~ self. ele. _ total += ditt self, _ _ tine.cot('(:.6)format(eoif. __total)) tele, _ eounter = selé.atter _idleleelé._ _ update) sare wu bdrmpublcatons com 87 & Een rene Vertically Scrolling Text ‘What's not to like about vertically scrolling text?.Its uses are many: the em pacte mcrae ata) Something épic, like the beginning of CNA eT eae oe Mecit accuse er io ac Peroni cle Ra eke EPICSCROLL.PY (We've used the poem Cimmeria by Robert E. Howard For the code's scrolling text, along with a dramatic black background and red text. We think you'll agree, i's quite epic. Amport pygane as pg from pygame.locals import * pg.tnseo text _list = 1 remember The dark woods, masking slopes of sonbre hills; ‘grey clouds’ leaden everlasting arch: e dusky streams that flowed without a sound, [And the lone winds that whispered down the passes. Vista on vista marching, hills on hills, 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, Tt was a gloomy land that seemed to hold [ALL winds and clouds and dreams that shun the sun, With bare boughs 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 st Cinmeria, land of Darkness and deep Night. Te was so long ago and far away T have forgot the very nane men called ne. The axe and fint-tipped spear are like a drean, And hunts and wars aze shadows, I recall Only the stillness of that sombre land; The clouds that piled forever on the hills, ‘he dinness of the everlasting woods. Cimmeria, land of Darkness and the Right, (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 wraps me in the grey Apparel of ghosts? T search my heart and Sind Cimmeria, land of Darkness and the Hight! vr gphst cn’) clase Credits: def __ init__(self, screen _rect, 1st): self erect = ecreen _ rect pele let = Let jelf.eize = 16 self.color = (255,0,0) ‘self butf_centery = self.srect.height/2 + 5 elf buff _ lines = 50 self-tiner = 0.0 self-delay = 0 jelf. make _ surfaces() def make _text(self message): font: = pg.font.SysFont("Arial’, self.size) ‘text = font.render(nessage,True,sel£.coloz) rect = text.get _ rect (center = (self.srect. conterx, self.srect.centery + self.butf _centery) ) return text rect for i, Line in enunerate(self.1st): 1 = self.make_ text(Line) py += iselE butt Lines E.text.append(l) def update(sels): Af pg.tine.get _ ticks()-self.timer > self.delay: e.timer = pg.tine.get _ticks() for text, rect in self.taxt: recty = 1 def render(self, surf): for text, rect in self.text: ‘surf.blit(text, rect) screen = pg.display.set _ mode((800,600)) screen _ rect running=true ered = Credits(screen rect, text _ list) while cunning: for event in pg.event.get(): Af event.type == QUIT: running = False screen £11((0,0,0)) ‘cred.update() ccred,render(screen) Pg.display.update() ‘clock. tick(60) Vertically Scrolling Text ALLong Time Ago.. The obvious main point of enhancement is the actual text self. Replace It with alist of credits, or an equally epic ‘opening storyline to your Python game, andi will certainly hitthe mark with whoever playsit. Don't forget to change the screen resolution if needed; were currently running feat 800 x 600. 89 Een Code and res i} Text to Binary Convertor While it may not seem too exciting, this TXT2BIN.PY Mee eee Naturally we're using the Format function to convert the ORNS AMMEN GMM ccs entered text string tots binary equivalent you SoC CORCLRECUTINO Mor {0 eck ts 2cuaeyyoucan lug the binary nto an Moline textsinput("Enter text to convert to Binary: ") print(’ ‘join(format(ord(s), ‘b’) for x in text)) Seo aaa st File Edit Format Run Options windows Help print¢ ) text=input( ) print(* *.join(format(ord(x), text)) 1000010 1101001 1101110 1100001 1110010 1111001 The text to binary convertor does offer some room for improvement and enhancement. There are many uses:it could be utilised ina password or secret word script, as part of an adventure game or just a novel way to display someone's name. \With regards to improvements, ou could display the binary cenwersion ina Pygame window, using the animated text options From page 100, You could also ask the user if they wanted to have another go, or even askif they wanted the binary outputto be saved toa file, \With regards to rendering the outputted binary corwersion toa Pygame window, complete with rotating text, you can use: smport pygane ygane.inito BLACK = (0, 0, 0) ITE = (255, 255, 255) ‘BUM = (, 0, 258) GREEN = (0, 255, 0) RED = G55, 0, 0) Print (>oospesppptext to Binary Convertoropppoppppilangmancecececeee det guess{self,letter): Af letter in selfword and letter not in self. (guessed _ letters: If guessed _ lettere.append(letter) elif letter not in self word and letter not in self.mised letters: sf missed _ letters append(letter) for letter in self.word: Af letter not in self.guessed _letters: inte else: tn += letter return tn def print _ game _status(selé): Print (board{ien(self missed _ letters))) Print (Word: ° + self.hide_word)) print (‘Letters Missed: ) for letter in self.nissed _ letter print (letter,) print () Print ("Letters Gues for letter in self.guessed_ letters: print (letter,) Print () def rand _word(): bank = “ability about above absolute accessible ‘accommodation accounting beautiful bookstore calculator clever engaged engineer enough handsome refrigerator opposite socks interested ‘strawberry backgammon anniversary confused dangerous entertainnent exhausted impossible overveight temperature vacation scissors accommodation appointment. decrease development ‘earthquake environment brand environment necessary Hangman Game Script Auggage responsible anbassador circunstance congratulate frequent’,split() return bank{random.randint(0,len(bank))] ef main(): ‘gane = Hangman(rand _word()) while not gane hangman _ over(): ‘game.print _gane _ status() ‘user _ input = input(\nfnter a letter: ") ‘game guess(user _ input) ‘game print _ game _ status() if gane.hangman _won(): QuiT() Since this the last example in our Python code repository, we thought we'd go out witha bang and feature the hangman gallows being drawn with each incorrect quess of the word. Don't worry fit looks misaligned in the text here, this is merely de tothe differences between using the Python |DLE editor and pasting the code into a word processor (which Formats tings differenti) “There's plenty you can do to improve, enhance and expand on ‘what we've presented here, You can include aroutine that returns an errorif the user enters a number or character. You can include extra points For someone who guesses the entire ‘word n one go rather than one leer at atime and you could perhaps add Chopin's Funeral March should youlose the ‘game; or something celebratory if you win, Consider replacing the bank of words too. They're Found under the bank list, and could easly be swapped out For something more difficult IFyou download wivwcithub.com/

You might also like