【发布时间】: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 公式中的“打印”部分之前添加全局变量