Unbound Local Error Python Cipher - python-3.x

I have been trying out this Ceasar Cipher and I am getting an error that I can't seem to get around. I am currently using python36 and wondering if there is anyone that can let me know why the unbound local error is coming up. Thank you!
#Ceasar Cipher
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
MAX_KEY_SIZE = len(SYMBOLS)
def getMode():
while True:
print('Do you wish to ENCRYPT or DECRYPT a message?')
mode = input().lower()
if mode in ['encrypt', 'e', 'decrypt', 'd']:
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
symbolIndex == SYMBOLS.find(symbol)
if symbolIndex == -1: # Symbol not found in SYMBOLS.
# Just add the symbol without any change.
translated += symbol
else:
# Encrypt or decrypt.
symbolIndex += key
if symbolIndex >= len(SYMBOLS):
symbolIndex -= len(SYMBOLS)
elif symbolIndex < 0:
symbolIndex += len(SYMBOLS)
translated += SYMBOLS[symbolIndex]
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
Update
The error I receive looks like this:
Traceback (most recent call last):
File "C:\Users\Badger\Desktop\DEV\Scripts\Ceasar_Cipher.py", line 52, in
print(getTranslatedMessage(mode, message, key))
File "C:\Users\Badger\Desktop\DEV\Scripts\Ceasar_Cipher.py", line 32, in getTranslatedMessage
symbolIndex == SYMBOLS.find(symbol)
UnboundLocalError: local variable 'symbolIndex' referenced before assignment

The key for the Caesar Cipher will be a number from 1 to 26.
your len(SYMBOLS) is larger than 26.
This Code Worked for me with python3
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = raw_input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return raw_input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
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
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))

I found what was wrong...
I set the symbolIndex to "==" when I was assigning it.
After changing it to "=" everything worked beautifully!

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

Code Not Compiling- Unable to figure out Issue

I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)

convert between str of text and lists of numbers in which described in the Numerical Equivalents of Letters

dic is a lookup dic for letters to number and numdic is a lookup for num to letters
'k':'10','l':'11','m':'12','n':'13','o':'14','p':'15','q':'16','r':'17','s':"18",'t':'19','u':'20',
'v':'21','w':'22','x':'23','y':'24','z':'25'}
numdic = {'0':'a','1':'b','2':'c','3':'d','4':'e','5':'f','6':'g','7':'h','8':'i',
'9':'j','10':'k','11':'l','12':'m','13':'n','14':'o','15':'p','16':'q','17':'r','18':'s','19':'t','20':'u',
'21':'v','22':'w','23':'x','24':'y','25':'z'}
def encode(message):
cipher = ''
for letter in message:
# checks for space
if(letter != ' '):
#adds the corresponding letter from the lookup_table
cipher += dic[letter]
else:
# adds space
cipher += ' '
return cipher
def decode(nummessage):
ciphertext = ''
for letter in nummessage:
if (letter != ' '):
ciphertext += numdic[letter]
else:
ciphertext +=' '
return ciphertext
# Driver function to run the program
def main():
#encrypt the given message
print('Enter a message to encrypt:')
message = input()
print(encode(message))
print('Enter message to decrypt:')
nummessage = input()
#decrypt the given message
print(decode(nummessage))
if __name__ == '__main__':
main()
when i run the code, for decoding if i enter 18 for example it gives me bi instead of s, is there another way to do this?
Your issue is that you are interpreting 18 as '18'. Then, when you iterate over that you get '1' and '8'. Try:
def decode(nummessage):
ciphertext = ''
for letter in nummessage.split(','):
if (letter != ' '):
ciphertext += numdic[letter]
else:
ciphertext +=' '
return ciphertext
And you can use it like this:
>>> decode("18,1,2")
sbc

How to encrypt using 2 keys/keynumbers (Caesar cipher)

