Skip to main content

Posts

Showing posts from May, 2023

What Is Recursion?

  What Is Recursion? 👉 Recursion is a type of program where you get a subroutine to call itself. It gets kinda hard to explain. I'd very much recommend this book, which does an excellent job of explaining this concept. Recursion lets us solve problems in a more human way. Some mathematical problems can just be solved better using recursion. For example: We want to print out a sequence of the same emoji, reducing by 2 emojis per line. (eg print a row of 9, then a row of 7, then 5, etc. until we get none). We will end up with a reverse pyramid pattern. We could use range(), but it's a bit odd with counting backwards. Or a loop, but that would be pretty long. 👉 Here's an example of a recursive solution. def reverse(value):   if value <= 0:     print("Done!")     return   # This `if` provides the 'stop' condition for the program. Otherwise it would run forever.   else: # if we're not at the stop condition.     for i in range(value):       print("

The os Library , List a file, Create a folder, Renames a file

  The os Library Today's lesson is going to use the os library to create folders and navigate around them. Previously, we've used os to clear the screen. Here are a few other things that it can do: List a file 👉 listdir() will allow you to list all the files: import os print(os.listdir()) # Lists all the files in the current directory. Useful for checking that a file is in the folder we think it is. files = os.listdir() if "quickSave.txt" not in files:   print("Error: Quick Save not found.") #Checks if a file is in a directory and outputs an error if not. Create a folder 👉 Try this code with os.mkdir(): import os os.mkdir("Hello") # Creates a folder called 'Hello'  Renames a file 👉 os.rename() takes 2 arguments: the file to rename and the new name. import os os.rename("myname.txt", "NEW.o")

Comma-Separated Values , Make it Beautiful! , Filter the Output

 Comma-Separated Values CSV files are a way of storing a spreadsheet as a text file. Every value in the file is separated by a comma. Hence the name... Look, it's basically a spreadsheet. Opening A CSV File Fortunately, CSV files are so common that Python already has built-in libraries for working with them. 👉 The csv file 'January.csv' has been added for you. Let's see what happens: import csv # Imports the csv library with open("January.csv") as file: # Opens the csv file   reader = csv.reader(file) # reads the contents of the csv file into the 'reader' variable   line = 0   for row in reader: # loop to output each row in the 'reader' variable one at a time.     print (row) This works, but the output isn't very pretty. And we like pretty. Make it Beautiful! 👉 Let's use join. It allows us combine lists in a more interesting way. import csv  with open("January.csv") as file:    reader = csv.reader(file)    line = 0   for row

Avoiding Crashes, Try...except ,You are a Software Developer! , Traceback

  Avoiding Crashes Sometimes, we just can't code around a crash. It's coming anyway, and all you can do is brace for impact. Until now! Let's look at an example based on yesterday's lesson.  👉 In this example, if the 'Stuff.mine' file doesn't exist, then the code will throw a 'no such file' error. myStuff = [] f.open("Stuff.mine","r") myStuff = eval(f.read()) f.close() for row in myStuff:   print(row) Try...except The new construct to get around this is called try.... except All the code that should work goes inside the try. The error messages/instructions to handle any errors running the try code go inside the except 👉 Like this: myStuff = [] try:   f.open("Stuff.mine","r")   myStuff = eval(f.read())   f.close() # Try to find a file called 'Stuff.mine' and open it except:   print("ERROR: Unable to load") # If the file can't be found, show the error instead of crashing the whole program

Save to and Load From Files, Auto-Save, Preventing Data Loss

  Save to and Load From Files There are some things that primary storage in the RAM does better. For example, it's easy to access, amend, or remove a piece of data held in a list (in the RAM). Holding data in secondary storage in a file makes this more difficult. Or does it? With Python, there's more than meets the eye 👉 The program below lets me add & remove events and dates into a diary system. It adds the name & date of an event to the 2D list. Or it searches for an existing name & date and removes it. myEvents = [] def prettyPrint():   print()   for row in myEvents:     print(f"{row[0] :^15} {row[1] :^15}")   print() while True:   menu = input("1: Add, 2: Remove\n")   if menu == "1":     event = input("What event?: ").capitalize()     date = input("What date?: ")     row = [event,date]     myEvents.append(row)     prettyPrint()   else:     criteria = input("What event do you want to remove?: ").title()

Open , Read and Close , Print , Split , Form an orderly queue , Repeat , Just Use a Loop!

  Reading From a File  Once we've got data into a file, wouldn't it be just splendid to load it back into our program to use again? Yes. Yes is the answer you're looking for. Open  👉 The code to load from a file is pretty similar to that for writing. The command is open instead of read, and the permissions are slightly different. f = open("filenames.list", "r")    Read and Close 👉 In this example, the permission 'r' means 'read only'. Now we load the contents of the file into a variable using the read function. Next, close the file to free up the RAM used to store it. f = open("filenames.list", "r") contents = f.read() f.close() Print 👉 Finally output the contents of the 'contents' variable to test that it worked. f = open("filenames.list", "r") contents = f.read() f.close() print(contents) Split Bringing everything in in one go is fine, but it would be much more useful to have it as sepa

File Writing , Temporary Memory , Creating A New File , Close , Preventing Overwrite , New Lines

  File Writing  Our repls don't need to be just one file that contains all of the code and data. We can write data to other files for longer term storage, then access it when we need it.  To do this we're going to use the Files tab in the left hand toolbar. It looks like this    Temporary Memory When we use variables, lists, dictionaries and other data structures in our code, the data inside them are stored in the computer's RAM. RAM is temporary storage (usually called memory). It's used to hold data and instructions for programs that your computer currently has open. The problem is, that when a program finishes, or is closed, its data and instructions are removed from the RAM to free up space. This is why you had to re-input all of your test data for your dynamic list & dictionary programs every time you ran them. The contents of those lists/dictionaries were removed from RAM when the program finished executing. Creating A New File To avoid this incredibly annoyin

2D Dictionaries

    2D Dictionaries  Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it's worth and the key is what it is called. The key is used to access the value, and keys are more meaningful than index numbers. Today we are going to expand our mad dictionary skills into the second dimension.  Dynamically Adding To A 2D Dictionary  This code dynamically adds to a 2D dictionary by starting with an empty dictionary and using an infinite loop to add user input. EXAPMLE: clue = {} while True:   name = input("Name: ")   location = input("Location: ")   weapon = input("Weapon: ")   clue[name] = {"location": location, "weapon":weapon}#line 7   print(clue) The real magic happens on the 7th line of code. Instead of using .append() like we would with a list, we create a new dictionary entry. The key is the name of the beast, but the value is a whole new dictionary that contains the d