我做了一个完全正常的计算器代码,但我需要将结果附加到文本文件和/或从文本文件中读取。我已经做了大部分但是我遇到了一些我需要帮助的错误 - 当我追加结果时,它只是打印“5.098.042.0 ...”它应该是这样打印
“5 + 3 = 8
7 * 3 = 43 ......“ 它确实在代码中显示它,但由于某种原因它只是在文本中打印结果 请帮助,任何建议将来保存工作或任何事情都将不胜感激,谢谢!
def menu():
print("\t1. Addition")
print("\t2. Substraction")
print("\t3. Multiplication")
print("\t4. Division")
print("\t5. Show")
print("\t6. Quit")
def option(min, max, exi):
option= -1
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
while (option < min) or (option > max):
print("\n\t>>> Error. Invalid option.")
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
return option
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
print("\n\t-> The result of " + str(num1) + " + " + str(num2) + "= ", answer)
return answer
def subs():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 - num2
print("\n\t-> The result of " + str(num1) + " - " + str(num2) + "= ", answer)
return answer
def mult():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
answer = num1 * num2
print("\n\t-> The result of " + str(num1) + " * " + str(num2) + "= ", answer)
return answer
def div():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
if num2 != 0:
answer = num1 / num2
print("\n\t-> The result of " + str(num1) + " / " + str(num2) + "= ", answer)
else:
print("\n\t>>> Error. Division by zero.")
answer= "Error. Division by zero."
return answer
def result(r):
print("\n\t The last result was" , r)
def ex():
print("Goodbye")
def main():
solution = 0
op= -1
while op != 6:
op = option(0, 6, 0)
if op == 1:
solution = str(add())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 2:
solution = str(subs())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 3:
solution = str(mult())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 4:
solution = str(div())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 5:
with open ("myResultt.txt","r") as f:
for line in f:
print(line)
else:
solution = ex()
with open ("myResultt.txt","r") as f:
f.close()
main()
答案 0 :(得分:1)
您在sum
等函数中提示操作数。如果您希望这些操作数出现在结果文件中,您必须将它们与答案一起返回,或者在函数本身中进行写入。例如,
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
result = "{} + {} = {}".format(num1, num2, answer)
print("\n\t-> The result of " + result)
with open ("myResultt.txt","a") as f:
f.write(result + "\n")
return answer