Python Program beeps when run? - python

I am running into a problem. The following program beeps when it runs, which I did not program into it. I am running Windows 7 on a laptop and was wondering why this happens.
My code is basically a simple little encryptor. It is not yet capable of handling things outside of the ASCII range but that is outside the scope of this question.
Ultimately, I would like to know, why does it beep?
(Note: this is from a class which is why self is included.)
def encrypt(self,message,private_key):
import random
self.message=str(message)
self.private_key=int(private_key)
self.public_key=""
self.final_message=""
self.errors=[]
for letter in str(self.message):
y=random.randrange(0,ord(letter))
a=y+self.private_key
x=ord(str(letter))^a
if x in range(0,256):
z=chr(x)
self.final_message=self.final_message+str(z)
self.public_key=self.public_key+str(chr(y))
else:
char="Letter: "+str(letter)+", ASCII value unabled to be processed: "+str(x)+" using keys: "+"Private key: "+str(self.private_key)+" Random Key: "+str(y)
self.errors.append(char)
print "Message: "+str(self.message)
print
print "Length of Message: "+"["+str(len(str(self.message)))+"]"
print
print "Final Message: "+"["+str(self.final_message)+"] "+"length of message: "+str(len(str(self.final_message)))
print
print "Public Key: "+"["+str(self.public_key)+"] "+"length of key: "+str(len(str(self.public_key)))
print
print "Private Key:"+"["+str(self.private_key)+"]"
if len(self.errors)!=0:
print "errors: "
print
for error in self.errors:
print error
print

http://en.wikipedia.org/wiki/Bell_character
ascii 7 is your culprit. consider encoding into base64 or some other printable subset.

If you are printing ASCII code 7 at any time, you may make your console/terminal beep.
Try it:
>>> print chr(7)

Related

Value of string to be a trigger

I'm trying to get my code to get a string of data from a sensor, and then do something when it reads a specific value.
The following code is how I'm receiving the data now (this is just a test) the function is called earlier in the code at the time where I want it to be called.
def gettemperature(self)
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
This code works, and returns the temperature value rounded to the terminal, but how could I, instead of printing the value to the terminal, make it so when that string of rounded value is say, 200 degrees, then it prints the temperature value? instead of printing it every 2 seconds (the frequency of the data being received, as per another part of the code)
Using something like
if temp = 200
then print(blahblah)
in short, the above code is what I'm trying to do. If the temp equals a certain value, then something else will happen.
That last code doesn't work. I'm pretty new to coding, so I'm assuming I'm either not going about this the right way, or the syntax of how I'm going about trying to get that value to do something isn't correct (obviously)
Thanks for any help! I'm surprised I got this far, haha.
It would be better if your function gettemperature would return something and then print the result in the condition:
def gettemperature()
temp = board.temp_sensor
return temp
temp = gettemperature()
if temp == 200:
print("Temperature is " + str(round(temp)) + " degrees.")
Before using stackoverflow, I'd recommend learning all this stuff from some basic course, as you'll get to learn the stuff yourself rather then get the answer from someone else.
Try learning conditional statements.
what you want is, to put a conditional statement which triggers if temperature is greater than 200.
If the temp is always a number in string data type, you can use the below code.
def gettemperature(self):
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
temp=int(temp) #typecasting string datatype to integer
if temp == 200:
print("Temperature is high")

Trying to get my python program to run but I keep getting a variable assignment error. Any ideas as to what I am doing wrong?

def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.

How to exit from try block and show exception message?

This Python code block generates an error at student [3]. How to immediately show the error message in except rather than printing the previous values?
try:
student = ['bob','rob','mob']
print (student )
print (student [0])
print (student [1])
print (student [2])
print (student [3])
except:
print("error")
Current Output:
['bob','rob','mob']
bob
rob
mob
error
Process finished with exit code 0
How could I avoid the printing before the error is raised?
The code will run until some error happens and the error won't happen until print (student [3]). Therefore previous commands will run and there is now way back.
A simple solution is that you first assign these values to some variables and then print them:
try:
student = ['bob','rob','mob']
a=student [0]
b=student [1]
c=student [2]
d=student [3]
print (a)
print (b)
print (c)
print (d)
except:
print("error")
So the error happens in d=student [3] before the print commands are executed.
You can't do that AFAIK.
Python doesn't know that it is going to encounter an IndexOutOfBounds (IndexError) exception, so it will execute until getting to the exception.
A way to remedy the situation would be to use a for loop and only iterate on that. It should avoid the exception altogether:
try:
student = ['bob','rob','mob']
for stud in student:
print stud
except:
print("error") # less likely to be reached :)

Why does printing a packed int freak out OS X?

When printing a binary packed nonce in the terminal, it generates a bunch of alerts.
The code of the program is:
from struct import pack, unpack
import hashlib
import sys
print "Input the message you want to work on:"
message = raw_input()
orig_hash = hashlib.sha512(message).digest()
trialValue = 99999999999999999999
target = 4103215547750
nonce = 0
while trialValue > target:
nonce += 1
packed_nonce = pack('>Q', nonce)
print packed_nonce
trialValue, = unpack('>Q',hashlib.sha512(packed_nonce + orig_hash).digest()[0:8])
print nonce
print trialValue
This isn't a big deal, but does anyone know why this happens?
Probably because some of the data you're printing contains a BEL (0x07) character, which causes the terminal to beep.
Don't print control characters unless you want the terminal to do weird things.

Unknown reason for code executing the way it does in python

I am a beginner programmer, using python on Mac.
I created a function as a part of a game which receives the player's input for the main character's name.
The code is:
import time
def newGameStep2():
print ' ****************************************** '
print '\nStep2\t\t\t\tCharacter Name'
print '\nChoose a name for your character. This cannot\n be changed during the game. Note that there\n are limitations upon the name.'
print '\nLimitations:\n\tYou cannot use:\n\tCommander\n\tLieutenant\n\tMajor\n\t\tas these are reserved.\n All unusual capitalisations will be removed.\n There is a two-word-limit on names.'
newStep2Choice = raw_input('>>>')
newStep2Choice = newStep2Choice.lower()
if 'commander' in newStep2Choice or 'lieutenant' in newStep2Choice or 'major' in newStep2Choice:
print 'You cannot use the terms \'commander\', \'lieutenant\' or \'major\' in the name. They are reserved.\n'
print
time.sleep(2)
newGameStep2()
else:
newStep2Choice = newStep2Choice.split(' ')
newStep2Choice = [newStep2Choice[0].capitalize(), newStep2Choice[1].capitalize()]
newStep2Choice = ' ' .join(newStep2Choice)
return newStep2Choice
myVar = newGameStep2()
print myVar
When I was testing, I inputted 'major a', and when it asked me to input another name, i inputted 'a b'.
However, when it returned the output of the function, it returns 'major a'. I went through this with a debugger, yet I still can't seem to find where the problem occurred.
Thanks for any help,
Jasper
Your recursive call to newGameStep2() isn't returning, so when the second call finishes, control flow continues in the first call after the if/else block, and return newStep2Choice returns the first read value. You need to change the recursive call to:
return newGameStep2()

Categories