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 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.
Write a program that receives 2 numbers as the interval, in which the interval of all the 5 existing numbers. For example, in the interval of 1 to 20 the number 2 times the number 5 repeated (5 and 15)
Write a program that receives an email address and separates the various sections as follows and prints on the output example: email: [email protected] info amirhn.ir Example: email: [email protected] username gmail.com
Write a program that prints each student's name according to the list below, and as much as his / her name, the star of his name prints the question. Try to use the nested rings Amir 5hooshang 7rez ...
Write a function that receives infinite parameter and returns the average of numbers. If the parameter was non -extensive, it ignores it
برای استفاده از این بخش باید وارد حساب کاربریت بشی
ورود/ثبت نام 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.