随机因素并在python中导出它们

时间:2016-12-21 13:09:37

标签: python math random

我被分配了一个任务,要求我有一个用户输入数字,然后通过随机因素运行公式。然后,用户应该可以选择将数据保存到文本文件中。到目前为止,我已经完成了任务,但由于随机因素,我面临着文本文件中数据不一致的问题,我怎么能超过这个?感谢。

import random
import os.path
def main ():
    print ("1.input numbers")
    print ("2.run formula")
print ("3.export data")
maininput = int(input("Enter:"))
if maininput == 1:
    number ()
elif maininput == 2:
    formula ()
elif maininput == 3:
    file_check ()
elif maininput >3:
    print ("invalid number")
    return main ()

def number ():
    number.n1 = int(input("first number:"))
    number.n2 = int(input("second number:"))
    main()

def formula ():
    randomfactor = random.uniform (0.8 ,0.5)
    output = number.n1 * number.n2 * randomfactor
    print (" answer:",round (output))
    main()

def file_check ():
    file_check.file_name = input("What would you like to name the file?")
    if os.path.exists (file_check.file_name):
        print ("A file with the same name already exists")
        print ("Press 1 to overwrite")
        print ("Press 2 to choose a new file name")
        option = int(input("Enter:  "))
        if option ==1:
            export()
        elif option ==2:
            return file_check()
        elif option >2:
            return file_check()
    if not os.path.exists(file_check.file_name):
        export()

def export ():
    file = open (file_check.file_name,"w")
    randomfactor = random.uniform (0.8 ,0.5)
    output = number.n1 * number.n2 * randomfactor
    exout = round (output)
    file.write ("number:" + str(exout)+ '\n')
    file.close
    main ()




main ()

1 个答案:

答案 0 :(得分:1)

您生成两次随机数。因此,您可以将结果存储在formula.output

def formula ():
    randomfactor = random.uniform (0.8 ,0.5)
    formula.output = number.n1 * number.n2 * randomfactor
    print (" answer:",round (output))
    main()

然后使用此结果写入您的文件:

def export ():
    file = open (file_check.file_name,"w")
    exout = round (formula.output)
    file.write ("number:" + str(exout)+ '\n')
    file.close
    main ()

顺便说一下。您可以将if not os.path.exists(file_check.file_name):更改为else: