Reputation: 23
I am struggling in a college beginner's computer science course and just need simple homework help.
Now, we are currently working on function definitions, and I have to write a program that reads a list of integers, and outputs whether the list contains all even numbers, odd numbers, or neither. The input begins with an integer indicating the number of integers in the list. The first integer is not in the list (it just tells the length of the list).
My program must define and call the following two functions. def is_list_even()
returns true if all integers in the list are even and false otherwise. def is_list_odd()
returns true if all integers in the list are odd and false otherwise. If the list is all even I also have to print 'all even'. If the list is odd, I must print 'all odd'. If the list has both, I must print 'not even or odd'.
I have been able to get all of the integers I need into the list, however the definitions are what I am struggling with (formatting, returning it, etc.). I have pasted the code I have so far below (this website has changed the format of it) but my program produces no output. Any help would be appreciated. Thank you.
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def IsListEven(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 0:
return True
else:
return False
def IsListOdd(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 1:
return True
else:
return False
def GetUserValues():
if IsListOdd(my_list) == True:
print("all odd")
elif IsListEven(my_list) == True:
print("all Even")
else:
print("not even or odd")
Upvotes: -2
Views: 13262
Reputation: 22255
You're definitely on the right track! Consider simplifying the logic in your for loops by using comprehensions and the all
function. Also, avoid using Hungarian notation in Python and aim to code to abstractions, such as collections.abc.Sequence
, for better flexibility and readability:
from collections.abc import Sequence
from typed_input import int_input # pip install typed_input
def are_all_even(numbers: Sequence[int]) -> bool:
return all(x % 2 == 0 for x in numbers)
def are_all_odd(numbers: Sequence[int]) -> bool:
return all(x % 2 != 0 for x in numbers)
def main() -> None:
num_elements = int_input('Enter the number of elements: ')
elements = [
int_input(f'Enter element {i + 1}: ') for i in range(num_elements)
]
print('Input sequence:', elements)
if are_all_even(elements):
print('All elements are even.')
elif are_all_odd(elements):
print('All elements are odd.')
else:
print('Mix of evens and odds.')
if __name__ == '__main__':
main()
Example Usage 1:
Enter the number of elements: 5
Enter element 1: 1
Enter element 2: 5
Enter element 3: 9
Enter element 4: 7
Enter element 5: 1
[1, 5, 9, 7, 1]
All elements are odd.
Example Usage 2:
Enter the number of elements: 3
Enter element 1: 2
Enter element 2: 4
Enter element 3: 8
[2, 4, 8]
All elements are even.
Example Usage 3:
Enter the number of elements: 4
Enter element 1: 1
Enter element 2: a
Error: You must enter a valid integer.
Enter element 2: 2
Enter element 3: 5
Enter element 4: 7
[1, 2, 5, 7]
Mix of evens and odds.
Upvotes: 1
Reputation: 346
Use a flag to check if all the values satisfy the condition. Example :
def IsListEven(my_list):
answer = True
for i in range(len(my_list)):
if my_list[i] % 2 == 0: # As pointed in comment, use != for isEven
answer = False
break
return answer
Upvotes: 2
Reputation: 15470
return
will immediately break the loop, so use a holding boolean variable like:
def IsListEven(my_list):
allEven = True
for i in range(len(my_list)):
if my_list[i] % 2 != 0:
allEven = False
return allEven
def IsListOdd(my_list):
allOdd = True
for i in range(len(my_list)):
if my_list[i] % 2 != 1:
allOdd = False
return allOdd
def GetUserValues():
if IsListOdd(my_list) == True:
print("all odd")
elif IsListEven(my_list) == True:
print("all Even")
But your functions can be one liner if you use all()
, an example to check if all is odd
my_list = [1,3,5]
print(all(x % 2 == 1 for x in my_list))
Upvotes: 1
Reputation: 628
There is one major logical error, and a few minor syntactical fixes.
Currently, the IsListEven()
and IsListOdd()
functions will immediately return when they find an even or odd element, respectively. This leads to lists being marked as "even" even if only the very first element is even (and vice versa). One way this can be solved is by returning false when the opposite is found, and true if not:
def IsListEven(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 1:
return False
return True
and
def IsListOdd(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 0:
return False
return True
More explicitly, this can be defined with a for-else
statement (although not completely necessary here):
def IsListEven(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 0:
return False
else:
return True
In terms of syntax, there isn't much of a reason to use list indexing within the for loops. A simpler method is to access the numbers directly:
def IsListEven(my_list):
for i in my_list:
if i % 2 == 1:
return False
else:
return True
Additionally, the final checks can be simplified because the returned values are booleans:
if IsListOdd(my_list):
print("all odd")
elif IsListEven(my_list):
print("all Even")
else:
print("not even or odd")
Upvotes: 1