【问题标题】:random factors and exporting them in python随机因素并在 python 中导出它们
【发布时间】:2016-12-21 13:09:37
【问题描述】:

我被分配了一项任务,该任务要求我让用户输入数字,然后通过带有随机因子的公式运行。然后,用户应该可以选择将数据保存到文本文件中。到目前为止,我已经完成了任务,但是由于随机因素,我面临文本文件上的数据不一样的问题,我该如何克服呢?谢谢。

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 ()

【问题讨论】:

  • 你能修复你的缩进吗?
  • 你想要随机还是不随机?你想修复随机数吗?
  • @Jean-FrançoisFabre 随机数必须保留,但文本文件中的数字必须相同
  • 在这种情况下,只需执行一次random.uniform 并将结果存储在全局变量中。不要多次致电random.uniform
  • @Jean-FrançoisFabre 所以我会在 def 公式中的“打印”部分之前添加全局变量

标签: python math random


【解决方案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:

【讨论】:

  • 我想知道你是否可以帮助我完成一个我在 python 中做的更大的项目?
  • 什么样的帮助?
  • 我的问题和这个类似,但我想不出一种将它实现到我的代码中的方法。
  • 如果我可以将 python 文件发送给您,以便您查看并帮助我使其正常工作?
  • 你为什么不用你的代码发布问题。 SO 社区随时为您提供帮助。你只需要问正确的问题。
猜你喜欢
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多