gpt4 book ai didi

python - 我的 Python 3 文件代码没有附加或读取文件的权利

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:21 24 4
gpt4 key购买 nike

我编写了一个运行良好的计算器代码,但我需要将结果附加到文本文件和/或从文本文件中读取。我已经完成了大部分工作,但我遇到了一些需要帮助的错误- 当我追加结果时,它只打印“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()

最佳答案

您提示输入 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

关于python - 我的 Python 3 文件代码没有附加或读取文件的权利,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com