Im working on a finger exercise from Guttag Intro to computer science and programming using python, and Im working on the following finger exercise:
Finger Exercise: Implement a function that satisfies the specification def findAnEven(l): """Assumes l is a list of integers Returns the first even number in l Raises ValueError if l does not contain an even number"""
This is what I wrote so far, it get's the job done, but is definitely not what Guttag intended as an answer.
def isEven(l):
"""Assumes l is a list of integars
returns the first even number in list
raises an exception if no even number in list"""
for i in l:
if i % 2 == 0:
print i, " is the first even number in the list"
exit()
raise ValueError("No even numbers in list!")
I would highly appreciate any input on how professor Guttag intended the code to look. I'm assuming I should have used the try statement somewhere, and the using the exit statement is very crude in this context. Thanks in advance.
The issue with your code is the usage of exit()
. Generally return
will exit for you. To fix the code, just remove it:
def isEven(l):
for i in l:
if i % 2 == 0:
return i
raise ValueError("No even numbers in list!")