Python <function at 0x> output [duplicate] - python

This question already has answers here:
"Function ________ at 0x01D57aF0" return in python
(2 answers)
Closed 6 years ago.
I wrote a new function and when I execute it, I get an error:
<function read_grades at 0x000001F69E0FC8C8>
Ok so here is my code:
def add(x, y):
z = x / y * 100
return z
def calc_grade(perc):
if perc < 50:
return "1"
if perc < 60:
return "2"
if perc < 75:
return "3"
if perc < 90:
return "4"
if perc >= 90:
return "5"
def calc_command():
num1 = input("Input your points: ")
num2 = input("Input maximum points: ")
num3 = add(float(num1), float(num2))
grade = calc_grade(num3)
print("This is your result:", str(num3) + "%")
print("Your grade:", grade)
save = open("grades.txt", "r")
read_grades = save.read()
save = open("grades.txt", "w")
save.write(read_grades + grade)
save.close()
def read_grades():
save = open("grades.txt", "r")
read_grades = save.read()
grades = read_grades.split()
save.close()
return grades
while True:
command = input("Input your command: ")
if command == "CALC":
calc_command()
elif command == "EXIT":
break
elif command == "GRADES":
print(read_grades)
elif command == "HELP":
print("These are the commands:\nCALC - Calculates your grade and writes in the file.\nEXIT - Exits the program.\nGRADES - Reads your previous grades.\nHELP - This command. It helps you.")
else:
print("You inputed an invalid command. Type HELP for help.")
This error happens when I execute the read_grades() function or the GRADES command.
For those who marked this question: I did some searching and I didn't find that post and now that i read it i dont understand the answer

That's not a runtime error, you printed a function
print(read_grades)
Try calling it instead
read_grades()
And you override your function here
read_grades = save.read()
So, advice is to not use variable names that conflict with your function names

Related

Why am I not breaking out of a try loop with a break statement?

My code for now works as desired where the user can input a level 1-3 depending on how hard they would like it to be (1-3 being the amount of digits the numbers will have in the math equation), and then must solve math equations. Those math equations will output EEE if the answer is incorrect and everything works as planned if you correctly answer the question as it exits the function and adds one total_correct_answers variable at the bottom, then will prompt you with another equation. However, if you input an incorrect answer and then a correct answer, you will just be prompted with the same question over and over again without the try loop being truly broken out of and total_correct_answers not being incremented positively by 1. The incrementation block of code is at lines 61-65, and the equation code is lines 30-49.
import random
def main():
ten_questions()
def get_level():
while True:
try:
level_input = int(input("Level: "))
if level_input in [1,2,3]:
return level_input
except:
pass
def integer_generator(level):
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10, 99)
y = random.randint(10, 99)
else:
x = random.randint(100, 999)
y = random.randint(100, 999)
return x, y
def question_generator(x, y):
real_answer = x + y
wrong_counter = 0
while True:
try:
answer_given = input(str(x) + " + " + str(y) + " = ")
if int(answer_given) == real_answer:
if wrong_counter == 0:
return True
elif int(answer_given) == real_answer and wrong_counter != 0:
break
else:
while wrong_counter < 2:
print("EEE")
wrong_counter +=1
break
else:
print(str(x) + " + " + str(y) + " = " + str(real_answer))
print("False, that was last attempt")
break
except:
print("EEE")
pass
def ten_questions():
num_of_questions = 0
total_correct_answers = 1
my_level = get_level()
correct_answers = question_generator(*integer_generator(my_level))
while num_of_questions <= 8:
question_generator(*integer_generator(my_level))
num_of_questions +=1
if correct_answers == True:
total_correct_answers +=1
print("Score: " + str(total_correct_answers))
if __name__ == "__main__":
main()
Because of your line 36:
if int(answer_given) == real_answer: happens when someone answers correctly, wether they are right or wrong. So it enters the if, and then faces if wrong_counter == 0: which discards wrong answers. So just replace those two lines with if int(answer_given) == real_answer and wrong_counter == 0: and you are good to go.

Script stops executing once it encounters def line

