Working with in -file numbers
Write a program that reads the contents of a file called "numbers.txt" which includes integers and calculates the sum and average of the numbers inside it
Write a program that reads the contents of a file called "numbers.txt" which includes integers and calculates the sum and average of the numbers inside it
sum = 0
counter = 0
with open ("numbers.txt","r") as file:
for item in file:
sum += int(item)
counter += 1
avr = sum / (counter)
print(f"sum = {sum}")
print(f"average = {avr}")
def calculate_sum_and_average(filename):
with open(filename, 'r') as file:
numbers = [int(line.strip()) for line in file]
total = sum(numbers)
average = total / len(numbers) if numbers else 0
return total, average
total, average = calculate_sum_and_average("numbers.txt")
print("Sum:", total)
print("Average:", average)
def read_numbers_from_file(file_name):
"""محتویات فایل را خوانده و اعداد صحیح را برمیگرداند."""
try:
with open(file_name, 'r') as file:
# Read lines and convert to integers list
numbers = [int(line.strip()) for line in file if line.strip().isdigit() or (line.strip()[1:].isdigit() and line.strip()[0] == '-')]
return numbers
except FileNotFoundError:
print(f"فایل '{file_name}' پیدا نشد.")
return []
except ValueError:
print("خطا در تبدیل دادهها به عدد صحیح.")
return []
def calculate_sum_and_average(numbers):
"""مجموع و میانگین اعداد را محاسبه میکند."""
total = sum(numbers)
average = total / len(numbers) if numbers else 0
return total, average
def main():
file_name = "numbers.txt"
# Read numbers from the file
numbers = read_numbers_from_file(file_name)
if numbers:
# Calculate the sum and average
total, average = calculate_sum_and_average(numbers)
# View results
print(f"مجموع اعداد: {total}")
print(f"میانگین اعداد: {average:.2f}")
else:
print("هیچ عددی برای محاسبه وجود ندارد.")
# Implementation of the main function
if __name__ == "__main__":
main()
whit open ("number.txt" , "r")as file:
adad = file.read()
reaturn+=(sum (adad)/len[adad]
print(return)
Submitting answers is currently unavailable.
You must be logged in to access this section.
Login/Sign up If you don’t understand the exercise or can’t solve it for any reason, that’s completely
normal—don’t worry 😊
Try checking out easier exercises and reviewing different answers
submitted by others. Gradually, you can move on to more challenging exercises. Also, your answer
might be correct even if it’s different from others.