How would you encrypt using 2 keys instead of 1 key? It is for school.
So it would ask how much to shift the code by, then ask how many times to shift again, which would shift it even further.
def runProgram():
def choice():
userChoice = input('Do you wish to Encrypt of Decrypt? Enter E or D: ').lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getPees():
try:
userpees = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getpees()
else:
if userpees < 1 or userpees > 26:
print("Invalid Option. Please try again.")
getpees()
else:
return userpees
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
def getpranslated(userChoice, message, pees):
pranslated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
pranslated += chr(num)
else:
for character in message:
num = ord(character)
num -= key
pranslated += chr(num)
return pranslated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
pees= getPees()
sqq= getTranslated(userChoice, message, key)#Runs function to translate message, using the choice, message and key variables)
spp= getTranslated(userChoice, message, pees)
dranslatedMessage = sqq + spp
print( 'hi' + int(spp), int(sqq) )
runProgram()

Python caesar cipher A-Z capital only

Just need a suggest for my code as, I have my code at the moment so that it will work and just add 5 to the ASCII value, but what I need to know is how can I make this work for just moving 5 places along the alphabet e.g. now if I were to type Z I would just get a _ when I would like to get a D.
Ceaser Cipher
bLoopProgram = True
while bLoopProgram == True:
sEncryptOrDecrypt = input("Encrypt Or Decrypt : ").lower()
if sEncryptOrDecrypt == "encrypt":
while sEncryptOrDecrypt == "encrypt":
sPassNonEnc = input("Enter a password to encrypt : ")
aPass = []
for i in range(0, len(sPassNonEnc)):
nASCII_VALUE = ord(sPassNonEnc[i])
if nASCII_VALUE < 64:
nASCII_VALUE += 10
aPass.append(chr(nASCII_VALUE))
elif nASCII_VALUE > 63:
nASCII_VALUE -= 10
aPass.append(chr(nASCII_VALUE))
else:
print("\n * Unknown Character [ASCII INDEX]")
aPass.append()
print("".join(aPass))
sSaveToTxt = input("Would you like to save your encrypted password to a text document?\nThe Text document will be found next to this python file and called password_enc (Yes/no): ").lower()
if sSaveToTxt == "yes":
fFileRequestedOpen = open('password_enc.txt', 'w')
fFileRequestedOpen.write("".join(aPass))
fFileRequestedOpen.close()
print("Saved to text document have a nice day!")
break
elif sSaveToTxt == "no":
print("okay have a nice day!")
break
else:
print("\n*Invalid Option*\n")
if sEncryptOrDecrypt == "decrypt":
while sEncryptOrDecrypt == "decrypt":
sReadOrInput = input("Would you like to load password from text document if saved,\n or would you like to input a encypted password (read/enter): ").lower()
if sReadOrInput == "read":
fFileRequestedOpen = open('password_enc.txt', 'r')
sPassEnc = fFileRequestedOpen.read()
fFileRequestedOpen.close()
aPass = []
for i in range(0, len(sPassEnc)):
nASCII_VALUE = ord(sPassEnc[i])
if nASCII_VALUE < 64:
nASCII_VALUE -= 10
aPass.append(chr(nASCII_VALUE))
elif nASCII_VALUE > 63:
nASCII_VALUE += 10
aPass.append(chr(nASCII_VALUE))
else:
print("\n * Unknown Character [ASCII INDEX]")
print("".join(aPass))
break
if sReadOrInput == "enter":
sPassEnc = input("Enter a password to decrypt : ")
aPass = []
for i in range(0, len(sPassEnc)):
nASCII_VALUE = ord(sPassEnc[i])
if nASCII_VALUE < 64:
nASCII_VALUE -= 10
aPass.append(chr(nASCII_VALUE))
elif nASCII_VALUE > 63:
nASCII_VALUE += 10
aPass.append(chr(nASCII_VALUE))
else:
print("\n * Unknown Character [ASCII INDEX]")
print("The now unencrypted password is:")
print("".join(aPass))
break
elif sEncryptOrDecrypt == "quit":
quit()
else:
print("")
You have to use modulo (%) to restrict your values within 65 (A) and 90 (Z)
For instance:
nASCII_VALUE = 90 # This is a Z
nASCII_VALUE += 5 # chr(95) = _
print(chr(((nASCII_VALUE - 64) % 26) + 64))
This will print 'E' (5th letter of alphabeth)

Resources