Need Guidance with some Python code (Substitute Cypher Python) - python

I have some code already but I got feedback on how to pass the rest of the criteria but I have no idea how to do it.
Assignment brief:
You are working in a Newspaper office that handles the reports from their journalists. You have been asked to design a program that will be used to help them send confidential reports in that others cannot read as email is not secure, we need to generate an encryption key that they can encode their scoops and documents when sent by email.
The program will need to generate the key. Encode the message, export the key, import a key from another person and decode a message. It will be a simple substitution cipher. The key needs to be made up out of all Alphanumeric Characters and some Special Characters. It will be a single key per session so you will need to save the key if you close the program otherwise you won’t be able to decode those messages used to encode them.
All projects start with planning it is the most important part that can make or break a project so ensure this is carried out correctly
Pass, Merit and Distinction Requirements
What the feedback says to do:
You were asked to import a key and export a key your program doesn't allow this so you would need to resubmit to get Pass4 and Pass6
Code I have done so far below
def run():
x=input("code or decode? ")
if x == "code":
a=list("")
import string
alpha = str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
message=input("What is your message to encode? ")
x=len(message)
y=0
z=0
for counter in range(x):
y=y+1
letter = alpha.find(message[z:y])
z=z+1
letter=letter+13
if letter > 24:
letter=letter-24
letter=alpha[letter:letter+1]
if counter != x-1:
print(letter,end="")
else:
print(letter)
x=input("type yes to go again? ")
if x == "yes":
run()
else:
input()
else:
a=list("")
import string
alpha = str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
message=input("What is your message to decode? ")
x=len(message)
y=0
z=0
for counter in range(x):
y=y+1
letter = alpha.find(message[z:y])
z=z+1
letter=letter-13
if letter < 0:
letter=24+letter
letter=alpha[letter:letter+1]
if counter != x-1:
print(letter,end="")
else:
print(letter)
x=input("again? ")
if x == "yes":
run()
else:
input()
run()

I did some research and come up with this.
You can use it as it is or edit it to meet your needs. Hope it helps.
Update.1: The longer the message, the bigger the encryption key will be. One solution for this is to use zlib.compress method in order to shrink the key, and then decompress it when needed.
Update.2: Added the export/import functionality of the encryption key using a Json file (you can of course choose other way of storing data) along with a title assigned to it, so you have the choice to either enter the title or enter the encryption key of the message for decryption. The title is just optional and for simplicity purposes, you can get rid of it if you want to. You'll also notice the code contains lots of if/else statements, that's just so you know where you currently are and what choices you have.
A GUI based would be better.
import string
import json
import os
# A list containing all characters
alpha = string.ascii_letters
def code(title, message, key = 6):
temp_dict = {}
cipher=[]
for i in range(len(alpha)):
temp_dict[alpha [i]] = alpha [(i+key)%len(alpha )]
# Generating the encryption key
for char in message:
if char in alpha :
temp = temp_dict[char]
cipher.append(temp)
else:
temp =char
cipher.append(temp)
# This code is needed to decode the expected message so make sure to save it by any method you want,
# otherwhise it'll generate a random text.
cipher= "".join(cipher)
main_data = {title : cipher}
file_name = "encryption_key.json"
if os.path.exists(file_name):
with open(file_name, "r+") as file:
data = json.load(file)
data[0].update(main_data)
file.seek(0)
json.dump(data, file)
else:
with open(file_name, "w") as file:
json.dump([main_data], file)
print("Encryption code :",cipher)
def decode(cipher, key = 6):
temp_dict = {}
for i in range(len(alpha)):
temp_dict[alpha [i]] = alpha [(i-key)%(len(alpha ))]
# Decoding the message
decoded_text = []
for char in cipher:
if char in alpha :
temp = temp_dict[char]
decoded_text.append(temp)
else:
temp = char
decoded_text.append(temp)
decoded_text = "".join(decoded_text)
return decoded_text
while True:
# There is an optional parameter (key) within the function which you can change according to your preference.
# The default value is 5 and it needs to be the same in both encode and decodefunctions.
x=input('[E]ncode or [D]ecode? answer with "e/d:" ')
if x.lower() == "e":
title = input("Enter the title of the message: ")
message = input("What is your message to encode? ")
code(title, message)
break
elif x.lower() == "d":
file_name = "encryption_key.json"
if os.path.exists(file_name):
with open(file_name, "r+") as file:
data = json.load(file)[0]
else:
print("There is no related file for decryption.")
continue
choice = input('Enter the [T]itle or the [K]ey of the message for decryption. [A]ll to decrypt everything on the file. answer with "t/k/a:" ')
if choice.lower() == 't':
title = input("Enter the title: ")
if title in data.keys():
encryption_key = data[title]
print(decode(encryption_key))
break
else:
print("There is no such title.")
elif choice.lower() == "k":
encryption_key = input("Enter the encryption code related to the message? ")
if encryption_key in data.values():
print(decode(encryption_key))
break
else:
print("There is no such encryption key.")
elif choice.lower() == "a":
decrypt_dict = {}
for k, v in data.items():
decrypt_dict[k] = decode(v)
print(decrypt_dict)
break
else:
print("There is no related file for decryption.")
else:
print("Enter a valid answer.")

