这是我到目前为止所拥有的。它一直有效,直到我添加了功能。我需要在代码中有两个功能,我不知道如何正确地工作并尝试了几种不同的方法。代码需要将X量的随机数写入文本文件。
import random
random_numbers = open('ran_numbers.txt', 'w')
def main():
getRandom()
writeFunction()
def getRandom():
qty_numbers = int(input('How many random numbers should be written to the file? '))
for count in range (qty_numbers):
number = random.randint(1,500)
def writeFunction():
random_numbers.write(str(number)+ '\n')
random_numbers.close()
print('Your list of random numbers have been written to the file named')
print('ran_numbers.txt')
main()
答案 0 :(得分:0)
改变这个:
random_numbers = open('ran_numbers.txt', 'w')
def main():
getRandom()
writeFunction()
def getRandom():
qty_numbers = int(input('How many random numbers should be written to the file? '))
for count in range (qty_numbers):
number = random.randint(1,500)
对此:
random_numbers = open('ran_numbers.txt', 'w')
def main():
getRandom()
def getRandom():
qty_numbers = int(input('How many random numbers should be written to the file? '))
for count in range (qty_numbers):
number = random.randint(1,500)
writeFunction(number)
因为,number是getRandom()函数的局部变量,所以要么直接写入该函数本身的文件,要么返回main函数中的数字并将其传递给writeFunction()
def main():
number= getRandom()
writeFunction(number)
您所做的是您的选择,但在一个区块中定义数字不起作用。
答案 1 :(得分:0)
在创建随机数
之后,永远不会调用writeFunction()只需改变:
for count in range (qty_numbers):
number = random.randint(1,500)
到此:
for count in range (qty_numbers):
number = random.randint(1,500)
writeFunction(number)
并更改行:
def writeFunction():
为:
def writeFunction(number):
最后将main()更改为:
def main():
getRandom()
random_numbers.close()
并删除
random_numbers.close()
来自writeFunction()的
我希望这会对你有所帮助。
答案 2 :(得分:0)
我认为你只需要有一个生成的数字列表并将它们传递给file_writer。以下是我对您的代码所做的更改:
import random
def main():
random_result = getRandom()
writeFunction(random_result)
def getRandom():
qty_numbers = int(input('How many random numbers should be written to the file? '))
res = []
for count in range (qty_numbers):
res.append(random.randint(1,500))
return res
def writeFunction(random_numbers_list):
random_numbers = open('ran_numbers.txt', 'w')
for number in random_numbers_list:
random_numbers.write(str(number)+ '\n')
random_numbers.close()
print('Your list of random numbers have been written to the file named')
print('ran_numbers.txt')
main()
答案 3 :(得分:0)
如果你必须有两个功能,那么这将是一个更好的解决方案。将随机数放在列表中,然后将其传递给writeFunction函数。
import random
random_numbers = open('ran_numbers.txt', 'w')
def main():
writeFunction(getRandom())
def getRandom():
qty_numbers = int(input('How many random numbers should be written to the file? '))
nums = []
for count in range (qty_numbers):
nums.append(random.randint(1,500))
return nums
def writeFunction(a_list):
random_nums = '\n'.join([str(x) for x in a_list])
random_numbers.write(random_nums)
random_numbers.close()
print('Your list of random numbers have been written to the file named')
print('ran_numbers.txt')
main()