如何确定用户输入是奇数还是偶数?

时间:2013-12-04 05:08:09

标签: python

我应该知道用户输入的所有5个数字是奇数还是偶数。它的输出应该如下所示:

>>> Enter 5 integers (e.g. 1 2 3 4 5): 1 2 3 4 5 
The array contains odd and even numbers. 

>>> Enter 5 integers (e.g. 1 2 3 4 5): 1 3 5 7 9 
The array contains only odd numbers.

>>> Enter 5 integers (e.g. 1 2 3 4 5): 2 4 6 8 0 
The array contains only even numbers.

这是我到目前为止所拥有的:

def main():
    numEnter = 5
    numbers = [0] * numEnter

    for index in range(numEnter):
        numbers[index] = int(input('Enter the numbers: '))
    print(numbers)

    if numbers % 2 == 0:
    print('The numbers are odd')

main()

我遇到了这段代码的问题。我似乎无法弄清楚如何查看数字是奇数还是偶数。

4 个答案:

答案 0 :(得分:2)

def oddOrEven(number):
    if ( (number % 2) == 0 ):
        print('The number is even')
    else:
        print('The number is odd')


numEnter = 5
numArray = [0] * numEnter

for index in range(numEnter):
    numArray[index] = int(raw_input('Enter an integer number: '))
    oddOrEven(numArray[index])

答案 1 :(得分:1)

使用循环:

numEnter = 5
numbers = [0] * numEnter

odd = False
even = False

for index in range(numEnter):
    numbers[index] = int(input('Enter the numbers: '))
print(numbers)

for i in numbers:
    if i % 2 == 0:
        even = True
        continue
    else:
        odd = True
        continue

if odd and even:
    print 'The array contains odd and even numbers.'
elif odd:
    print 'The array contains only odd numbers.'
elif even:
    print 'The array contains only even numbers'

如果输入[1, 2, 3, 4, 5]输出将是:

[1, 2, 3, 4, 5]
The array contains odd and even numbers.

答案 2 :(得分:0)

在python中,你必须在if语句后缩进代码。您的if numbers % 2 == 0:没有做任何事情。

答案 3 :(得分:0)

您可以将列表理解与一些内置函数一起使用:

numbers = []
numEnter = 5

for i in range(numEnter):
    numbers.append(int(input('Enter the numbers: ')))

results = [number % 2 in numbers]

if all(results):
    print('The array contains only odd numbers.')
elif any(results):
    print('The array contains odd and even numbers.')
else:
    print('The array contains only even numbers.')

列表理解表达式将创建包含模运算结果的新列表,如下所示:

[1, 1, 0, 1, 0]

Python将1和0分别视为True和False。因此,如果所有数字在模数(%)运算后都为1,则all()函数将返回true。如果至少有一个元素为1,则any()函数将返回true。因此,如果所有元素都为0,则看起来所有数字都是偶数。

此解决方案包含更多标准库函数的使用,这些函数具有更好的性能。