简体   繁体   中英

My assignment is to Create a file with comma seperated random numbers. Write python code to sum and average of them. How to do this?

n = ("random_numbers", "r+")
a = int(input("How many number do want to input? Type 0 to exit:"))

sum = 0
count = 0
number = 0

for i in range(a):
    x = int(input("Enter a number:"))
    n.write(str(x) + str(','))
    sum = sum + number
    count += 1

average = sum/count

n.write('the sum of the numbers is' + sum)
n.write('the average of the numbers is' + average)
n.seek(0)
n.read()
n.close()

This code when it is run shows the error: AttributeError: 'tuple' object has no attribute 'write'

you can use random.sample to generate your random numbers:

import random

a = int(input("How many number do want to input?"))

with open('my_file.txt', 'w') as fp:
    my_numbers = random.sample(range(1000), a)
    fp.write(','.join(map(str, my_numbers)))
    fp.write( '\nthe sum of the numbers is ' + str(sum(my_numbers)))
    fp.write( '\nthe average of the numbers is ' + str(sum(my_numbers) / len(my_numbers)))

in the above example if you have a > 1000 this code will not work, another way to generate your random numbers is:

import random

a = int(input("How many number do want to input?"))

with open('my_file.txt', 'w') as fp:
    my_numbers = [random.randint(0, 1000) for _ in range(a)]
    fp.write(','.join(map(str, my_numbers)))
    fp.write( '\nthe sum of the numbers is ' + str(sum(my_numbers)))
    fp.write( '\nthe average of the numbers is ' + str(sum(my_numbers) / len(my_numbers)))

using random.randint

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM