Python Encryption - python

So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error.
TypeError: 'int' object is not iterable
Heres the code, i hope you guys can help me, much appreciated
plainNum = input("enter a number to encode ")
codedNum = ' '
Key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum

Use raw_input if you expect a string:
plainNum = raw_input("enter a number to encode ")
input() interprets the input as if it is Python code; enter 5 and it'll return an integer, enter 'some text' (with quotes) and it'll return a string. raw_input() on the other hand returns the entered input uninterpreted.

Most dirty fix of all, simply change
for i in plainNum:
with
for i in str(plainNum):

This is working but not if I use a decimal and it doesn't behave if I enter words or spaces. Consider checking first that the entry is a number with something like:
try:
float(element)
except ValueError:
print "Not a float"
after stripping any whitespace with something like:
plainNum = plainNum.strip()
But this outputs the encoded digits of your entered integer:
plainNum = raw_input("enter a number to encode ")
codedNum = ' '
key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Ask the user for the number with raw_input. This makes the input a string which you can iterate over with:
for char in plainNum:
Yes, this is a now a char in a string and so you've used the int(i) function.

you maybe also wanna change key to Key to reflect what variable is declared
and also make codeNum initially equal to '' instead of ' ' (no space vs space)
just book keeping stuff

Related

How do I make an input() detect if the user input is something other than a string?

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported character.
Here's the code I have so far:
while True:
name = input('What is your name? ')
if name is str:
print('Hi,%s. ' % name)
if name != str:
print('That is not a valid character!')
Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.
isalpha() returns True for strings with only alphabets.
isalnum() returns True for strings with only alphabets and numbers and nothing else.
isdigit() returns True for strings with only numbers.
Also your if-else statement is off
name = input('What is your name? ')
if name.isalpha():
print('Hi,%s. ' % name)
else:
print('That is not a valid character!')
When you do
name = input('What is your name? ')
you get a string called name, so checking it it is a string won't work.
What you can check is if it's an alphabetical character, using isalpha:
if name.isalpha():
# as you were
There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

Program that reads strings typed by user until nothing entered then prints strings in reverse order

I am trying to write a program that allows a user to continue to type out strings until an empty string is entered. Then the program sorts through the strings and prints the string in depending order ( lexicographically ).
The string output should look something like this.
enter a string: the tree is nice and brown
output: tree the nice is brown and
I have tried to implement this code for myself however I have ran into a problem where it prints the code multiple times. see bellow code.
Enter string: the tree is nice and brown
Output: tree Output: the Output: nice Output: is Output: brown Output: and Enter string:
how can I fix my code to remove the Output: that continues to be printed after each word in the string. And also make the final enter new string print on a new line.
See bellow my final code.
s=input("Enter string: ")
while s!="":
a=s.lower()
b=a.split()
b.sort(reverse=True)
for i in b:
answer=""
answer+=i
print("Output: ", answer, end=" ")
s=input("Enter string: ")
while s := input('Enter string: '):
a=s.lower()
b=a.split()
b.sort(reverse=True)
output = ("OUTPUT: \n" + " ".join(b))
print(output)
You could break this down to just two lines. Not necessarily very instructive but just for fun:
while s := input('Enter string: '):
print('Output:\n'+' '.join(sorted(s.lower().split(), reverse=True)))
You should probably collect all data first and the perform the operations you want on said data.
Left some comments on your code:
s=input("Enter string: ")
while s!="":
a=s.lower()
b=a.split()
b.sort(reverse=True)
for i in b: #Every time you input something new you also enter this for-loop
answer="" #This resets the variable every for-loop
answer+=i #This tries to concatenate a string i to the variable answer but since you reset the variable every loop you will never get anything else than i here
print("Output: ", answer, end=" ") #Does this run?
s=input("Enter string: ")
"Correct" code:
s=input("Enter string: ")
while s!="":
# All the input data is split and all characters made lowercase and appended to wordlist variable
a=s.lower()
b=a.split()
wordlist=[]
for i in b:
wordlist.append(i)
# After splitting and making all characters lowercase sort the new list.
wordlist.sort(reverse=True)
# Concatenate the list into a new string
answer=""
for i in wordlist:
answer+=" "+i
#Print
print("Output:"+answer+"\n")
s=input("Enter string: ")

Conversion Program