Related

Create encryption and decryption program

I need someone to edit my code to debug it. It won't display any of the encrypted or decrypted text which I think is because the formatting is messed up but I don't know. If you could help that'd be greatly appreciated. (I have to include functions and user input)
result = ''
text = ''
text = input("Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
def toList(text):
text.split()
return text
decrypted = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
encrypted = b"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM "
encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)
text = input('Enter message for encryption: ')
def encrypt(text):
result = ''
text = ''
result = text.translate(encrypt_table)
print(result + '\n\n')
cipherText = input('Enter message to decrypt: ')
def decrypt(cipherText):
result = ''
message = ''
result = message.translate(decrypt_table)
print(result + '\n\n')
if text == '1':
encrypt(text)
print(result + '\n\n')
elif text == '2':
decrypt(cipherText)
elif text != '0':
print('You have entered an invalid input, please try again. \n\n')
You had quite a number of confusions. Look at encrypt, for example. You pass in text, then you immediately set text='', thereby destroying the message that was input. Similarly, in decrypt, you pass in cipherText, but you run message.translate. And your functions need to return their results, not print them. Let the caller decide what to do with the returned results.
Also, it is a good practice to collect your functions at the top of the module, so you don't fool yourself into believing that things get called in the wrong order.
Here is your code, modified so that it works:
def encrypt(text):
result = text.translate(encrypt_table)
return result
def decrypt(message):
result = message.translate(decrypt_table)
return result
decrypted = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
encrypted = b"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM "
encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)
while True:
text = input("Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if text == '1':
text = input('Enter message for encryption: ')
result = encrypt(text)
print(result)
elif text == '2':
cipherText = input('Enter message to decrypt: ')
result = decrypt(cipherText)
print(result)
elif text == '0':
break
else:
print('You have entered an invalid input, please try again. \n\n')
Note that encrypt and decrypt don't really need to store in a temporary variable. The only reason to do that is because it is more convenient for debugging, to add a quick print(result) before the return.

Python 3 dictionary.get() function not working with sys.stdin

I am currently writing a dictionary program that allows the user to enter in two words: an English word and its foreign translation. Then, the user should be able to input a foreign word and retrieve the English word; however, I am required to use sys.stdin for the second half.
import sys
dictionary = dict()
userInput = input()
while userInput != "":
buf = userInput.split()
english = buf[0]
foreign = buf[1]
dictionary[foreign] = english
userInput = input()
for userInput in sys.stdin:
print(type(userInput))
if userInput in dictionary:
print(dictionary.get(userInput))
else:
print("Word not in dictionary.")
When I use sys.stdin, the dictionary.get() function is not functioning properly. When I simply use the normal input() function instead of sys.stdin, the dictionary is able to function properly. Why is this and how can I get sys.stdin to properly work with the dictionary search?
This code seems to work, but once again... it used input() instead of sys.stdin:
import sys
dictionary = dict()
userInput = input()
while userInput != "":
buf = userInput.split()
english = buf[0]
foreign = buf[1]
dictionary[foreign] = english
userInput = input()
userInput = input()
while userInput != "":
if userInput in dictionary:
print(dictionary.get(userInput))
else:
print("Word not in dictionary")
userInput = input()
Thanks!
A trailing '\n' was the issue. string = string.rstrip('\n') fixed this for me.

Getting the Value returned from a Loop to print() only once

When trying to retrieve the decrypted password for the second choice, I can't keep the program from printing Does Not Compute no matter whether the website entered is true or not. It prints twice when it is untrue so this leads me to believe the it's printing for i in the range(len(passwords)) which is 2.
How do I get it to print just the password or Does Not Compute once and not have it iterate again? I'm trying to check if the input is equal to the website but it still prints iterates twice.
import csv
import sys
# The password list - We start with it populated for testing purposes
passwords = [["yahoo", "XqffoZeo"], ["google", "CoIushujSetu"]]
# The password file name to store the passwords to
passwordFileName = "samplePasswordFile"
# The encryption key for the caesar cypher
encryptionKey = 16
# Caesar Cypher Encryption
def passwordEncrypt(unencryptedMessage, key):
# We will start with an empty string as our encryptedMessage
encryptedMessage = ""
# For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage
for symbol in unencryptedMessage:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
elif symbol.islower():
if num > ord("z"):
num -= 26
elif num < ord("a"):
num += 26
encryptedMessage += chr(num)
else:
encryptedMessage += symbol
return encryptedMessage
def loadPasswordFile(fileName):
with open(fileName, newline="") as csvfile:
passwordreader = csv.reader(csvfile)
passwordList = list(passwordreader)
return passwordList
def savePasswordFile(passwordList, fileName):
with open(fileName, "w+", newline="") as csvfile:
passwordwriter = csv.writer(csvfile)
passwordwriter.writerows(passwordList)
prompt_msg = """
What would you like to do:
1. Open password file
2. Lookup a password
3. Add a password
4. Save password file
5. Print the encrypted password list (for testing)
6. Quit program
Please enter a number (1-4)
"""
while True:
print(prompt_msg)
choice = input()
if choice == "1": # Load the password list from a file
passwords = loadPasswordFile(passwordFileName)
elif choice == "2": # Lookup at password
print("Which website do you want to lookup the password for?")
for keyvalue in passwords:
print(keyvalue[0])
print("----")
passwordToLookup = input()
for i in range(len(passwords)):
print(f"i={i}, store_info={passwords[i]}, website={passwords[i][0]}")
if passwordToLookup == passwords[i][0]:
password = passwordEncrypt(passwords[i][1], -(encryptionKey))
print(f"=> The password is {password}.")
else:
print("=> Does not compute!")
elif choice == "3":
print("What website is this password for?")
website = input()
print("What is the password?")
unencryptedPassword = input()
unencryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey)
newList = [website, unencryptedPassword]
passwords.append(newList)
print("Your password has been saved.")
elif choice == "4": # Save the passwords to a file
savePasswordFile(passwords, passwordFileName)
elif choice == "5": # print out the password list
for keyvalue in passwords:
print(", ".join(keyvalue))
elif choice == "6": # quit our program
sys.exit()
print()
print()
####### YOUR CODE HERE ######
# You will need to find the password that matches the website
# You will then need to decrypt the password
#
# 1. Create a loop that goes through each item in the password list
# You can consult the reading on lists in Week 5 for ways to loop through a list
#
# 2. Check if the name is found. To index a list of lists you use 2 square backet sets
# So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
# So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
# If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
# will want to use i in your first set of brackets.
#
# 3. If the name is found then decrypt it. Decrypting is that exact reverse operation from encrypting. Take a look at the
# caesar cypher lecture as a reference. You do not need to write your own decryption function, you can reuse passwordEncrypt
#
# Write the above one step at a time. By this I mean, write step 1... but in your loop print out every item in the list
# for testing purposes. Then write step 2, and print out the password but not decrypted. Then write step 3. This way
# you can test easily along the way.
#
It seems like you want to print does not compute only if NONE of the stored passwords match the input; but as it is, you're printing that message for EACH password that doesn't match (even if some other password did match).
I've modified your loop to break when a match is found, and only print the message if no matches were found (by adding an else clause to the for loop, which executes only if the loop makes it all the way to the end.)
passwordToLookup = input()
for i in range(len(passwords)):
if passwordToLookup == passwords[i][0]:
webSite = passwordEncrypt(passwords[i][1],-(encryptionKey))
print()
print('The password is ' + webSite+'.')
print(i)
print(passwords[i])
print(passwords[i][0])
break
else:
# if we got to the end of the loop, no passwords matched
print('Does not compute!')
First, I took the liberty to reformat and improve your code to look a bit nicer.
Multi-line string for the prompt
F-string to print variables (Python 3.4 and above)
Formatting with the new black module
Your problem is that you loop through all the stored websites
for i in range(len(passwords)):
if passwordToLookup == passwords[i][0]:
...
else:
...
Actually what you should do is
Checking if the website exists in the current list
Return decrypted password if found, and Cannot computer otherwise
The best way to do 1. is to:
Transform the tuples of passwords to a dictionary: passwords = {"yahoo":"XqffoZeo", "google":"CoIushujSetu"}
Check if website is one of the keys: if website in passwords.keys(): ...
Update the rest of the code accordingly (as the list of passwords is not a list of tuples but a dictionary)
Or more simply: just transform the list of tuples to a dictionary when extracting the password:
elif choice == "2": # Lookup at password
print("Which website do you want to lookup the password for?")
for keyvalue in passwords:
print(keyvalue[0])
print("----")
passwordToLookup = input()
dict_passwords = dict(passwords)
if passwordToLookup in dict_passwords:
encrypted = dict_passwords[passwordToLookup]
password = passwordEncrypt(encrypted, -(encryptionKey))
print(f"=> The password is {password}.")
else:
print("=> Does not compute!")

