Python tkinter can't use Entry.get() fucntion - python

So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")

Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()

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.

I am getting an error if acc[0] == var[0]: TypeError: 'NoneType' object is not subscriptabl. how do I fix this?

I am writing a car rental program on python.
In this function I am trying to modify car details which are added in the details.txt file but I am getting an error "if acc[0] == var[0]:TypeError:'NoneType' object is not subscriptable"
how do I fix this error ?
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
count += 1
mod_file.close()
if exist != True:
print("!!! Can NOT Find The Data !!!")
elif exist == True:
s_list = []
mod_file = open("details.txt", "r")
for s in mod_file:
s = s.strip()
s_list.append(s)
mod_file.close
choice = "Y"
while choice == "Y":
print("\n===============================")
print("---------- MODIFY Cars ----------")
print("---------------------------------")
print("Select the details you wish to modify")
print("1. Type")
print("2. Manufactured Year")
print("3. details of the car")
print("4. car code")
print("5. Daily price rate ( USD $ )")
print("6. back")
while True:
try:
c = int(input("please select a number (1 - 5): "))
modify = ["Type", "Manufactured Year", "details of the car", "car code", "Daily price rate ( USD $ )"]
if c > 0 and c < 6:
new = input("\nType the New " + modify[c - 1] + ":")
var[c - 1] = new
temp = ",".join(var)
s_list[count] = temp
mod_file = open("details.txt", "w")
mod_file.write("")
mod_file.close()
count_file = 0
for s in range(len(s_list)):
mod_file = open("details.txt", "r")
for counting in mod_file:
count_file += 1
mod_file.close()
mod_file = open("details.txt", "a")
if count_file == 0:
mod_file.write(s_list[s])
else:
mod_file.write("\n")
mod_file.write(s_list[s])
mod_file.close()
print("\nDetails UPDATED")
be_exit = input("\nDo you want to modify again? (Y/N): ").upper()
if be_exit == "y":
choice = "y"
else:
modifying(acc)
elif c == 6:
modifying(acc)
else:
print("\n!!! Incorrect Input !!!\n")
continue
except:
print("\n!! NOT a Number !!!\n")
continue
modifying()
You have to do
acc = some_value
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
In your example you haven't defined the variable acc. Using global just say that the variable is a global variable, but you're not assigning a value to it

Does anyone know how to combine these functions?

I want to combine the functions def clicked and def clicked2 because they are the same but I don't know how to do that. I haven't tried yet but I can't think of a way to do it.
from tkinter import *
import random
window = Tk()
x = round(random.random()) + 1
m = 7
window.title("NIM-7 spel")
window.geometry('350x200')
lbl = Label(window, text="Player " + str(x) + " next")
lbl2 = Label(window, text="Their are " + str(m) + " coins left")
lbl.grid(column=0, row=1)
lbl2.grid(column=1, row=0)
def clicked():
global x
global m
m -= 1
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
def clicked2():
global x
global m
m -= 2
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
btn1 = Button(window, text="Take 1 coin", command=clicked)
btn2 = Button(window, text="Take 2 coins", command=clicked2)
btn1.grid(column=1, row=1)
btn2.grid(column=2, row=1)
window.mainloop()
Does anyone know how to do it?
You can add arguments to tkinter buttons if you use a lambda function.
Some identical questions were asked already:
Functions in Tkinter
How to call a function with arguments in "Button" function from "tkinter" python package?
def clicked(value):
global x
global m
m -= value
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
btn1 = Button(window, text="Take 1 coin", command = lambda:clicked(1))
btn2 = Button(window, text="Take 2 coins", command = lambda:clicked(2))
Pass in how much you want to decrement m as a parameter. So:
def clicked(decrement):
global x
global m
m -= decrement
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
Then call it like this: clicked(1) and clicked(2).
Because you are passing it as a parameter to Button, you can create dummy functions:
def clicked1():
clicked(1)
and similar for clicked2.

syntaxerror: 'return' outside function in python code

There is something wrong with my python code. I am a beginner in python.
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", amount.length(), amount)
pp_str = "00020101021129370016A000000677010111"
+ pp_acc_id
+ "5303764"
+ pp_amount
+ "5802TH"
+ "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
Error says it's SyntaxError: 'return' outside function. What's the problem with this code. By the way i convert the code from java to python. Is that everything okey in my code? I edit my code here but still there are some error
You need to properly indent your code. From your question I'm guessing this would resolve your issue:
import crc16
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", amount.length(), amount)
pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
Python is what is called "whitespace-sensitive": it matters how stuff is indented. For example, it expects the contents inside an if-clause to be indented below that statement:
if True or False:
execute_this_function()
This will not work:
if True or False:
execute_this_function()
The same applies to return statements: they should be inside the function they apply to, i.e. that you are returning from:
def my_method():
return True
Again, this will not work and raise the error you are getting:
def my_method():
return True
Thus, the solution is to make sure your returns are indented correctly. Of course, the same applies to the rest of the code!
Edit Based on the modification of your OP, this is the indentation you require; I also fixed the .length() you copied over from Java, it seems:
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", len(amount), amount)
pp_str = "00020101021129370016A000000677010111"
+ pp_acc_id
+ "5303764"
+ pp_amount
+ "5802TH"
+ "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str

Python - print value to new file?

import sys
import pickle
import string
def Menu():
print ("\n***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def Loop():
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
user_File = ReadTextFile()
elif choice == 2:
DisplayCounts(user_File)
elif choice == 3:
DisplayStats(user_File)
elif choice == 4:
PrintStats(aDictionary)
else:
print ("Error.")
def ReadTextFile():
print "\n"
while True:
InputFile = input("Please enter a file name (NOTE: must have quotation marks around name and extension): ")
if (InputFile.lower().endswith('.txt')):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return InputFile
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def DisplayStats(InputFile):
print "\n"
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(InputFile, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def PrintStats(aDictionary):
print "\n"
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
Loop()
There's something with that last function that is really tripping me up. I keep getting errors. I know aDictionary is not defined but I do not even know what to define it as! Any of you guys have an idea? Thanks.
with open("some_file.txt","W") as f:
print >> f, "Something goes here!"
its hard to say without your errors. .. but you almost certainly need to have aDictionary defined
also probably something like
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
return dict(numbers=numCount,
comma=commaCount,
dot=dotCount,
line=lineCount,
word=wordCount)
result = DisplayCounts("someinput.txt")
print result

Categories

Resources