How do I make this only print the last value? - python

I have the fallowing code to encrypt a massage:
massage= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
say I give "yo yo" to it
it will give me :
,
,:
,:u
,:u,
,:u,:
I only need the final answer which is the ,:u,:
what do i have to do?

Put the print statement outside the loop.
Since the print statement is inside, it is running once per iteration. If it is outside, then it will only do it one time-- once it has finished.
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt

Move the print statement outside the for loop. To do that you need to unindent the print statement.

unindent the call to print. This will take it out of the for loop and only print its value when the loop is finished.
On a slightly different note, you might want to work on your acceptance rate if you want people to put time and effort into answering your questions. You've asked 8 questions so far and you haven't accepted an answer to any of them. (Click the arrow next to an answer to accept it)

message= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(message)):
encrypt = encrypt + chr(ord(message[i]) ^ key)
print encrypt

Using a generator:
message= raw_input("Enter message to be encrypted: ")
key=0b1010101
print ''.join(chr(key^ord(c)) for c in message)

Related

Python ValueError: chr() arg not in range(0x110000)

import enchant
message_decrypt= input("Enter the message you want to decrypt: ")
key= 0
def caesar_hack(message_decrypt,key):
final_message=""
d= enchant.Dict("en.US")
f= d.check(message_decrypt)
while f== False:
for characters in message_decrypt:
if ord(characters)<=90:
if ord(characters)-key<ord("A"):
final_message= final_message+ chr(ord(characters)-key)
else:
final_message= final_message+ chr(ord(characters)-key+26)
else:
if ord(characters)-key<ord("a"):
final_message=final_message+chr(ord(characters)-key)
else:
final_message= final_message+chr(ord(characters)-key+26)
key=key+1
f= d.check(message_decrypt)
else:
print(final_message)
caesar_hack(message_decrypt, key)
Why doesn't this code work?
I'm trying to do a caesar cipher hack using the brute force technique. I get an error as below
Can someone please help fix this code.
There's a couple of tweaks I had to make to get your code to work, here's a working version:
import enchant
message_decrypt= input("Enter the message you want to decrypt: ")
key= 0
def caesar_hack(message_decrypt,key):
final_message=""
d= enchant.Dict("en.US")
f= d.check(message_decrypt)
while f== False:
for characters in message_decrypt:
if ord(characters)<=90:
if ord(characters)-key<ord("A"):
final_message= final_message+ chr(ord(characters)-key+26) # The additional 26 should be here, not below
else:
final_message= final_message+ chr(ord(characters)-key)
else:
if ord(characters)-key<ord("a"):
final_message=final_message+chr(ord(characters)-key+26) # The additional 26 should be here, not below
else:
final_message= final_message+chr(ord(characters)-key)
key=key+1
f= d.check(final_message) # Check should be on final_message, not message_decrypt
if not f:
final_message = "" # Need to reset the final_message if not matched
else:
print(final_message)
caesar_hack(message_decrypt, key)
I've commented the main changes I made. One key one was checking final_message in the loop, not message_decrypt (and resetting it again for the next loop if no match).
The other was that your addition of 26 to the character ordinal if it was out of range needed to be moved. Without doing that, it was generating non-printable characters so the check was failing with an enchant error.

Passwords/username from a file

I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]

Python XOR Encryption program sometimes doesn't work

I am trying to make a simple xor encryption program in python and what I have now is working almost fine, only sometimes it doesn't and I just can't figure out why. For example, if I input 'hello' and the key '1234' it will encrypt it to YW_X^ and if I then decrypt this with the same key it will print 'hello'. But if I change the key to 'qwer' the encrypted message is something like '^Y^R ^^^^' and if I try to decrypt it, 'heERQWERoi' comes out.
This is the code:
from itertools import cycle, izip
choice = int(raw_input('Press 1 to encrypt, 2 to decrypt. '))
if choice == 1:
message = raw_input('Enter message to be encrypted: ')
privatekey = raw_input('Enter a private key: ')
encrypted_message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(privatekey)))
print 'Encrypted message:'
print encrypted_message
elif choice == 2:
todecrypt = raw_input('Enter a message to be decrypted: ')
otherprivatekey = raw_input('Enter the private key: ')
decrypted_message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(todecrypt, cycle(otherprivatekey)))
print 'Decrypted message:'
print decrypted_message
I have no idea what is wrong with it so I would really appreciate some help, thank you!
It's probably working fine, but you are getting characters which you may not be able to re-input into your terminal directly as they don't correspond to the ordinarily inputtable ASCII characters. In particular, with the key qwer, the values of ord become [25, 18, 9, 30, 30], which you may have a hard time inputting (cf. this table).
The similar problem will not occur if you use 1234 as a key as in that case the values are [89, 87, 95, 88, 94] which correspond to "normal" characters.
Your script is printing non-printing characters, which sometimes can't be copy/pasted. You could encode the ciphertext into a format that uses only the characters abcdef0123456789, which lets you display it without issue:
print encrypted_message.encode('hex')
You can then decode it when the user types it in once more:
todecrypt = raw_input('Enter a message to be decrypted: ').decode('hex')

There appears to be a bug in my XOR encryption program written in python

I have been trying to write a simple encryption program in Python, and when I try to execute the code on Linux, it is not printing anything. Could someone please tell me why?
#!/usr/bin/env python2
import binascii
def encrypt():
text = raw_input("Please input your information to encrypt: ")
for i in text:
#Convert text into a binary sequence
i = bin(int(binascii.hexlify(i),16))
key = raw_input("Please input your key for decryption: ")
for j in key:
#Convert key into a binary sequence
j = bin(int(binascii.hexlify(j),16))
#This is only here for developmental purposes
print key
print text
Edit
I did what one of the users said, but my code still does not seem to be converting my plain text into binary like I want it too.
#!/usr/bin/env python2
def encrypt():
text = raw_input("Please input your information to encrypt: ")
for i in text:
#Convert text into a binary sequence
i = bin(ord(i))
key = raw_input("Please input your key for decryption: ")
for j in key:
#Convert key into a binary sequence
j = bin(ord(j))
#This is only here for developmental purposes
print key
print text
encrypt()
There are a number of major problems with your program:
You are defining a function called encrypt(), but never calling it.
Neither of your loops actually modifies the string. They modify loop variables, which are not the same thing!
int(binascii.hexlify(x), 16) is an overcomplicated way of writing ord(x).
bin() does not do what you are hoping for here.
Nothing is actually being XORed here. Your program is unfinished.
I think this is what you're trying to do
def encrypt():
cleartext = raw_input("Please input your information to encrypt: ")
ciphertext = []
for char in cleartext:
ciphertext.append(bin(ord(char))[2:])
ciphertext = ''.join(ciphertext)
key = raw_input("Please input your key for decryption: ")
decryptionKey = []
for char in key:
decryptionKey.append(bin(ord(char))[2:])
decryptionKey = ''.join(decryptionKey)
print "The key is '%s'" %decryptionKey
print "The encrypted text is '%s'" %ciphertext

Restricting the User Input to Alphabets

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.

Categories