So, I had 2 scripts, a Vigenere cipher and a Caesar cipher, however, when I decided to merge them into a "mainproject" file by using "import" to import the script after the wanted answer from the user is sent on the Terminal page, when I've done the code and decided to execute the mainproject, I've got the question whether to choose to use Vigenere or Caesar, once I typed caesar (1) it played the first 2-4 lines and stopped the code once I've encountered the "def" line on both of scripts, if thats the problem, I can't use imports with "def", how can I merge them both into one file that asks which script I would like to use?
Caesar:
import time
import sys
print("Welcome to Caesar Cipher")
time.sleep(3)
print("Choose the corresponding number to Encrypt or Decrypt in Caesar Cipher")
def encryption():
print("Encryption")
print("You have chose ENCRYPTION")
msg = input("Enter message: ")
key = int(input("Enter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32:
encrypted_text += chr(ord(msg[i]))
elif ord(msg[i]) + key > 122:
temp = (ord(msg[i]) + key) - 122
encrypted_text += chr(96+temp)
elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)
else:
encrypted_text += chr(ord(msg[i]) + key)
print("Your Encrypted Message: " + encrypted_text)
def decryption():
print("Decryption")
print("You have chose DECRYPTION")
encrp_msg = input("Enter encrypted Text: ")
decrp_key = int(input("Enter key(0-25): "))
decrypted_text = ""
for i in range(len(encrp_msg)):
if ord(encrp_msg[i]) == 32:
decrypted_text += chr(ord(encrp_msg[i]))
elif ((ord(encrp_msg[i]) - decrp_key) < 97) and ((ord(encrp_msg[i]) - decrp_key) > 90):
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
elif (ord(encrp_msg[i]) - decrp_key) < 65:
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
else:
decrypted_text += chr(ord(encrp_msg[i]) - decrp_key)
print("Text has been Decrypted: " + decrypted_text)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
Vigenere:
import time
print("Welcome to Vigenere Cipher")
time.sleep(2)
print("Choose the corresponding number to Encrypt or Decrypt in Vigenere Cipher")
time.sleep(2.5)
def msg_and_key():
msg = input("Enter message: ").upper()
key = input("Enter key: ").upper()
key_map = ""
j=0
for i in range(len(msg)):
if ord(msg[i]) == 32:
key_map += " "
else:
if j < len(key):
key_map += key[j]
j += 1
else:
j = 0
key_map += key[j]
j += 1
return msg, key_map
def create_vigenere_table():
table = []
for i in range(26):
table.append([])
for row in range(26):
for column in range(26):
if (row + 65) + column > 90:
table[row].append(chr((row+65) + column - 26))
else:
table[row].append(chr((row+65)+column))
return table
def cipher_encryption(message, mapped_key):
table = create_vigenere_table()
encrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
encrypted_text += " "
else:
row = ord(message[i])-65
column = ord(mapped_key[i]) - 65
encrypted_text += table[row][column]
print("Encrypted Message: {}".format(encrypted_text))
def itr_count(mapped_key, message):
counter = 0
result = ""
for i in range(26):
if mapped_key + i > 90:
result += chr(mapped_key+(i-26))
else:
result += chr(mapped_key+i)
for i in range(len(result)):
if result[i] == chr(message):
break
else:
counter += 1
return counter
def cipher_decryption(message, mapped_key):
table = create_vigenere_table()
decrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
decrypted_text += " "
else:
decrypted_text += chr(65 + itr_count(ord(mapped_key[i]), ord(message[i])))
print("Decrypted Message: {}".format(decrypted_text))
print("Key and Message can only be alphabetic")
time.sleep(1.5)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
print("You have chose ENCRYPTION")
message, mapped_key = msg_and_key()
cipher_encryption(message, mapped_key)
elif choice == 2:
print("You have chose DECRYPTION")
message, mapped_key = msg_and_key()
cipher_decryption(message, mapped_key)
else:
print("Wrong choice")
Any help would be appreciated!
def only defines a function. To actually execute it you need to call it.
It seems the following part should be outside of decryption function body i.e. indented to the left. It:
call be executed directly on the module level
can be a separate function e.g. main that you can call
As main:
def main():
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
And now you can call the main function:
main()
Welcome to Stackoverflow. This answer ended up more as general advice than a specific point solution to your problem, but I hope it's helpful.
One obvious remark is that it would be nice not to have to import the code for the cypher you don't intend to use.
Imports are executable statements, so this is quite practical.
Your code is far from optimally organised. Much of the code on the two files is the same or very similar. This is not unusual for new programmers, as it takes a while to learn how to break problems down and extract the common elements. The real problem is that while it defines lots of functions, none of them actually get called (unless there's more code you haven't included).
I would recommend that you modify your code so that there's a top-level program that collects the key and data and performs the required operations, along with your two
encryption/decryption modules. The encryption and decryption routines shouldn't do any input or output at all, just deal with the data.
Let's assume you have a variable mtype that holds the type of encryption you want to use. The top-level logic could look something like this:
if mtype == "caesar":
from caesar import encrypt, decrypt
elif mtype == "vigniere":
from vigniere import encrypt, decrypt
else:
sys.exit("Unrecognised message type")
If this code succeeds you would then have an encrypt and a decrypt function from the correct module. This means that they have to have the same interface, since your logic must now be written to accommodate either.
The remainder of your logic would look something like this (untested):
operation = input("E(ncrypt) or D(ecrypt)? ")
if operation.upper().startswith("E"):
function = encrypt
elif operation.upper().startswith("D"):
function = decrypt
else:
sys.exit("Unknown operation")
message = input(...)
key = input(...)
output = function(message, key)
This will hopefully make your code clearer by separating out the I/O responsibility
from the encryption and decryption tasks.

TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

I am having trouble with feeding a value into a function, and not having that values type be an int, instead it is a NoneType, which I cannot operate with. Here's the error message I am thrown:
Traceback (most recent call last):
File "NumberGame1.py", line 140, in <module>
main()
File "NumberGame1.py", line 29, in main
result = guessinggame(number)
File "NumberGame1.py", line 92, in guessinggame
if guess - number <= level * 0.1:
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
Here is all of the code:
import random
import timeit
def main():
print "\nWelcome to Ethan's Number Guessing Game!"
print "What would you like to do?: \n1. Play game\n2. View High Scores\n3. View Credits"
menuchoice = input()
## choice is Menu Decision
if menuchoice == 1:
difficulty = input("Pick a difficulty!: \n1: Easy\n2: Medium\n3: Hard\n4: Insane\n5. Out of control!\n6. Custom\n")
leveldif = difcalc(difficulty)
## Exits program if you don't choose a difficulty
global level
level = leveldif[0]
difmod = leveldif[1]
number = numbergenerator(level)
result = guessinggame(number)
totalTime = result[0]
tries = result[1]
scorer(tries, totalTime)
elif menuchoice == 2:
## Figure out how to access high scores
print "This feature is currently under development.\n"
elif menuchoice == 3:
print "\nDeveloped by Ethan Houston"
raw_input()
print "\nDeveloped in Python 2.7.9 using Sublime Text 2"
raw_input()
print "\nThanks for playing :)"
raw_input()
## Simple credits reel. Go me
def difcalc(difficulty):
if difficulty == 1:
leveldif = [10, 1]
elif difficulty == 2:
leveldif = [50, 1.5]
elif difficulty == 3:
leveldif = [100, 2]
elif difficulty == 4:
leveldif = [1000, 10]
elif difficulty == 5:
leveldif = [10000, 20]
elif difficulty == 0:
leveldif = [1, 1]
return leveldif
def guessinggame(number):
tries = 1
## Counter for number of attempts at guessing
guess = input("Guess a number between 1 and " + str(level) + "!: ")
## Takes input from user
while guess > level:
guess = input("Above range!\nMake sure to guess between 1 and " + str(level) + "!: ")
## If the user chooses a number above the range, makes you try again until within range
startTime = timeit.default_timer()
## Starts a timer once first valid number is selected
while guess != number:
## While loop that runs as long as guess isn't correct
if guess > number:
if guess - number <= level * 0.1:
guess = input("Too high, close!: ")
tries += 1
## If difference between guess and answer is less than or equal to 10% of level,
## prints different prompt
else:
guess = input("Too high, guess again: ")
tries += 1
## Normal behavior
elif guess < number:
if guess - number <= level * 0.1:
guess = input("Too low, close!: ")
tries += 1
## If difference between guess and answer is less than or equal to 10% of level,
## prints different prompt
else:
guess = input("Too low, guess again: ")
tries += 1
## Normal behavior
endTime = timeit.default_timer()
## Takes the time after the correct number is chosen
totalTime = endTime - startTime
## Calculates time difference between start and finish
result = [totalTime, tries]
return result
def numbergenerator(level):
global number
number = random.randint(1, level)
def scorer(tries, totalTime):
print "\nCorrect! It took you " + str(round(totalTime, 2)) + " seconds and " \
+ str(tries) + " tries to guess.\n"
## Once user guesses correct number, program tells how many tries it took, and how long
score = 1/(1+(tries * round(totalTime, 2))) * 1000 * difmod
## Calcualtes score, making lower times and fewer tries yield a higher score
## Difmod takes into account the difficulty
## Multiply by 1000 to make number more readable
print "Score: " + str(round(score, 2)) + "\n"
## Printsthe score, rounded to 1 decimal place
main()
When a python function does not explicitly return anything , it returns None . In your case, you have a function -
def numbergenerator(level):
global number
number = random.randint(1, level)
This does not return anything, instead you set a global variable number .
But when you are calling this function in main() , you do -
number = numbergenerator(level)
And here number is not a global variable (Even if it was a global it wouldn't matter) , so after calling numbergenerator() , since it does not return anything, it returns None , which gets set to number variable, and hence number is None, causing the issue you are having.
I believe you do not need to use global variable there, you should just return the number from numbergenerator() function , example -
def numbergenerator(level):
return random.randint(1, level)

Why am i getting a Type error with global variable editing?

I am working on creating an easygui/python calculator math program and i keep getting this error
Traceback (most recent call last):
File "C:\Python27\Scripts\MathHelper.py", line 83, in <module>
MathType()
TypeError: 'str' object is not callable
I can't figure out why it is happening. I believe it is with the global variable I try to call and change but i can't figure out how to stop the error. I know my code is kind of messy right now i am trying to work a proof of concept.
#MathType == what kind of math to compute. IE. Subtraction or addition
#Selection == Yes or no
math = 1
MathType = "Addition"
loop = 1
import easygui
def start():
print("startMessage")
MathType = easygui.msgbox(msg="Hello and welcome to my Math Helper.",
title = "Welcome")
startMessage = "0"
#End of start
#
#
#
def MathType():
global MathType
print("Math Type Gathered")
MathType = easygui.buttonbox("Select the type of Math you would like to compute:",
title = "Math Selection",
choices = ["Addition", "Subtraction", "Shut Down"] )
#End of MathType
#
#
#
def Addition():
num1 = easygui.enterbox(msg = "Please enter the first Number.",
title = "Addition")
#print(num1)
num2 = easygui.enterbox(msg = "Please enter the second number. "+num1+" + ___ = ___",
title = "Addition")
#print(num2)
easygui.msgbox("Here is your equation: "+num1+" + "+num2+" = ___ ",
title = "Equation")
NUM1 = int(num1)
NUM2 = int(num2)
numFinal = (NUM1 + NUM2)
NUM3 = str(numFinal)
easygui.msgbox(msg="Your answer is: "+NUM3+"",
title="Final")
#print(numFinal)
#End of Addition
#
#
def Subtraction():
num1 = easygui.enterbox(msg = "Please enter the first Number.",
title = "Subtraction")
#print(num1)
num2 = easygui.enterbox(msg = "Please enter the second number. "+num1+" - ___ = ___",
title = "Subtraction")
#print(num2)
easygui.msgbox("Here is your equation: "+num1+" - "+num2+" = ___ ",
title = "Equation")
NUM1 = int(num1)
NUM2 = int(num2)
numFinal = (NUM1 - NUM2)
NUM3 = numFinal
easygui.msgbox(msg="Your answer is: "+NUM3+"",
title="Final")
#print(numFinal)
#End of Subtraction
#
#
def MathFinder():
if MathType == "Addition":
print("Addition")
Addition()
elif MathType == "Subtraction":
print("Subtraction")
Subtraction()
elif MathType == "Shut Down":
exit()
start()
while loop == 1:
MathType()
MathFinder()
At line 4 you have MathType = "Addition"
At line 18 you have def MathType():
The error tells you that it can't call a string.
MathType() is actually MathType = "Addition" which is a string and not a function.
Please try to prevent using the same name for your functions, variables etc.
You have two types of 'MathType', one is a string and other is a function.
You have a function and a string variable named MathType.

How to get two variables from the previous function in python? [duplicate]

This question already has answers here:
What's the best way to return multiple values from a function? [duplicate]
(6 answers)
Closed 8 years ago.
I'm very new at python so I'm still learning some things. But I'm doing this code and I need to know how to get the x and y variables from the "getHumanMove" function so that I can use it in the "getPiles" function
def getHumanMove(x,y):
finished = False
while not finished:
x=int(input("Which pile would you like to take from?(1 or 2)"))
y=int(input("How many would you like from pile "+ str(x)+ "? "))
if pile1 and pile2<y:
print("pile " +str(x)+ " does not have that many chips. Try again.")
elif y==0:
print("You must take at least one chip. Try again.")
else:
print("That was a legal move. Thank You.")
finished = True
return x,y
def getPiles(pile1, pile2):
print("Here are the piles: ")
#################################Here is where I need to put the x, y variables
pile1= pile1
pile2= pile2
if temp_x == 1:
pile1= pile1- temp_y
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
elif temp_x == 2:
pile2= pile1- temp_y
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
return pile1, pile2
##############################Main##############################
move= getHumanMove(pile1, pile2)
pile= getPiles(pile1, pile2)
How about in your call to getPiles:
pile = getPiles(pile1, pile2, move)
and then in your getPiles definition:
def getPiles(pile1, pile2, move):
x, y = move
Assuming this is what you mean:
x,y = getHumanMove(pile1, pile2)
pile1, pile2 = getPiles(x, y)
You can use tuple unpacking:
move = getHumanMove(pile1, pile2)
pile = getPiles(*move)
Or get each variable separately, so you can pass them separately too:
move1, move2 = getHumanMove(pile1, pile2)
pile = getPiles(move1, move2)
When a function is returning two values, you can do
value1, value2 = some_function(argument1, argument2, argument3, ...)
to store the two return values in value1 and value2.

Categories

Resources