Okay, so I've been doing a lot of research and I couldn't find any answers so I came here to ask for some help.
My problem that I have encountered is I am having trouble taking a variable, then in the background of my code converting each individual string of that variable back to its ascii form and manipulating it using math, such as +, -, * and /. Here is my code..
Note: I had one theory, which is using a for loop to say for each character in this variable, do... blah blah. Here's my code anyways.
import random
import sys
import time
invalid_input = True
def start():
print("Welcome to the Encryption / Decryption Program!")
menuAnswer = input("Please select the number corresponding to the option you would like (1 - 3)\n---------------------------------\n[1] Encrypt\n[2] Decrypt\n[3] Exit the program\n---------------------------------\n")
if menuAnswer == '1':
print("You have chosen to Encrypt!")
invalid_input = False
message = open("sample.txt","r")
msgName = input("What is the name of the text document you would like to Encrypt?\n")
msgName = msgName.upper()
if msgName == 'SAMPLE':
key = '' #This variable will have the encryption key stored inside of it.
for i in range(0,8):
random_number = (random.randint(33,162)) #Generate a random ascii number from the range 33 to 162
key +=str(chr(random_number)) #Convert and store this ascii number as a character to the variable 'Key'
print(key)
print("Remember this key, as you will need it to decrypt your file!")
#\\ Offset //# #Finding the offset, must be able to convert each individual character of the key variable and return it to its usual form to manipulate using math.
else:
print("Invalid Filename")
elif menuAnswer == '2':
print("You have chosen to Decrypt!")
invalid_input = False
elif menuAnswer == '3':
print("You have chosen to exit!")
invalid_input = False
time.sleep(1)
print("Exiting...")
time.sleep(1.5)
exit()
else:
print("Invalid Input, Please try again!")
while invalid_input:
start()
Sorry if this question was difficult to understand, I am really confused myself and have been stuck on this for a week straight.
If I understand correctly you want to convert each character of your string to its ascii number and then do some sort of math operation on it and then convert it back to a string which you can do using ord() like so
s = 'Sample'
tmp = ''
for i in s:
tmp += chr(ord(i)+1)
print tmp
Tbnqmf
Although with the code you have you don't need to convert it to a string and then back to characters to manipulate it you can just manipulate it as soon as you pick a random number like so
import random
def start():
key = ''
for i in range(0,8):
random_number = (random.randint(33,162))
key +=chr(random_number+1)
print(key)
start()
Note you need to be careful when manipulating your characters since you could manipulate it to a number that is not an ascii character
Related
I do not know how to read a random character from a text file, and would like to learn how.
This is what happened when I started messing around with python! I know I will be doing something like this later on in school so I am practising. Reading a line would not suffice as you will see - I am open to tips and just a straight answer as I realise my code is very sloppy. The Raspberry Pi with this code on is running Raspbian lite with a few bits extra installed (a gui, idle), and runs python 3.5.3.
I write some of these to a text file:
f = open("selected.txt","w")
chars = 'abcdefghijklmnopqrstuvwxyz'
ucchars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
smbls = '`¬!"£$%^&*()-_=+{[}]:;#~#<,>.?'
nos = '1234567890'
space = ' '
Like this:
usechars = input('Use lower case letters? answer y or n.')
if usechars == 'y':
f.write(chars)
useucchars = input('Use upper case letters? answer y or n.')
if useucchars == 'y':
f.write(ucchars)
usesmbls = input('Use symbols? answer y or n.')
if usesmbls == 'y':
f.write(smbls)
usenos = input('Use numbers 0-9? answer y or n.')
if usenos == 'y':
f.write(nos)
usespace = input('Use spaces? answer y or n.')
if usespace == 'y':
f.write(space)
I would like to print a selected amount of random characters from the text file and print it in the shell, but I do not know how to get a random single character from a text file. If there would be a better way of doing it (probably the case) or you need more code please tell me. Thanks in advance.
UPDATE
here is the code:
f.close()
with open("selected.txt","r") as f:
contents = f.read
random_character = random.choice(contents)
for i in range(amnt):
password = ''
for c in range(length):
password += random_character
print(password)
If the file is not very large an easy way to pick a random character is to read it into a string first, then just select a random character from the string:
import random
with open("selected.txt", "r") as f:
contents = f.read() # NOTE the () after read
random_character = random.choice(contents)
print("The random character I've chosen is: ", random_character)
If you'd like to create a string with random choices you can use your for loop, but you have to choose a new random character inside the loop:
with open("selected.txt","r") as f:
contents = f.read()
password = ''
for i in range(amnt):
random_character = random.choice(contents)
for c in range(length):
password += random_character
print(password)
I am trying to make a quiz but my answers are in an external file, so but everytime I run it with my correct answers they say they are incorrect.
Here is my code:
randNum = int(random.randint(0, 4))
song = open("songList.csv","rt")
with open("songList.csv", "rt") as f:
songn = str(song.readlines()[randNum])
reader= csv.reader(f)
for row in reader:
print (songn[0])
guess = input("What is the song called?")
score = 0
correct_guess = False
while True:
if guess == songn:
correct_guess = True
break
score += 1
if score>=total:
break
song_guess = input("Incorrect! Try again:\n> ")
if correct_guess:
print("Answer correct!")
else:
print("game over")
As pointed out in the comments, you have trailing newline characters in one of the strings. Hence they aren't equal.
However I wouldn't just remove the newline. It is always good practice, if your logic allows it, to normalize strings before you test for equality. There are lots of things you can do to normalize:
def normalize(string):
string = string.strip() # Remove any leading or trailing whitespaces
string = string.lower() # Make all letters lowercase
string = " ".join(string.split()) # If the user hit spacebar twice, for example, will remove the double space. Note can have side effects.
return string
Then check
if normalize(string1) == normalize(string2):
do_something()
In fact, if you are dealing with user input, even this might not be sufficient. For example, if the user makes a typo, it won't match.
So I recommend also looking at the fuzzywuzzy library
from fuzzywuzzy import fuzz
def similar(string1, string2):
ratio = fuzz.ratio(string1, string2)
return ratio >= 85 # number between 0 and 100. Higher means fewer differences are allowed
Fuzzywuzzy is very powerful and easy to use. For more info: https://github.com/seatgeek/fuzzywuzzy
I'm doing some code on a banking system wherein there is a pre-set password, then the program will generate a random number using randint, then that random number is a position of a character in the pre-set password. The user must type the character that is in the position of the number that was generated, for example, if my pre-set password is 12345 and the generated number was 3, I should type 4 to be given access to the system.
As you could see, I'm testing out calling the character from the string and merging it with the random number but it doesn't work, do you have any other ideas to perform it? Thanks. Sorry if it may cause you some confusion but this is how far as my code has gone, I'm still starting out with python though.
import random
randomOne = (random.randint(0,3))
password = "code"
print(randomOne)
decode = input("input a character: ")
if decode == password + str(randomOne):
print("Access Granted")
pass
else:
print("Access Denied")
Is this what you're looking for?
#This is your randomly generated character position in the password
randomIndex = random.randint(0,len(code)-1)
#This is the character itself
randomCharacter = code[randomIndex]
#Ask the user for input
reply = input("Please enter the character in position", randomIndex+1)
#Check to see if user's input matches the actual character
if reply == randomCharacter:
print("Access")
else:
print("Fail")
You're not using any random numbers in here,
If you must know the index it chose, use:
random_position = random.randint(0, len(password)-1)
random_letter = password[random_number]
#then ask them to enter the letter at the index it chose
Otherwise if you only need a random letter from password use:
random_letter = random.choice(password)
#then ask for them to enter the letter it chose
Using random.randrange here would work. This will allow you to build a range using the len of your password, and then select a random integer from that range. You can then use this random int to index your code password.
from random import randrange
pwd = 'code'
pos = randrange(len(pwd))
attempt = input(f'Enter character at index {pos}: ')
if attempt == pwd[pos]:
print('Access Granted')
else:
print('Access Denied')
I am writing a program that will allow a user to decode a word (an encoded football team) that has been imported from a text file. Another text file contains the decoded football team. The user will be allowed to take a guess at decoding the word and selecting letters to replace in the word until he guesses them all correctly (then game over).
Thanks to some help I received here I was able to adapt some code that allowed me to record each character swap the user made by appending both the old and new letters through enumeration to an indices list.
I need the user to be able to choose to delete a previous character swap and that is where I am falling down at the minute. I know how to undo the previous change (thanks to some help here) but I want the user to be able to see the previous swaps listed in one go and then choose a letter to restore to its original place in the decoded letter. Here is the main function of the code so far:
def play():
global encoded
global plaintext
x = 40
for i in range(x):#give the user 40 goes maxiumum
print("\nThe encoded team is {0}\n".format("".join(encoded)))
choose = input("What character would you like to replace?")
indices = []
for i, j in enumerate(encoded):
if j == choose:
indices.append(i)
replace = input("What character would you like to replace it with")
for i in indices:
encoded[i] = replace
changes.append((choose, replace, indices))
for choose, replace, indices in changes:
print("Replaced '{0}' with '{1}'".format(choose, replace))
undo = input("Would you like to undo any changes - type 'undo'? ").lower()
if undo == "undo":
print("Here are the previous letters you have swapped ")
for i , j in enumerate (changes):
for c in changes:
for i in indices:
print(choose, replace)
Here are my text file calls and list definitions:
with open("football.txt","r") as file_one:
Encoded_Team = file_one.read()
with open("football_Solved.txt","r") as file_two:
Team = file_two.read()
encoded = list(Encoded_Team)
plaintext = list(Team)
changes = []
print("\nThe encoded team is {0}\n".format("".join(encoded)))
print("You will have 15 goes maxium")
menu()
Here is the menu:
def menu():
play_game = print("1. Play the game")
instruc = print("2. Instructions")
question = input("Enter choice")
if question == "2":
print("You will given a list of coded words, you have to replace the symbols to letters to get the word")
print("\n")
menu()
else:
play()
I am trying to develop the following piece of code from the main function so it allows the user to choose a previous character swap to undo - I know I need to enumerate but I am just not able to piece it together. Any ideas?
undo = input("Would you like to undo any changes - type 'undo'? ").lower()
if undo == "undo":
print("Here are the previous letters you have swapped ")
for i , j in enumerate (changes):
for c in changes:
for i in indices:
print(choose, replace)
I have added the following code to display the previous pairings chosen:
if undo == "undo":
for index, change in enumerate(changes):
chosen, replaced, indices = change
pairs.append(change)
for change in pairs:
print(chosen, replaced)
But instead of displaying the two last pairing, it will display the last pairing twice
What character would you like to replace?M
What character would you like to replace it withL
Replaced 'M' with 'L'
Would you like to undo any changes - type 'undo'?
The encoded team is Ljwfsqppm
What character would you like to replace?j
What character would you like to replace it withi
Replaced 'M' with 'L'
Would you like to undo any changes - type 'undo'? undo
j i
j i
Replaced 'j' with 'i'
Would you like to undo any changes - type 'undo'?
Any idea?
I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.