Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
alphabet = 'abcdefghijklmnopqrstuvwxyz'
message = input('Please insert the message you want to encrypt')
key = input('whay key value do you want in your encyption?')
for m in message:
if m in alphabet:
key += alphabet [(alphabet.index(m)+key)%(len(alphabet))]
Keeping to your original idea, you were fairly close. Note, Python already keeps a handy list of lower case letters:
import string
alphabet = string.ascii_lowercase
message = input('Please insert the message you want to encrypt: ')
key = int(input('What key value do you want in your encryption? '))
output = []
for m in message:
if m in alphabet:
output.append(alphabet[(alphabet.index(m) + key) % (len(alphabet))])
print(''.join(output))
You need to create a new output list of characters as it is not possible to directly change the characters in the original string. This list can then be joined back together to display your output.
So for example, this would give you the following:
Please insert the message you want to encrypt: hello
What key value do you want in your encryption? 3
khoorzruog
Please also note, there are more efficient ways to tackle this, for example the use of maketrans.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
My problem is very small, and is that I can't do a normal letter substitution. I know the .replace command, but I can't seem to use it correctly.
For example: My k##yb0%%rd is br###k##n. ### should be replaced with o, ## with e, and %% with a. Thanks!
a = input("What did she say? ")
b = a.replace("###", "o")
print(b)
You can try something like this:
a = input("What did she say? ")
d = {'###':'o', '##':'e','%%':'a'}
for k,v in d.items():
a = a.replace(k, v)
b = a # if you need value in b variable
print(b)
You can create such dictionary and use it replace multiple values. Make sure to properly arrange your dictionary.
As the first thing I would suggest to read the Python's documentation for str.replace.
I would suggest something like this:
b = a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')
This is possible because the returned value of a.replace("###", 'o') is of type str, so that the method replace can be applied on it too.
If you don't know which characters will be replaced, you should do like suggested by Vaibhav, creating a dict that associates old chars (key) with new chars (value).
What's more str is an immutable type, so you can't just do
a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')
but anyway you don't have to assign the returned value to b, you can't reassign it to a without problems:
a = a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')
and you can print it directly too.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Q. Write a function called shift_string that takes a string and an integer n as parameters and returns a new string with every letter of the string shifted by the n alphabets. It should also work for negative alphabets in reverse order.
So far, I have come up with this:
usr_input=input('Please enter string: ')
n=input('enter shifts: ')
encryption= ""
def shift_string(usr_input,n):
for i in usr_input:
if i.isupper():
i_unicode=ord(i) #find position
i_index=i_unicode-ord('A')
new_index= (i_index + n)
new_unicode= new_index +ord('A') #to perform shift
new_character=chr(new_unicode)
encryption= encryption+new_character #to append string
else:
encryption=encryption+i #for non-uppercase
print('Encrypted text is',encryption)
At encryption= encryption+new_character I am getting the error:
"Local variable 'encryption' defined in enclosing scope on line 23 referenced before assignment...(pyflakes E)"
n=input(eval('enter shifts: '))
The argument to eval() has to be a string containing a Python expression. enter shifts is not a valid expression, you can't evaluate it. I suspect you meant eval(input('enter shifts: ')).
But you shouldn't use eval() to process user input. If you want to convert the input to a number, use int() or float().
n = int(input('enter shifts: '))
The second error is because encryption is a local variable in the function, and you're trying to add to it before you've initialized it. You need to move encryption = "" inside the function. Then you can return the value.
def shift_string(usr_input,n):
encryption = ""
for i in usr_input:
if i.isupper():
i_unicode=ord(i) #find position
i_index=i_unicode-ord('A')
new_index= (i_index + n)
new_unicode= new_index +ord('A') #to perform shift
new_character=chr(new_unicode)
encryption= encryption+new_character #to append string
else:
encryption=encryption+i #for non-uppercase
return encryption
encrypted = shift_string(usr_input, n)
print('Encrypted text is',encrypted)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I can't find a way to sum the ASCII numerical values, I keep getting errors.
This is my code:
str = input("Enter your name: ")
for c in str:
print("The ASCII value for ", c, "is", ord(c))
I deleted the part that was summing it because it was wrong.
You can try with the following using built-in sum and list comprehensions. As a good practice, remember not to define variables with built-in types or functions names (str).
name = input("Enter your name: ")
for c in name:
print("The ASCII value for ", c, "is", ord(c))
print("The total sum is: ",sum([ord(c) for c in name]))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, the part of this project I cannot get to work is the sum() function.
It works during:
a = [1, 2, 3, 4, 5]
b = sum(a)
print b
But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.
namelist = []
agelist = []
while True:
name = raw_input("Enter a name or type Exit to end data entry: ")
namelist.append(name)
if name == "Exit": #creates an exit point from data entry
break
age = raw_input("How old is " + name + "? ")
agelist.append(age)
lenage = len(agelist)
sumage = sum(agelist) #here is the problem -<<
avgage = sumage / lenage
print avgage
How can I get the sumage to work?
Is it not working because I did not define how long the list is?
The variable age has type string, so you need to convert it to an integer:
agelist.append(int(age))
The reason for the error is that agelist is a list of strings (inputs from the user) and before you can "add" those inputs you need to convert them either to an integer number or (probably) to a floating number (depending on what kind of average you want: an integer or floating point in Python 2):
sumage = sum(map(int, agelist)) # OR, replace int with float
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Suppose I have a list of strings
['elvis','elo','eels','acdc']
Is there a function that accept this string and returns a unique character for each of the strings? For example, in this case, I expect to get
['e','l','s','a']
Edit: To clarify my meaning.
I want a function that will return an identifier character or string that is based on the input list members. jme answer and bonit's one are a good example.
I think I see your point. There is no built-in for this.
Correct me if I am wrong, but it seems like you want to take the first not already taken character in each string and take one only.
Here is some code to do that
def get_first_not_know(l):
chars = []
for word in l:
for letter in word:
if letter not in chars:
chars.append(letter)
break
return chars
If you don't care about order of letters you take, you can do something quicker using sets.
Assuming BenoƮt Latinier's interpretation of your question is right (which, it looks like it is), then there will be some cases where a unique letter can't be found, and in these cases you might throw an exception:
def unique_chars(words):
taken = set()
uniques = []
for word in words:
for char in word:
if char not in taken:
taken.add(char)
uniques.append(char)
break
else:
raise ValueError("There are no unique letters left!")
return uniques