Overview

This blog briefly discusses how I was able to implement what we learned in 2.3 this week into my PBL Project that could also be my CPT submission. Below is a python code block that includes comments as well as extra explanations below it.

import pandas as pd
import random
import sys

# student-developed procedure update_progress, includes sequencing, selection, and iteration.
def update_progress(letter, word, blanks, progress):
    for i in range(len(word)):
        if letter == word[i]:
            blanks[i*2] = word[i]
            # keeps track of progress, if progress = word, the user has won
            progress[i] = word[i]

words = pd.read_json("files/words.json")
word = random.choice(words["words"].values)

lives = 7

# creates a list, number of blanks depends on length of the word

# the blanks list and the progress list stores the number of letters that the user has guessed correctly (data abstraction), list is used rather than defining a variable for every single letter (managing complexity?)

blanks = ["_", " "]*len(word)

progress = [" "]*len(word)

while lives > 0:
    if "".join(progress) == word:
        print("You Win!")
        sys.exit()
    print("".join(blanks))
    user_input = input("Enter a letter.")

    if user_input.lower() in word:
        print(f"The letter {user_input} is in the word")
        update_progress(user_input.lower(),word,blanks,progress)

        
    else:
        lives-=1
        print(f"Sorry! The letter {user_input} is not in the word.")

if lives == 0:
    print(f"You Lost! The word was {word}.")
    sys.exit()
_ _ _ _ _ _ _ _ 
The letter  is in the word
_ _ _ _ _ _ _ _ 
Sorry! The letter g is not in the word.
_ _ _ _ _ _ _ _ 
Sorry! The letter a is not in the word.
_ _ _ _ _ _ _ _ 
The letter e is in the word
_ _ _ e _ e _ _ 
The letter i is in the word
i _ _ e _ e _ _ 
Sorry! The letter o is not in the word.
i _ _ e _ e _ _ 
Sorry! The letter u is not in the word.
i _ _ e _ e _ _ 
The letter n is in the word
i n _ e _ e _ _ 
Sorry! The letter m is not in the word.
i n _ e _ e _ _ 
The letter t is in the word
i n t e _ e _ t 
The letter r is in the word
i n t e r e _ t 
The letter s is in the word
You Win!
An exception has occurred, use %tb to see the full traceback.

SystemExit
/home/emaad/anaconda3/lib/python3.9/site-packages/IPython/core/interactiveshell.py:3377: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

Brief Explanation

As shown, this program randomly chooses words from a database file that I created called words.json. The program reads what is inside the file (read_json) and randomly chooses a work from there. This program uses the pandas libraries that we learned about in order to perform this operation. The contents of the words.json file is shown below (generated with PIL!)

from PIL import Image
db = Image.open('../images/wordsdbfile.png')

display(db)