Caesar substituion -function not returning results - python

I have the following python code which is supposed to use brute force to decrypt secret message. The encryption technique is Ceasarean subsitution i.e. every letter in the alphabet is moved by a certain number of places. My main function is supposed to return the decrypted message with the letters moved by all 26 possible number of places (I hope it makes sense but its basically like ROT13 but we don't know the number. It could be ROT13, ROT5, ROT20 etc.)
The problem is my main function doesn't print out the result from the caesarBreak function.
Thanks in advance!
import sys
def caesarBreak(cipheredMsg):
alphabet = "abcdefghijklmnopqrstuvwxyz "
shift = 1
plainText = ""
for ch in cipheredMsg:
idx = alphabet.find(ch) - shift
plainText = plainText + alphabet[idx]
shift = shift + 1
return plainText
def main():
print("We will now try to break the msg: 'we ovugpzghugpu lylz pungwyvnyhttpungshunahnl'\n\n")
secretmsg = 'we ovugpzghugpu lylz pungwyvnyhttpungshunahnl'
caesarBreak(secretmsg)
main()

Because you didn't ask your main function to print it.
print(caesarBreak(secretmsg))
it did return the result, if you find a place to store it then later you could print it out or do whatever you want with it.
result = caesarBreak(secretmsg)
print(result)

Agree with Yunkai Xiao, you have to use print() to print out your result.
print(#your function here)
Also, there might be other error for you to check just a fyi.

Related

Amateur Text Editor Malfunctioning

My brother and I are creating a simple text editor that changes entries to pig latin using Python. Code below:
our_word = ("cat")
vowels = ("a","e","i","o","u")
#remember I have to compare variables not strings
way = "way"
for i in range(len(our_word)):
for j in range (len(vowels)):
#checking if there is any vowel present
if our_word[i] == vowels[j]:
# if there were to be any vowels our_word[i] wil now be changed with way
#.replace is our function the dot is what notates this in the python library
our_word = our_word.replace(our_word[i], way)
print(our_word)
Right now we're testing the word 'cat' but the program when run returns the following:
/Users/x/PycharmProjects/pythonProject3/venv/bin/python /Users/x/PycharmProjects/pythonProject3/main.py
cwwayyt
Process finished with exit code 0
We're not sure why there is a double 'w' and a double 'y'. It seems the word 'cat' is edited once to 'cwayt' and then a second time to 'cwwayyt'.
Any suggestions are welcome!
The problem arises from the fact that on the next iteration of for loop after doing the substitution, you are looking at the next position, which is part of the way that you just substituted into place. Instead, you need to skip past this. You would also experience another problem, that it only loops up to the original length, rather than the new increased length. You are probably better in this situation to use a while loop with an index variable that you can manipulate to point to the correct place as needed. For example:
our_word = "cat"
vowels = "aeiou"
way = "way"
i = 0
while i < len(our_word):
if our_word[i] in vowels:
our_word = our_word[:i] + way + our_word[i + 1:]
i += len(way) # <=== if you made a substitution, skip over the bit
# that you just substituted in place
else:
i += 1 # <=== if you didn't make any substitution
# just go to the next position next time
print(our_word)

My function is too long. In order to pass class I need < 18 lines

So I am a total beginner yet this is 100% my code and I am proud of it. Now mind you I need a little cleaning up, however it does what I want it too. My issue is this: In order to turn this in for credit, one of the things is that procedures(functions) should not contain more than 18 lines. My function gameCont() has many more. Would anyone have suggestions on how I could shorten it up? Additionally I am obviously challenged when it comes to function parameters so any help is appreciated. Please be gentle as I am BRAND NEW! :)
game1 = "When dealing with SCUBA diving there are many dangers to consider. The very first one is _1_. \
I mean if you take water into your lungs, you are NOT SCUBA diving. Another is rising to the surface too quickly which could \
result in the _2_. Now this is a funny name, as I am sure when it happens, you dont feel 'bendy'. Let's also consider Nitrogen Narcosis.\
If you dont know what that is, well when you are very deep and your body is absorbing more nitrogen than it is used to, you can get \
feeling kinda _3_ feeling as though you just drank not one, but _4_ martinis"
game1_answers = ["drowning", "bends", "drunk", "2"]
game2 = "When you first learn to dive you are taught to do dives within a no DECOmpression limit(NDL). \n This means you do not want to \
stay that deep too long or you will rack up _1_. \n If you DO stay longer than what the NDL allows, you will have an obligation to \
take your time getting to the surface allowing that _2_ gas to leave your body. If you were taking IN gas you may call it \
in-gassing, but when you are decompressing, it may be called _3_-gassing. You are taught also, how to read _4_"
game2_answers = ["deco", "nitrogen", "off", "tables"]
game3 = "Equipment used by cold water divers such as myself are as such. On my head I would wear a _1_. To help regulate the breathing\
pressure from my SCUBA tank I would use a _2_. To help me propel through the water I would place_3_ on my feet. Considering \
we cannot see underwater I need to be wearing a _4_ on my face. Diving in the tropic, many people would use wetsuits, however it's\
very cold where I dive so we wear _5_ suits."
game3_answers = ["hood", "regulator", "fins", "mask", "dry"]
def howManyTries():
gameTries = raw_input("Thanks for giving my quiz a try, how many attempts do you want? ")
return int(gameTries)
def game_choice(): #this function is used to determin which difficulty the user wants and returns the proper game and answer list
user_input = raw_input("Greetings. This is my Udacity project for fill in the blanks. Which one of my options would you like?\
easy, hard, or hardest? Please take note of capitalization ")# this will define the user_input variable to raw input placed in by user
print ("\n" * 20)# just something to clean up the screen
print "Decided to choose " + user_input + '?' " Well " + user_input + " it is"# this confirms to the user which difficulty they chose.
print ""
print ""
if user_input == "easy": #easy returns game1 and game1 answers
return game1, game1_answers
elif user_input == "hard": # hard returns game2 and game2 answers
return game2, game2_answers
elif user_input == "hardest": #hardest returns game3 and game 3 answers
return game3, game3_answers
else:
print "It seems that " + user_input + " is not a valid response" #in case the user doesnt choose or spell choice correctly
def gameCont():
blanks = 1 #this assings blank to 1 which will tell the user which blank they are guessing in below prompt
attempts = howManyTries() #this calls the howManyTries function for a user choice integer
quiz, answers = game_choice() #this returns 2 values (game# and game# answers)
while attempts > 0: #while attempts (called from function) is greater than 0 we will loop this
print quiz #prints the chosen quiz for user updated each time the loop runs with correct answer
print("\n" * 10) #clears some more screen to loook better for the user
guess = raw_input("Reading the above paragraph, What would your guess be for _" + str(blanks) + "_") #asks for guess for current blank which always starts at 1
print("\n" * 10) #clears some more screen to loook better for the user
if guess == answers[blanks - 1]: #because indexing count starts at zero, and blanks start at 1 this will check if answer is equal to blanks - 1
print "As you can see your correct choice has replaced the variable, great job!!"#this will print if the guess is correct
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz
break
elif guess != answers[blanks -1]: #if the answer does not match the list index
attempts = attempts - 1 #then we will subtract 1 from the attempts
print ("\n" * 10)
print "Oops that is not correct, there should be hints in the paragraph" # lets user know they were wrong
print "You have " + str(attempts) + " attempts left." # lets the user know how many attempts they have left
print ""
if attempts < 1:
print "Well it looks like you are out of choices, Try again?"
break
print "Thanks for playing"
gameCont()
All of the printing that you're doing could be done in a separate function
def game_print(newlines_before, text, newlines_after)
print ("\n" * newlines_before + text + "\n" * newlines_after)
Two suggestions:
Delegate tasks that are accomplished by your function to smaller functions. So, for example, if you had a function that needed perform task A and performing that task could be divided into tasks B, C, and D, then create helper functions and call them inside of the function that does task A.
You have long strings, maybe store them somewhere else? Create a class just for constant strings of related functions and access that when you need a particular string. It'll make it less likely that you'll make a mistake when you need to use that string in multiple locations.
class Constants:
str1 = "..."
str2 = "..."
print(Constants.str1)
you can call a function from inside another function. inside an if statement you could call a small new function that just prints some stuff. this should make it easy to get the function size down.
something like this should work:
def correct(quiz, blanks):
print "As you can see your correct choice has replaced the variable, great job!!"
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz`
remember that you still want to break after calling that function in order to exit your loop.

Print function returns two values

I have a created a function to print out the statistics of a tokenized text:
def print_statistics(text):
print("\nThe total number of tokens is " +str(number_of_tokens(ny))+".")
return ???
This function gives me two outputs (the second is "none"). But I want the function to give me the print output. Any idea how I can do this?
The function could return the string to print:
def get_statistics_string(text):
return "\nThe total number of tokens is " + str(number_of_tokens(ny)) + "."
Or print the statistics:
def print_statistics(text):
print("\nThe total number of tokens is " + str(number_of_tokens(ny)) + ".")
# note that it will still return None)
It is usually a good idea to decide that a function will either do something, or return something, not both.
If you want the function to print the required output, then do the following:
def print_statistics(text):
print("\nThe total number of tokens is " +str(number_of_tokens(ny))+".")
return
Else if you want your function to return the required output, do the following:
def print_statistics(text):
return "\nThe total number of tokens is " +str(number_of_tokens(ny))+"."
This function gives me two outputs (the second is "none").
You are executing the function in your Python shell (the builtin one, IPython or whatever). The Python shell always display the result of the last expression you eval'd. Since your function doesn't explicitely returns anything, it (implicitely) returns None, which is your "second output" - the first "output" being the function printing to sys.stdout. If you execute this function from a script, you will only see what the function prints.
What you mean by "I want the function to give me the print output" is quite unclear. If you want your function to print to sys.stdout then it's done, you have nothing to change. If you want it to instead return the formatted string (the one it currently prints) as a Python variable, then replace print('yourstringhere') by return 'yourstringhere'.
As a side note: learn to use proper string formatting, it's much easier to read and maintain:
nb_tokens = number_of_tokens(ny)
msg = "\nThe total number of tokens is {}.".format(nb_tokens)
# then either `print(msg)` or `return msg`
You can just have the function return the output, like:
def print_statistics(text):
return "\nThe total number of tokens is " +str(number_of_tokens(ny))+"."

Please help me better understand this one "except"conditional line

I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)

password strength code help python

so i am writing code in python to tell you your password strength but it is not doing as i say and keeps saying invalid password password unless you use only numbers
hy=1
while(y==1):
passwordentered=str(input("plaese enter your proposed password "))
x=len(passwordentered)
numbers=passwordentered.count ("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
lowerletters=passwordentered.count ("a"and"b"and"c"and"d"and"e"and"f"and"g"and"h"and"i"and"j"and"k"and"l"and"m"and"n"and"o"and"p"and"q"and"r"and"s"and"t"and"u"and"v"and"w"and"x"and"z")
higherletters=passwordentered.count ("A"and"B"and"C"and"D"and"E"and"F"and"G"and"H"and"I"and"J"and"K"and"L"and"M"and"N"and"O"and"P"and"Q"and"R"and"S"and"T"and"U"and"V"and"W"and"X"and"Z")
if(numbers>0 and lowerletters==0 and higherletters==0):
david=9
elif(lowerletters>0 and numbers==0 and higherletters==0):
david=9
elif(higherletters>0 and numbers==0 and lowerletters==0):
david=9
elif(higherletters>0 and numbers>0 and lowerletters==0):
david=8
elif(higherletters>0 and lowerletters>0 and numbers==0):
david=8
elif(numbers>0 and lowerletters>0 and higherletters==0):
david=8
elif(numbers>0 and lowerletters>0 and higherletters>0):
david=7
elif(x>12 or x<6):
david=10
elif(lowerletters==0 and numbers==0 and higherletters==0):
david=10
if(david==10):
print("the password you entered was invalid\
why not try again.")
y=1
elif(david==9):
print("the password you entered is very weak,try to include numbers, lower case letters and upper case letters. why not have another go.")
y=1
elif(david==8):
print("your password is good but it could be better try to include numbers, lower case letters and upper case letters. why not have another go.")
y=1
elif(david==7):
print("your password is really good. thank you for using this program")
y=0
any help would be appriciated
First of all, Python is a very forgiving language, you can get away with a lot of stuff that you can't do in other languages, HOWEVER:
numbers=passwordentered.count("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
Will not work. Python will evaluate everything within the brackets as a boolean expression and this line of code essentially boils down to:
numbers=passwordentered.count("9")
The same goes for the other checks as well. To get what you actually wanted from this, you should use a loop of some sort. You can use something like this:
numbers = sum( ch.isdigit() for ch in passwordentered )
This will give you a count of how many digits are found within the password string. You can modify this to count the number of lowercase and uppercase letters too.
Finally, you should try to clean up your if statements, you could break them down a bit more neatly and make this more readable.
Those count functions won't work if written like that.
Try to replace this:
numbers=passwordentered.count ("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
lowerletters=passwordentered.count ("a"and"b"and"c"and"d"and"e"and"f"and"g"and"h"and"i"and"j"and"k"and"l"and"m"and"n"and"o"and"p"and"q"and"r"and"s"and"t"and"u"and"v"and"w"and"x"and"z")
higherletters=passwordentered.count ("A"and"B"and"C"and"D"and"E"and"F"and"G"and"H"and"I"and"J"and"K"and"L"and"M"and"N"and"O"and"P"and"Q"and"R"and"S"and"T"and"U"and"V"and"W"and"X"and"Z")
with the following:
numbers = sum(typ in "0123456789" for typ in passwordentered)
lowerletters = sum(typ in "abcdefghijklmnopqrstuvwxyz" for typ in passwordentered)
higherletters = sum(typ in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for typ in passwordentered)
or the following for a verbose approach:
numberlist = "0123456789"
Lletterlist = "abcdefghijklmnopqrstuvwxyz"
Hletterlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers=0
lowerletters=0
higherletters=0
for f in xrange(0, x):
if numberlist.find(passwordentered[f]) != -1:
numbers = numbers+1
if Lletterlist.find(passwordentered[f]) != -1:
lowerletters = lowerletters+1
if Hletterlist.find(passwordentered[f]) != -1:
higherletters = higherletters+1

Categories

Resources