Python issue when reading from a file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hello so i was doing a school project and I wrote this out I got it all working so my next task was to make it to read the message from an file so i changed the definition where it asked for the message which is UserMessage() so i run the code it works it prints out whats in the text file but when i do the last bit where it gets the final answer it shows this error
Traceback (most recent call last):
File "C:\Users\christian\Desktop\Python\2 keywor with cypher code.py", line 138, in <module>
Restart()
File "C:\Users\christian\Desktop\Python\2 keywor with cypher code.py", line 127, in Restart
Text = TranslateMessage2(Key2, Message2, Option)
File "C:\Users\christian\Desktop\Python\2 keywor with cypher code.py", line 107, in TranslateMessage2
Translated.append(symbol) # The symbol was not in LETTERS, so add it to translated as is.
NameError: name 'Translated' is not defined
import pyperclip
Valid_Letters = 'ZABCDEFGHIJKLMNOPQRSTUVWXY' # This is where it stores the Letters witch are being used in the program
def Linespacer():
print('================================================================')
def GetOption(): # This is the first queston in the program witch is asking if they want to encrypt decrypt
while True:
print('Do you wish to encrypt or decrypt a message?')
Option = input().lower()
if Option in 'encrypt e decrypt d'.split():
return Option # This is where if the user does not enter the right ifomation it goes back tot he top and ask the question
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".') # If the user doers not enter the right thing for example if they enter an 'l' it prints that message
def UserMessage():
mes = str(input('would you like to encrypt or decrypt from a file or type your own message?(file/f or message/m): '))
if mes == 'f' or mes == 'file':
name = str(input("What is the document you want to read called?: "))
with open(name, "rt") as in_file:
text = in_file.read()
print(text)
return text
if mes == 'm' or mes == 'message':
text = str(input('Enter your message: '))
def UserKeyword(): # This def is what ask the user for the Message and gathers the infomation
print('Enter your First keyword:') # Prints out the message asking for the keyword
return input()
def UserKeyword2(): # This def is what ask the user for the Message and gathers the infomation
print('Enter your Second keyword:') # Prints out the message asking for the keyword
return input()
def TranslateMessage(Key, Message, Option): # This is the main def and where it does all of the maths when you call the def it reqires 3 Variables
Translated = [] # stores the encrypted/decrypted message string
keyIndex = 0 # This is the defult keyIndex when the program is started
Key = Key.upper() # This is allowing the user to have Upper case letters or lowercase letters
for symbol in Message: # loop through each character in message
num = Valid_Letters.find(symbol.upper()) #
if num != -1: # -1 means symbol.upper() was not found in LETTERS
if Option == 'encrypt' or Option == 'e':
num += Valid_Letters.find(Key[keyIndex]) #This makes it so if they are encrypting it adds
elif Option == 'decrypt' or Option == 'd':
num -= Valid_Letters.find(Key[keyIndex]) # This makes it so if they are decrypting it subtract
num %= len(Valid_Letters)
if symbol.isupper():
Translated.append(Valid_Letters[num])
elif symbol.islower():
Translated.append(Valid_Letters[num].lower())
keyIndex += 1 # move to the next letter in the key
if keyIndex == len(Key):
keyIndex = 0
else:
Translated.append(symbol) # The symbol was not in LETTERS, so add it to translated as is.
return ''.join(Translated) # It joins all of the functions together so the user can have all of the text together
def TranslateMessage2(Key2, Message2, Option): # This is the main def and where it does all of the maths when you call the def it reqires 3 Variables
Translated2 = [] # stores the encrypted/decrypted message string
keyIndex = 0 # This is the defult keyIndex when the program is started
Key2 = Key2.upper() # This is allowing the user to have Upper case letters or lowercase letters
for symbol in Message2: # loop through each character in message
num = Valid_Letters.find(symbol.upper()) #
if num != -1: # -1 means symbol.upper() was not found in LETTERS
if Option == 'encrypt' or Option == 'e':
num += Valid_Letters.find(Key2[keyIndex]) #This makes it so if they are encrypting it adds
elif Option == 'decrypt' or Option == 'd':
num -= Valid_Letters.find(Key2[keyIndex]) # This makes it so if they are decrypting it subtract
num %= len(Valid_Letters)
if symbol.isupper():
Translated2.append(Valid_Letters[num])
elif symbol.islower():
Translated2.append(Valid_Letters[num].lower())
keyIndex += 1 # move to the next letter in the key
if keyIndex == len(Key2):
keyIndex = 0
else:
Translated.append(symbol) # The symbol was not in LETTERS, so add it to translated as is.
return ''.join(Translated2) # It joins all of the functions together so the user can have all of the text together
def PlayAgainMessage():
again = str(input("Would you like to restart Y or N: "));
Linespacer()
if again == "Y" or again == "y": # This is an if statment it is saying that if the user types "Y" it runs the code to restart the program
Restart(); # If the user types "N" it Exits the program
elif again == "N" or again == "n":
exit()
def Restart(): # This is the def which allows the user to restart the prgram once they have done it
Option = GetOption()
Message = UserMessage()
Key = UserKeyword()
Key2 = UserKeyword2()
Message2 = TranslateMessage(Key, Message, Option)
Text = TranslateMessage2(Key2, Message2, Option)
Linespacer()
print('Your translated text is: %s' % Text) # Prints the message and get the text which has been encrypt or decrypt
pyperclip.copy(Text)
Linespacer()
name = str(input("What would you like to name the File: "))
name1 = str;
file = open(name+".txt", "w")
file.write(Text)
file.close()
PlayAgainMessage()
Restart()
You left a Translated in your TranslateMessage2 when you probably meant to change it to Translated2.
In TranslateMessage2:
Translated.append(symbol)
Should be:
Translated2.append(symbol)
You defined Translated in TranslateMessage but not in TranslateMessage2
As a result Translated does not exist within the global namespace, nor the namespace of TranslateMessage2.
Assuming you intentionally wanted to append to Translated and not Translated2 you either need to make Translated global variable or assign it to a variable through your TranslateMessage function.
To make Translated global you simply need to initialise it outside of the function.

