pythonpython-3.xvariablescalculatorbinomial-coefficients

Printing python variables to a txt file


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


Solution

  • I think this should work:

     f = open("Calculations.txt", "w")
     f.write(str(div))
     f.close