0

What is the best way to print the results of this math calculation to a document like .txt? What am i doing wrong?

def divide(x, y):
    return x / y

print("Menu.")
print("1.Offers")

while True:
    choice = input("Choose1(1): ")

    if choice in ('1'):
        num1 = float(input("Price: "))
        num2 = float(input("Surcharge: "))

        if choice == '1':
            print(num1, "/", num2, "==", divide(num1, num2))
        break
    else:
        print("Invalid Input")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
StudioMan
  • 55
  • 8
  • I edited the question to fix the code formatting, including the indenting. Just mentioning on the off chance I got it wrong. – wjandrea Dec 06 '20 at 22:27

2 Answers2

0

You simply do not write in a file.

Below the syntax to save your result.

def divide(x, y):
  return x / y

print("Menu.")
print("1.Offers")

while True:

  choice = input("Choose1(1): ")

  if choice in ('1'):
    num1 = float(input("Price: "))
    num2 = float(input("Surcharge: "))

    if choice == '1':
        print(str(num1)+"/"+str(num2)+"="+str(divide(num1, num2)))
        
        with open("output.txt", "w") as msg:
            msg.write(str(num1)+"/"+str(num2)+"="+str(divide(num1, num2)))
            msg.close()
    break
  else:
    print("Invalid Input")
Synthase
  • 5,849
  • 2
  • 12
  • 34
  • 2
    Btw you don't need the `msg.close()` when using `with open(...) as msg:` [link](https://stackoverflow.com/questions/1832528/is-close-necessary-when-using-iterator-on-a-python-file-object) – ssp Dec 06 '20 at 22:27
  • Thanks. You have a ref/link for that? I confess I tend to clean things up when I am not sure ;) – Synthase Dec 06 '20 at 22:28
  • 2
    @Synthase Ref: [Reading and Writing Files - Python Tutorial](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files): *"It is good practice to use the [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point."* – wjandrea Dec 06 '20 at 22:32
  • If you use `print(file=msg)`, you don't need to do manual string conversion and joining. `print(num1, "/", num2, "==", divide(num1, num2), file=msg)` – wjandrea Dec 06 '20 at 22:34
  • Thank you Synthase! – StudioMan Dec 06 '20 at 22:37
0

Try this:

with open("f.txt", 'w') as f:
    f.write(str(num1)+"/"+str(num2)+"="+str(divide(num1, num2)))