Python - Word Scramble Game

While this assignment is past due (I joined the class late unfortunately) I still need to figure it out. I have the following list of words:
abhor:hate
bigot:narrow-minded, prejudiced person
counterfeit:fake; false
enfranchise:give voting rights
hamper:hinder; obstruct
kindle:to start a fire
noxious:harmful; poisonous; lethal
placid:calm; peaceful
remuneration:payment for work done
talisman:lucky charm
abrasive:rough; coarse; harsh
bilk:cheat; defraud
I need to read this file into a dictionary, pick a random key, scramble it, then ask the user to solve it. Unlike other solutions on here, it does not iterate three times, but runs until the user enters 'n'. The code will ask the user after each round if the user wants to continue the game. The user can also type 'hint' to get the definition of the word.
There is a similar question here: (http://www.dreamincode.net/forums/topic/302146-python-school-project-write-a-word-scramble-game-status-complete/) or rather the result of a question, but I am not knowledgeable enough to bridge the gaps and make it work for my purposes. None of the variation on this that I have seen on stack overflow come close enough for me to bridge the gap either, likely because I just don't know enough yet. Before we even start, this code does not yet work at all really, I am pretty lost at this point, so please be gentle. My code so far is below:
import random
from random import shuffle
#Reads the words.txt file into a dictionary with keys and definitions
myfile = open("words.txt", "r")
wordDict = dict([(line[:line.index(":")], line[line.index(":") +1 : -1])
for line in myfile.readlines()])
#print (b)
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
print('If you need a hint, type "Hint"\n')
#Picks a random key from the dictionary b
def shuffle_word():
wordKey = random.choice(list(wordDict.keys()))
return wordKey
#Gives a hint to the user
def giveHint(wordKey):
hint = wordDict[wordKey]
return hint
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def getAnswer():
answer = input('\nEnter your first guess: ')
while True:
if answer.isalpha():
return answer
else:
answer = input('\nPlease enter a letter: ')
def keepPlaying():
iContinue = input("\nWould you like to continue? ")
return iContinue
def scramble():
theList = list(shuffle_word())
random.shuffle(theList)
return(''.join(theList))
#Main Program
if keepPlaying() == 'y':
intro()
shuffle_word()
randomW = shuffle_word()
#scramKey = list(randomW)
thisWord = scramble()
print ("\nThe scrambled word is " +thisWord)
solution = getAnswer()
if solution == thisWord:
print("\nCongratulations")
if solution == 'Hint' or solution == 'hint':
myHint = giveHint(wordKey)
print(myHint)
else:
print("\nThanks for playing")
I have edited this post to ask for new information, though I am not sure if that ishow its properly done. Thanks to the help of those below, I have made progress, but am stuck not on a specific piece.
I have two questions. 1: How can I get the giveHint() function to return the definition of the random key selected by the shuffle_wprd() function. I know what I have above will not work because it is simply returning a string, but it seems like just using a dict.get() function would not get the correct definition for the random word chosen.
2: How can I get the program not to ask the user to continue on the first pass, but to then ask from then on. I thought about using a while loop and redefining the variable during the iteration, but I don't know enough to get it to work properly.
regardless, thank you to those people who have already helped me.
This should help you out a bit, the length seems to be of no benefit as a hint as you can see the length of the scrambled word so I used the definition as the hint,I think you also want to ask the user to guess the word not individual letters:
from random import shuffle, choice
#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
word_dict = {}
for line in f:
# split into two parts, word and description
word, hint = line.split(":")
word_dict[word] = hint
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
#Picks a random key from the dictionary b
def pick_word():
word = choice(list(word_dict.keys()))
return word
#Gives a hint to the user
def give_hint(word):
# return the definition of the word
descrip = word_dict[word]
return descrip
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def get_answer():
while True:
answer = input('Please enter a guess: ')
if answer.isalpha():
return answer
else:
print("Only letters in the word")
def main():
intro()
word = pick_word()
# give user lives/tries
tries = 3
shffled_word = list(word)
# shuffle the word
shuffle(shffled_word)
# rejoin shuffled word
shffled_word = "".join(shffled_word)
# keep going for three tries as most
while tries > 0:
inp = input("Your scrambled word is {}\nEnter h if you want to see your hint or any key to continue".format(shffled_word))
if inp == "h":
print("The word definition is {}".format(give_hint(word)))
ans = get_answer()
if ans == word:
print("Congratulations you win!")
break
tries -= 1
# ask user if they want to play again, restarting main if they do
play_again = input("Press 'y' to play again or any key to exit")
if play_again == "y":
main()
# else the user did not press y so say goodbye
print("Goodbye")
main()
There are a few more bits to be added but I will leave that up to you.
Thank you to all those who helped. For any who come along later, the final product is here. Similar to what Padraic Cunningham put, but without the three answer limit, and without his more elegant solution of wrapping the main program into a called function.
import random
from random import shuffle, choice
#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
wordDict = {}
for line in f:
# split into two parts, word and description
word, hint = line.split(":")
wordDict[word] = hint
#print (b)
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
print('If you need a hint, type "Hint"\n')
#Picks a random key from the dictionary b
def shuffle_word():
wordKey = choice(list(wordDict.keys()))
return wordKey
#Gives a hint to the user
def giveHint(wordKey):
descrip = wordDict[word]
return descrip
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def getAnswer():
answer = input('\nEnter a guess: ')
while True:
if answer.isalpha():
return answer
else:
answer = input('\nPlease enter a letter: ')
def getAnswer2():
answer2 = input('\nEnter another guess: ')
while True:
if answer2.isalpha():
return answer2
else:
answer2 = input('\nPlease enter a letter: ')
def keepPlaying():
iContinue = input("\nWould you like to continue? ")
return iContinue
#def scramble():
# theList = list(shuffle_word())
# random.shuffle(theList)
# return(''.join(theList))
#Main Program
while keepPlaying() == 'y':
intro()
#shuffle_word()
randomW = shuffle_word()
cheatCode = giveHint(randomW)
#scramKey = list(randomW)
thisWord = list(randomW)
print(thisWord)
random.shuffle(thisWord)
print(thisWord)
thisRWord = ''.join(thisWord)
print ("\nThe scrambled word is " +thisRWord)
solution = getAnswer()
loopMe = False
while loopMe == False:
if solution == randomW:
print("\nCongratulations")
loopMe = True
if solution == 'Hint' or solution == 'hint':
print(cheatCode)
if solution != randomW:
loopMe = False
solution = getAnswer2()

Categories

Resources