产生错误的输出

时间:2014-10-02 18:55:37

标签: python debugging

我正在尝试创建一个生成十个随机整数的Python程序  这会产生错误的输出

def main():

    nums = [5, 3, 7, 9]

    myfile = open('nums_file.txt','w')

    for num in nums:
        myfile.write(str(num) + '/n')

      myfile.close()
      print('File created')
main()



infile = open('nums_file.txt','r')
line = infile.readline()

while line != '':
    num = int(line)
    total += num
    nums.append(num)
    line = infile.readline()

print(nums)
print('Total of list is',total)

1 个答案:

答案 0 :(得分:0)

你似乎正在阅读一个比你需要的文件复杂得多的文件。如果你想阅读文件中的所有行,只需使用for line in infile,也可以在创建的文件中将每个num添加到一行,而不是单独行,这样你的文件实际上就像{{{ 1}}这会导致尝试使用5/n3/n7/n9/n投射错误。

num = int(line)

如果您只想要import random nums = [5, 3, 7, 9] with open('nums_file.txt','w') as f: for num in nums: f.write("{}\n".format(num)) with open('nums_file.txt') as in_file: # use with to automatically close your files nums = [] tot = 0 for line in in_file: num = int(line) tot += num nums.append(num) print(nums) print('Total of list is',tot) print ("Total of odd numbers = {}".format(sum(x for x in nums if x % 2))) print ("Total of even numbers = {}".format(sum(x for x in nums if not x % 2))) rnd_10 = random.sample(nums,10) # get 10 random numbers from the list 中的十个随机数,则可以将1 - 100传递给range

random.sample()