I have a program where I need to prompt the user for an input of a word and a key. Next, the program should remove all the spaces, punctuation and all numbers from the word and convert all the letters into uppercase. Once that is done I need the program to replace all the characters of the word with the key. So if the word is a library, and the key is moose, the program should print out moosemo. I know that this part includes something like append.key(len plaintext) something of this fashion, but I'm not exactly sure how. I don't have a lot of the code done because I am pretty lost. Here is what I have so far:
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
print(phrase.upper()) #converts all characters from phrase to uppercase
If anyone knows what to do or what to change, please let me know. Please show the change in code with your response. Thanks in advance
I used answers from here and here to make compose this.
Here is one way you might do it, using the string class to get rid of punctuation and numbers.
import string
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
#replace - gets rid of spaces
#first translate - gets rid of punctuation
#second translate - gets rid of digits
#upper - capitalizes.
phrase = phrase.replace(" ", "")\
.translate(str.maketrans('', '', string.punctuation))\
.translate(str.maketrans('','',string.digits))\
.upper()
times_to_repeat = len(phrase)//len(encryptionkey)
leftover_length = len(phrase)%len(encryptionkey)
#multiply string by how many times longer it is than the encryption, then add remaining length.
#in python you can do 'string'*2 to get 'stringstring'
final_phrase = encryptionkey*times_to_repeat+encryptionkey[:leftover_length]
print(final_phrase)
Output:
# Only keep the alphabet characters
phrase = ''.join(c for c in phrase if c.isalpha())
# Add the encryption key at least 1 more times than divisible (to count for remainder)
# and slice the output to the length needed
phrase = (encryptionkey * (1 + len(phrase) // len(encryptionkey)) [:len(phrase)]

Python - Validation to ensure input only contains characters A-Z

I'm creating a program in Python 3.x where it asks the user for their first name and then last name and stores these in variables which are then concatenated into one variable:
firstName = input("What's your first name? ")
lastName = input("What's your first name? ")
name = firstName + " " + lastName
I tried:
while True:
try:
firstName = input("What's your first name? ")
lastName = input("What's your first name? ")
name = firstName + " " + lastName
break
except ValueError:
print("That's invalid, please try again.")
which ensures that a string is inputted, but inputting 'bob38', '74' or '][;p/' all count as string values, so these would be accepted, which is not what I want to happen.
I want valid input to only contain the letters A-Z/a-z (both uppercase and lowercase), and if the input contains anything else, an error message is outputted (e.g. 'That's invalid, try again.') and the user is asked the question again. How would I do this?
What you want to do is actually check if your string is not isalpha() and output an error and continue your loop until you get a valid entry.
So, to give you an idea, here is a simple example:
while True:
name = input("input name")
if name.isalpha():
break
print("Please enter characters A-Z only")
print(name)
Note, that as mentioned in the comments to this question, this is limited to only names that contain letters. There are several valid names that will contain ' and - that should probably be considered when wanting to validate names.
There is another solution. It's not as efficient as using re or isalpha but allows you to easily customize the characters you allow:
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# Just insert other characters into that string if you want to accept anything else.
while True:
firstName = input("What's your first name? ")
if all(char in valid_characters for char in firstName):
break
print("That's invalid, please try again.")
The all checks if all characters from firstName are contained in the valid_characters string and returns False if any of them is not in it.
So to add whitespace and minus - you can alter it slightly:
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -'
# whitespace is here ------------------------------^
assert all('a'<=letter<='z' or 'A'<= letter <= 'Z' for letter in name)
This will throw an error if name contains a non alphabet letter.
You can use a simple regular expression for this -
import re
is_valid_name = r'[a-zA-Z]+'
if bool(re.match(firstName, is_valid_name)) and bool(re.match(lastName, is_valid_name)):
name = firstName + lastName
else:
print('thats invalid')

Editing user-input string values in Python

I was wondering how to edit a string value input by user such that the first character of the string (and every occurrence of that same character) are replaced by another character (ie !)
IE if the user enters Pineapples they get !ineapples
but if they enter pineapples they get !inea!!les
Any help is very much appreciated
Here is what I Have so far
string1 = input("Enter a string: ")
svalue1 = string1[0]
string2 = string1.replace('string1[0]' , '!')
I'm guessing one of my issues is that I'm not using the replace function properly
You can try this function:
def RepFirstWith(s,c):
return s.replace(s[0],c)
For example:
print RepFirstWith('pineapples','!') # !iena!!les
Something like this:
>>> s = raw_input("Please enter a string: ")
Please enter a string: pineapples
>>> print s.replace(s[0], '!')
!inea!!les
All done and tested in Python shell
The problem was is that you wrote string1[0] which literally makes a string that is 'string1[0]' instead of computing that value

Categories

Resources