'Python exercise using try/except with continue [closed]
I can't figure out why my code doesn't work properly here, it seems to exit the for loop after the except: continue line. What do I do to fix this? (the code executes but the output is always -1 no matter what list/letter combination is fed so nothing is ever being added to the sum_total variable)
sample_list = [
'Black Mirror',
'Breaking Bad', #2
'Stranger Things', #6
'The Leftovers', #2
'How I Met Your Mother' #7 4.25
]
letter = 'e'
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += input_list.index(input_letter)
print(sum_total)
**except:
continue**
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
Solution 1:[1]
Here's fixed code:
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += i.index(input_letter)
print(sum_total)
except ValueError as e:
print(e)
print(f"No {input_letter} in {i}")
continue
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
Solution 2:[2]
Your code need to change like this
sample_list = [
'Black Mirror',
'Breaking Bad', #2
'Stranger Things', #6
'The Leftovers', #2
'How I Met Your Mother' #7 4.25
]
letter = 'e'
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += input_list.index(input_letter)
print(sum_total)
except:
continue
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
find_average_first_index(sample_list,letter)
errors:-
You need to add
tryandexceptlike this (if your code pattern is wrong you can see error messages; see: https://careerkarma.com/blog/python-break-and-continue/)try: sum_total += input_list.index(input_letter) print(sum_total) except: continuefind_average_first_index(sample_list,letter)run the code you need call function. (ref: https://www.w3schools.com/python/python_functions.asp)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | XOMA ZLOY |
| Solution 2 |
