How to fix invalid syntax error in 'except ValueError'?

I am trying to write simple exception handling. However, it seems that I am doing something wrong.

def average(): TOTAL_VALUE = 0 FILE = open("Numbers.txt", 'r') for line in FILE: AMOUNT = float(line) TOTAL_VALUE += AMOUNT NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT print("the average of the numbers in 'Numbers.txt' is :", format(NUMBERS_AVERAGE, '.2f')) FILE.close() except ValueError,IOError as err: print(err) average() > line 14 > except ValueError as err: > ^ > SyntaxError: invalid syntax 
+6
source share
1 answer

There are two things here. First, to round off errors, you need parentheses:

 except (ValueError,IOError) as err: 

Secondly, you will need to try for this except line:

 def average(): try: TOTAL_VALUE = 0 FILE = open("Numbers.txt", 'r') for line in FILE: AMOUNT = float(line) TOTAL_VALUE += AMOUNT NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT print("the average of the numbers in 'Numbers.txt' is :", format(NUMBERS_AVERAGE, '.2f')) FILE.close() except (ValueError,IOError) as err: print(err) 

except cannot be used without try .

+7
source

Source: https://habr.com/ru/post/958338/


All Articles