Creating a Caeser Cipher encryption in Python and Getting Errors [closed] - python

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)

Related

Defining function with parameters (str,n) that the index value "n" removes the character in that position? [closed]

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 last year.
Improve this question
Write a function that will accept two parameters: a string and an integer n. Return a new string
where the character at index n has been removed. If the value of n is invalid, return the original
string.
This function will be called into "main" function
Beginning python coder here and I am not the best at understanding how functions work.
my code --> enter image description here
Here you go...
and your code is not correct.
def removeChar(str, pos):
# str[:pos] gives string from index 0 upto pos (excluding pos)
# str[post+1:] gives string from pos + 1 upto end
return str[:pos] + str[pos+1:]
def main():
print(removeChar("Hello", 2))
main()
To remove any character from a String, we have to create a new string since Strings are immutable in Python (unlike lists).
There are several ways to do so -
Using Slicing - This is the most common approach.
s = 'ABCDE'
i = 2
s = s[:i] + s[i+1:]
# s[:i] gives the characters in the string from index 0 to i-1 (excludes index i)
# s[i+1:] gives the characters in the string from index i+1 to end
print(s) # This will print ABDE
Converting to List - We can convert the string to a mutable list of characters. After removing the character at the specified index, we can convert it back to string.
s = 'ABCDE'
i = 2
l = list(s) # Convert to list
del(list[i]) # Deletes the character at index i from the list
s = "".join(l) # Converts the list back to string
print(s) # This will print ABDE
Now, let's discuss about your code :)
def missingChar (str, n):
str = ""
# str is taken as an argument for the function. If it is initialized to "", the purpose of taking it as an input to the function is not served
index = str
value = n
# The above lines are unnecessary
for index in str: # Since, the value of the index at which the character should be removed is already given, a for loop is not needed
index.pop(value) # pop() is a list method... So, it can't be used with strings
return
# Create the main function that will be used throughout the HW
def main():
missingChar("kitten",1) # The function call is perfect :)
# If you want to print the output of the function 'missingChar', store the return value in a variable, and then print it or directly print it by calling the function inside print()
main()
Considering your approach, the following can be done -
def missingChar (s, n):
l = list(s) # Convert to list
l.pop(n) # Use the pop() list method freely :)
s = "".join(l) # Convert the list to string
return s
def main():
result = missingChar("kitten",1)
print(result)
# OR
# print(missingChar("kitten",1))
main()

Read input and return three strings in reverse order (only 1 string so far) [closed]

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 4 years ago.
Improve this question
def rev(one, two, three):
print("Reverse of the third string is",three[::-1])
# returning concatenation of first two strings
return one+two
def main():
# Taking user input of 3 strings
first = input("Enter first string:")
second = input("Enter second string:")
third = input("Enter third string:")
# calling function, passing three arguments
print("Reverse of third string is",rev(first, second, third))
main()
Assignment
Write a Python function that will accept as input three string values
from a user. The method will return to the user a concatenation of the string values in reverse order. The function is to be called from the main method.
In the main method, prompt the user for the three strings.
If the input of the strings is Hello, World, and Car, then the output should be raCdlroWolleH
Your rev function could contain just one line of code (you should call it in the main function). It is as simple as :
return three[::-1]+two[::-1]+one[::-1]
I think the problem is that you're doing two separated prints, one for the first two words and other to the third word. If what you pretende is to join all of the three words and return that, then all you have to do is
New = one + two + three
return New[::-1]

Python using sum() in a user made list [closed]

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

python find repeated substring in string [closed]

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 6 years ago.
Improve this question
I am looking for a function in Python where you give a string as input where a certain word has been repeated several times until a certain length has reached.
The output would then be that word. The repeated word isn't necessary repeated in its whole and it is also possible that it hasn't been repeated at all.
For example:
"pythonpythonp" => "python"
"hellohello" => "hello"
"appleapl" => "apple"
"spoon" => "spoon"
Can someone give me some hints on how to write this kind of function?
You can do it by repeating the substring a certain number of times and testing if it is equal to the original string.
You'll have to try it for every single possible length of string unless you have that saved as a variable
Here's the code:
def repeats(string):
for x in range(1, len(string)):
substring = string[:x]
if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
print(substring)
return "break"
print(string)
repeats("pythonpytho")
Start by building a prefix array.
Loop through it in reverse and stop the first time you find something that's repeated in your string (that is, it has a str.count()>1.
Now if the same substring exists right next to itself, you can return it as the word you're looking for, however you must take into consideration the 'appleappl' example, where the proposed algorithm would return appl . For that, when you find a substring that exists more than once in your string, you return as a result that substring plus whatever is between its next occurence, namely for 'appleappl' you return 'appl' +'e' = 'apple' . If no such strings are found, you return the whole word since there are no repetitions.
def repeat(s):
prefix_array=[]
for i in range(len(s)):
prefix_array.append(s[:i])
#see what it holds to give you a better picture
print prefix_array
#stop at 1st element to avoid checking for the ' ' char
for i in prefix_array[:1:-1]:
if s.count(i) > 1 :
#find where the next repetition starts
offset = s[len(i):].find(i)
return s[:len(i)+offset]
break
return s
print repeat(s)

How do I make a cipher and encrypt the text? [closed]

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.

Categories