CodeSolved

A comprehensive source of programming questions and exercises

Working with in -file numbers

Practice Easy 973/ Download 424 Views

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

3 Answers

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}")
Behcoder Download Python
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()
Mma123 Download Python
whit open ("number.txt" , "r")as file:
    adad = file.read()
    reaturn+=(sum (adad)/len[adad]
print(return)

Submit answer

Submitting answers is currently unavailable.

Related content

Detection using AI
×
×
Close