I'm trying to fix a script that's supposed to check if all numbers in a list are even. I can't add any lines, only modify existing ones, if I could add lines I know the solution. The problem is that the loop exits after checking the first number in the list.
def all_even(lst):
for i in range(len(lst)):
if lst[i] % 2 != 0:
return False
return True
Found other solutions but they add more lines which I can't because this is an assignment.
You can use Python's all()
function:
numbers = [1, 2, 3]
if all(number % 2 == 0 for number in numbers):
print("All numbers are even")
return True
else:
print("Not all numbers are even")
return False
Remove indentation for the last return so that it is executed out of the loop.
def all_even(lst):
for i in range(len(lst)):
if lst[i] % 2 != 0:
return False
return True
The indent int the last row makes your function abort the first time an even number is found. If you remove the indent your function will return False when it finds the first uneven number. Otherwise it loops over the whole list if it doesn't find an odd number and then it returns True. The return True statement has to be outside of the for loop.
def all_even(lst):
for i in range(len(lst)):
if lst[i] % 2 != 0:
return False
return True
You don't need to use range for this, because for loop in list will do the work.
def all_even(list):
for i in list:
if i % 2 != 0:
return False
return True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.