-2

Im currently trying to print the variable div to a txt file I've created called "Calculations.txt"

import math
n = int(input("Enter a value for n: "))
k = int(input("Enter a value for k: "))

if k == n:
    print(1)
elif k == 1:
    print(n)
elif k > n:
    print(0)
else:
    a = math.factorial(n)
    b = math.factorial(k)
    c = math.factorial(n-k)
    div = a // (b * c)
    with open("output.txt", "w") as f: 
        f.write(str(div))

How would i write div to the txt file? Also I'm looking for short and sweet code because I'm relatively new to python. Thank you

Cyber Guy
  • 7
  • 3
  • 1
    "``Ignore the indentation``" - no, indentation is an important feature of Python. Different indentation of the same code can change the behavior of the program. Please fix it. – Mike Scotty Mar 19 '21 at 16:31
  • I cant and i have it indented on my computer thats not ths issue. I currently have to type this on my phone which is the best i can do but I will go over it and manually add spaces – Cyber Guy Mar 19 '21 at 16:32
  • `from math import comb` `print(comb(n,k)` – Chris Charley Mar 19 '21 at 16:32

2 Answers2

1

Instead of printing, add this to the end of your code:

with open("Calculations.txt", "w") as f:
    f.write(str(div))
Blackgaurd
  • 608
  • 6
  • 15
0

I think this should work:

 f = open("Calculations.txt", "w")
 f.write(str(div))
 f.close
HTTP402
  • 16
  • 2